babylon.no-module.max.js 5.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007
  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. /**
  5782. * Unproject from screen space to object space
  5783. * @param source defines the screen space Vector3 to use
  5784. * @param viewportWidth defines the current width of the viewport
  5785. * @param viewportHeight defines the current height of the viewport
  5786. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5787. * @param transform defines the transform (view x projection) matrix to use
  5788. * @returns the new Vector3
  5789. */
  5790. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  5791. var matrix = MathTmp.Matrix[0];
  5792. world.multiplyToRef(transform, matrix);
  5793. matrix.invert();
  5794. source.x = source.x / viewportWidth * 2 - 1;
  5795. source.y = -(source.y / viewportHeight * 2 - 1);
  5796. var vector = Vector3.TransformCoordinates(source, matrix);
  5797. var m = matrix.m;
  5798. var num = source.x * m[3] + source.y * m[7] + source.z * m[11] + m[15];
  5799. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  5800. vector = vector.scale(1.0 / num);
  5801. }
  5802. return vector;
  5803. };
  5804. /**
  5805. * Unproject from screen space to object space
  5806. * @param source defines the screen space Vector3 to use
  5807. * @param viewportWidth defines the current width of the viewport
  5808. * @param viewportHeight defines the current height of the viewport
  5809. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5810. * @param view defines the view matrix to use
  5811. * @param projection defines the projection matrix to use
  5812. * @returns the new Vector3
  5813. */
  5814. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  5815. var result = Vector3.Zero();
  5816. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  5817. return result;
  5818. };
  5819. /**
  5820. * Unproject from screen space to object space
  5821. * @param source defines the screen space Vector3 to use
  5822. * @param viewportWidth defines the current width of the viewport
  5823. * @param viewportHeight defines the current height of the viewport
  5824. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5825. * @param view defines the view matrix to use
  5826. * @param projection defines the projection matrix to use
  5827. * @param result defines the Vector3 where to store the result
  5828. */
  5829. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  5830. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  5831. };
  5832. /**
  5833. * Unproject from screen space to object space
  5834. * @param sourceX defines the screen space x coordinate to use
  5835. * @param sourceY defines the screen space y coordinate to use
  5836. * @param sourceZ defines the screen space z coordinate to use
  5837. * @param viewportWidth defines the current width of the viewport
  5838. * @param viewportHeight defines the current height of the viewport
  5839. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5840. * @param view defines the view matrix to use
  5841. * @param projection defines the projection matrix to use
  5842. * @param result defines the Vector3 where to store the result
  5843. */
  5844. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  5845. var matrix = MathTmp.Matrix[0];
  5846. world.multiplyToRef(view, matrix);
  5847. matrix.multiplyToRef(projection, matrix);
  5848. matrix.invert();
  5849. var screenSource = MathTmp.Vector3[0];
  5850. screenSource.x = sourceX / viewportWidth * 2 - 1;
  5851. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  5852. screenSource.z = 2 * sourceZ - 1.0;
  5853. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  5854. var m = matrix.m;
  5855. var num = screenSource.x * m[3] + screenSource.y * m[7] + screenSource.z * m[11] + m[15];
  5856. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  5857. result.scaleInPlace(1.0 / num);
  5858. }
  5859. };
  5860. /**
  5861. * Gets the minimal coordinate values between two Vector3
  5862. * @param left defines the first operand
  5863. * @param right defines the second operand
  5864. * @returns the new Vector3
  5865. */
  5866. Vector3.Minimize = function (left, right) {
  5867. var min = left.clone();
  5868. min.minimizeInPlace(right);
  5869. return min;
  5870. };
  5871. /**
  5872. * Gets the maximal coordinate values between two Vector3
  5873. * @param left defines the first operand
  5874. * @param right defines the second operand
  5875. * @returns the new Vector3
  5876. */
  5877. Vector3.Maximize = function (left, right) {
  5878. var max = left.clone();
  5879. max.maximizeInPlace(right);
  5880. return max;
  5881. };
  5882. /**
  5883. * Returns the distance between the vectors "value1" and "value2"
  5884. * @param value1 defines the first operand
  5885. * @param value2 defines the second operand
  5886. * @returns the distance
  5887. */
  5888. Vector3.Distance = function (value1, value2) {
  5889. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  5890. };
  5891. /**
  5892. * Returns the squared distance between the vectors "value1" and "value2"
  5893. * @param value1 defines the first operand
  5894. * @param value2 defines the second operand
  5895. * @returns the squared distance
  5896. */
  5897. Vector3.DistanceSquared = function (value1, value2) {
  5898. var x = value1.x - value2.x;
  5899. var y = value1.y - value2.y;
  5900. var z = value1.z - value2.z;
  5901. return (x * x) + (y * y) + (z * z);
  5902. };
  5903. /**
  5904. * Returns a new Vector3 located at the center between "value1" and "value2"
  5905. * @param value1 defines the first operand
  5906. * @param value2 defines the second operand
  5907. * @returns the new Vector3
  5908. */
  5909. Vector3.Center = function (value1, value2) {
  5910. var center = value1.add(value2);
  5911. center.scaleInPlace(0.5);
  5912. return center;
  5913. };
  5914. /**
  5915. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  5916. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  5917. * to something in order to rotate it from its local system to the given target system
  5918. * Note: axis1, axis2 and axis3 are normalized during this operation
  5919. * @param axis1 defines the first axis
  5920. * @param axis2 defines the second axis
  5921. * @param axis3 defines the third axis
  5922. * @returns a new Vector3
  5923. */
  5924. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  5925. var rotation = Vector3.Zero();
  5926. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  5927. return rotation;
  5928. };
  5929. /**
  5930. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  5931. * @param axis1 defines the first axis
  5932. * @param axis2 defines the second axis
  5933. * @param axis3 defines the third axis
  5934. * @param ref defines the Vector3 where to store the result
  5935. */
  5936. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5937. var quat = MathTmp.Quaternion[0];
  5938. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5939. quat.toEulerAnglesToRef(ref);
  5940. };
  5941. return Vector3;
  5942. }());
  5943. BABYLON.Vector3 = Vector3;
  5944. /**
  5945. * Vector4 class created for EulerAngle class conversion to Quaternion
  5946. */
  5947. var Vector4 = /** @class */ (function () {
  5948. /**
  5949. * Creates a Vector4 object from the given floats.
  5950. * @param x x value of the vector
  5951. * @param y y value of the vector
  5952. * @param z z value of the vector
  5953. * @param w w value of the vector
  5954. */
  5955. function Vector4(
  5956. /** x value of the vector */
  5957. x,
  5958. /** y value of the vector */
  5959. y,
  5960. /** z value of the vector */
  5961. z,
  5962. /** w value of the vector */
  5963. w) {
  5964. this.x = x;
  5965. this.y = y;
  5966. this.z = z;
  5967. this.w = w;
  5968. }
  5969. /**
  5970. * Returns the string with the Vector4 coordinates.
  5971. * @returns a string containing all the vector values
  5972. */
  5973. Vector4.prototype.toString = function () {
  5974. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  5975. };
  5976. /**
  5977. * Returns the string "Vector4".
  5978. * @returns "Vector4"
  5979. */
  5980. Vector4.prototype.getClassName = function () {
  5981. return "Vector4";
  5982. };
  5983. /**
  5984. * Returns the Vector4 hash code.
  5985. * @returns a unique hash code
  5986. */
  5987. Vector4.prototype.getHashCode = function () {
  5988. var hash = this.x || 0;
  5989. hash = (hash * 397) ^ (this.y || 0);
  5990. hash = (hash * 397) ^ (this.z || 0);
  5991. hash = (hash * 397) ^ (this.w || 0);
  5992. return hash;
  5993. };
  5994. // Operators
  5995. /**
  5996. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  5997. * @returns the resulting array
  5998. */
  5999. Vector4.prototype.asArray = function () {
  6000. var result = new Array();
  6001. this.toArray(result, 0);
  6002. return result;
  6003. };
  6004. /**
  6005. * Populates the given array from the given index with the Vector4 coordinates.
  6006. * @param array array to populate
  6007. * @param index index of the array to start at (default: 0)
  6008. * @returns the Vector4.
  6009. */
  6010. Vector4.prototype.toArray = function (array, index) {
  6011. if (index === undefined) {
  6012. index = 0;
  6013. }
  6014. array[index] = this.x;
  6015. array[index + 1] = this.y;
  6016. array[index + 2] = this.z;
  6017. array[index + 3] = this.w;
  6018. return this;
  6019. };
  6020. /**
  6021. * Adds the given vector to the current Vector4.
  6022. * @param otherVector the vector to add
  6023. * @returns the updated Vector4.
  6024. */
  6025. Vector4.prototype.addInPlace = function (otherVector) {
  6026. this.x += otherVector.x;
  6027. this.y += otherVector.y;
  6028. this.z += otherVector.z;
  6029. this.w += otherVector.w;
  6030. return this;
  6031. };
  6032. /**
  6033. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  6034. * @param otherVector the vector to add
  6035. * @returns the resulting vector
  6036. */
  6037. Vector4.prototype.add = function (otherVector) {
  6038. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  6039. };
  6040. /**
  6041. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  6042. * @param otherVector the vector to add
  6043. * @param result the vector to store the result
  6044. * @returns the current Vector4.
  6045. */
  6046. Vector4.prototype.addToRef = function (otherVector, result) {
  6047. result.x = this.x + otherVector.x;
  6048. result.y = this.y + otherVector.y;
  6049. result.z = this.z + otherVector.z;
  6050. result.w = this.w + otherVector.w;
  6051. return this;
  6052. };
  6053. /**
  6054. * Subtract in place the given vector from the current Vector4.
  6055. * @param otherVector the vector to subtract
  6056. * @returns the updated Vector4.
  6057. */
  6058. Vector4.prototype.subtractInPlace = function (otherVector) {
  6059. this.x -= otherVector.x;
  6060. this.y -= otherVector.y;
  6061. this.z -= otherVector.z;
  6062. this.w -= otherVector.w;
  6063. return this;
  6064. };
  6065. /**
  6066. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  6067. * @param otherVector the vector to add
  6068. * @returns the new vector with the result
  6069. */
  6070. Vector4.prototype.subtract = function (otherVector) {
  6071. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  6072. };
  6073. /**
  6074. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  6075. * @param otherVector the vector to subtract
  6076. * @param result the vector to store the result
  6077. * @returns the current Vector4.
  6078. */
  6079. Vector4.prototype.subtractToRef = function (otherVector, result) {
  6080. result.x = this.x - otherVector.x;
  6081. result.y = this.y - otherVector.y;
  6082. result.z = this.z - otherVector.z;
  6083. result.w = this.w - otherVector.w;
  6084. return this;
  6085. };
  6086. /**
  6087. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6088. */
  6089. /**
  6090. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6091. * @param x value to subtract
  6092. * @param y value to subtract
  6093. * @param z value to subtract
  6094. * @param w value to subtract
  6095. * @returns new vector containing the result
  6096. */
  6097. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  6098. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  6099. };
  6100. /**
  6101. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6102. * @param x value to subtract
  6103. * @param y value to subtract
  6104. * @param z value to subtract
  6105. * @param w value to subtract
  6106. * @param result the vector to store the result in
  6107. * @returns the current Vector4.
  6108. */
  6109. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  6110. result.x = this.x - x;
  6111. result.y = this.y - y;
  6112. result.z = this.z - z;
  6113. result.w = this.w - w;
  6114. return this;
  6115. };
  6116. /**
  6117. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  6118. * @returns a new vector with the negated values
  6119. */
  6120. Vector4.prototype.negate = function () {
  6121. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  6122. };
  6123. /**
  6124. * Multiplies the current Vector4 coordinates by scale (float).
  6125. * @param scale the number to scale with
  6126. * @returns the updated Vector4.
  6127. */
  6128. Vector4.prototype.scaleInPlace = function (scale) {
  6129. this.x *= scale;
  6130. this.y *= scale;
  6131. this.z *= scale;
  6132. this.w *= scale;
  6133. return this;
  6134. };
  6135. /**
  6136. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  6137. * @param scale the number to scale with
  6138. * @returns a new vector with the result
  6139. */
  6140. Vector4.prototype.scale = function (scale) {
  6141. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  6142. };
  6143. /**
  6144. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  6145. * @param scale the number to scale with
  6146. * @param result a vector to store the result in
  6147. * @returns the current Vector4.
  6148. */
  6149. Vector4.prototype.scaleToRef = function (scale, result) {
  6150. result.x = this.x * scale;
  6151. result.y = this.y * scale;
  6152. result.z = this.z * scale;
  6153. result.w = this.w * scale;
  6154. return this;
  6155. };
  6156. /**
  6157. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  6158. * @param scale defines the scale factor
  6159. * @param result defines the Vector4 object where to store the result
  6160. * @returns the unmodified current Vector4
  6161. */
  6162. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  6163. result.x += this.x * scale;
  6164. result.y += this.y * scale;
  6165. result.z += this.z * scale;
  6166. result.w += this.w * scale;
  6167. return this;
  6168. };
  6169. /**
  6170. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  6171. * @param otherVector the vector to compare against
  6172. * @returns true if they are equal
  6173. */
  6174. Vector4.prototype.equals = function (otherVector) {
  6175. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  6176. };
  6177. /**
  6178. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  6179. * @param otherVector vector to compare against
  6180. * @param epsilon (Default: very small number)
  6181. * @returns true if they are equal
  6182. */
  6183. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  6184. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  6185. return otherVector
  6186. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  6187. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  6188. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  6189. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  6190. };
  6191. /**
  6192. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  6193. * @param x x value to compare against
  6194. * @param y y value to compare against
  6195. * @param z z value to compare against
  6196. * @param w w value to compare against
  6197. * @returns true if equal
  6198. */
  6199. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  6200. return this.x === x && this.y === y && this.z === z && this.w === w;
  6201. };
  6202. /**
  6203. * Multiplies in place the current Vector4 by the given one.
  6204. * @param otherVector vector to multiple with
  6205. * @returns the updated Vector4.
  6206. */
  6207. Vector4.prototype.multiplyInPlace = function (otherVector) {
  6208. this.x *= otherVector.x;
  6209. this.y *= otherVector.y;
  6210. this.z *= otherVector.z;
  6211. this.w *= otherVector.w;
  6212. return this;
  6213. };
  6214. /**
  6215. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  6216. * @param otherVector vector to multiple with
  6217. * @returns resulting new vector
  6218. */
  6219. Vector4.prototype.multiply = function (otherVector) {
  6220. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  6221. };
  6222. /**
  6223. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  6224. * @param otherVector vector to multiple with
  6225. * @param result vector to store the result
  6226. * @returns the current Vector4.
  6227. */
  6228. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  6229. result.x = this.x * otherVector.x;
  6230. result.y = this.y * otherVector.y;
  6231. result.z = this.z * otherVector.z;
  6232. result.w = this.w * otherVector.w;
  6233. return this;
  6234. };
  6235. /**
  6236. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  6237. * @param x x value multiply with
  6238. * @param y y value multiply with
  6239. * @param z z value multiply with
  6240. * @param w w value multiply with
  6241. * @returns resulting new vector
  6242. */
  6243. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  6244. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  6245. };
  6246. /**
  6247. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  6248. * @param otherVector vector to devide with
  6249. * @returns resulting new vector
  6250. */
  6251. Vector4.prototype.divide = function (otherVector) {
  6252. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  6253. };
  6254. /**
  6255. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  6256. * @param otherVector vector to devide with
  6257. * @param result vector to store the result
  6258. * @returns the current Vector4.
  6259. */
  6260. Vector4.prototype.divideToRef = function (otherVector, result) {
  6261. result.x = this.x / otherVector.x;
  6262. result.y = this.y / otherVector.y;
  6263. result.z = this.z / otherVector.z;
  6264. result.w = this.w / otherVector.w;
  6265. return this;
  6266. };
  6267. /**
  6268. * Divides the current Vector3 coordinates by the given ones.
  6269. * @param otherVector vector to devide with
  6270. * @returns the updated Vector3.
  6271. */
  6272. Vector4.prototype.divideInPlace = function (otherVector) {
  6273. return this.divideToRef(otherVector, this);
  6274. };
  6275. /**
  6276. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  6277. * @param other defines the second operand
  6278. * @returns the current updated Vector4
  6279. */
  6280. Vector4.prototype.minimizeInPlace = function (other) {
  6281. if (other.x < this.x) {
  6282. this.x = other.x;
  6283. }
  6284. if (other.y < this.y) {
  6285. this.y = other.y;
  6286. }
  6287. if (other.z < this.z) {
  6288. this.z = other.z;
  6289. }
  6290. if (other.w < this.w) {
  6291. this.w = other.w;
  6292. }
  6293. return this;
  6294. };
  6295. /**
  6296. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  6297. * @param other defines the second operand
  6298. * @returns the current updated Vector4
  6299. */
  6300. Vector4.prototype.maximizeInPlace = function (other) {
  6301. if (other.x > this.x) {
  6302. this.x = other.x;
  6303. }
  6304. if (other.y > this.y) {
  6305. this.y = other.y;
  6306. }
  6307. if (other.z > this.z) {
  6308. this.z = other.z;
  6309. }
  6310. if (other.w > this.w) {
  6311. this.w = other.w;
  6312. }
  6313. return this;
  6314. };
  6315. /**
  6316. * Gets a new Vector4 from current Vector4 floored values
  6317. * @returns a new Vector4
  6318. */
  6319. Vector4.prototype.floor = function () {
  6320. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  6321. };
  6322. /**
  6323. * Gets a new Vector4 from current Vector3 floored values
  6324. * @returns a new Vector4
  6325. */
  6326. Vector4.prototype.fract = function () {
  6327. 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));
  6328. };
  6329. // Properties
  6330. /**
  6331. * Returns the Vector4 length (float).
  6332. * @returns the length
  6333. */
  6334. Vector4.prototype.length = function () {
  6335. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6336. };
  6337. /**
  6338. * Returns the Vector4 squared length (float).
  6339. * @returns the length squared
  6340. */
  6341. Vector4.prototype.lengthSquared = function () {
  6342. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6343. };
  6344. // Methods
  6345. /**
  6346. * Normalizes in place the Vector4.
  6347. * @returns the updated Vector4.
  6348. */
  6349. Vector4.prototype.normalize = function () {
  6350. var len = this.length();
  6351. if (len === 0) {
  6352. return this;
  6353. }
  6354. return this.scaleInPlace(1.0 / len);
  6355. };
  6356. /**
  6357. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  6358. * @returns this converted to a new vector3
  6359. */
  6360. Vector4.prototype.toVector3 = function () {
  6361. return new Vector3(this.x, this.y, this.z);
  6362. };
  6363. /**
  6364. * Returns a new Vector4 copied from the current one.
  6365. * @returns the new cloned vector
  6366. */
  6367. Vector4.prototype.clone = function () {
  6368. return new Vector4(this.x, this.y, this.z, this.w);
  6369. };
  6370. /**
  6371. * Updates the current Vector4 with the given one coordinates.
  6372. * @param source the source vector to copy from
  6373. * @returns the updated Vector4.
  6374. */
  6375. Vector4.prototype.copyFrom = function (source) {
  6376. this.x = source.x;
  6377. this.y = source.y;
  6378. this.z = source.z;
  6379. this.w = source.w;
  6380. return this;
  6381. };
  6382. /**
  6383. * Updates the current Vector4 coordinates with the given floats.
  6384. * @param x float to copy from
  6385. * @param y float to copy from
  6386. * @param z float to copy from
  6387. * @param w float to copy from
  6388. * @returns the updated Vector4.
  6389. */
  6390. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  6391. this.x = x;
  6392. this.y = y;
  6393. this.z = z;
  6394. this.w = w;
  6395. return this;
  6396. };
  6397. /**
  6398. * Updates the current Vector4 coordinates with the given floats.
  6399. * @param x float to set from
  6400. * @param y float to set from
  6401. * @param z float to set from
  6402. * @param w float to set from
  6403. * @returns the updated Vector4.
  6404. */
  6405. Vector4.prototype.set = function (x, y, z, w) {
  6406. return this.copyFromFloats(x, y, z, w);
  6407. };
  6408. /**
  6409. * Copies the given float to the current Vector3 coordinates
  6410. * @param v defines the x, y, z and w coordinates of the operand
  6411. * @returns the current updated Vector3
  6412. */
  6413. Vector4.prototype.setAll = function (v) {
  6414. this.x = this.y = this.z = this.w = v;
  6415. return this;
  6416. };
  6417. // Statics
  6418. /**
  6419. * Returns a new Vector4 set from the starting index of the given array.
  6420. * @param array the array to pull values from
  6421. * @param offset the offset into the array to start at
  6422. * @returns the new vector
  6423. */
  6424. Vector4.FromArray = function (array, offset) {
  6425. if (!offset) {
  6426. offset = 0;
  6427. }
  6428. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  6429. };
  6430. /**
  6431. * Updates the given vector "result" from the starting index of the given array.
  6432. * @param array the array to pull values from
  6433. * @param offset the offset into the array to start at
  6434. * @param result the vector to store the result in
  6435. */
  6436. Vector4.FromArrayToRef = function (array, offset, result) {
  6437. result.x = array[offset];
  6438. result.y = array[offset + 1];
  6439. result.z = array[offset + 2];
  6440. result.w = array[offset + 3];
  6441. };
  6442. /**
  6443. * Updates the given vector "result" from the starting index of the given Float32Array.
  6444. * @param array the array to pull values from
  6445. * @param offset the offset into the array to start at
  6446. * @param result the vector to store the result in
  6447. */
  6448. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  6449. Vector4.FromArrayToRef(array, offset, result);
  6450. };
  6451. /**
  6452. * Updates the given vector "result" coordinates from the given floats.
  6453. * @param x float to set from
  6454. * @param y float to set from
  6455. * @param z float to set from
  6456. * @param w float to set from
  6457. * @param result the vector to the floats in
  6458. */
  6459. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  6460. result.x = x;
  6461. result.y = y;
  6462. result.z = z;
  6463. result.w = w;
  6464. };
  6465. /**
  6466. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  6467. * @returns the new vector
  6468. */
  6469. Vector4.Zero = function () {
  6470. return new Vector4(0.0, 0.0, 0.0, 0.0);
  6471. };
  6472. /**
  6473. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  6474. * @returns the new vector
  6475. */
  6476. Vector4.One = function () {
  6477. return new Vector4(1.0, 1.0, 1.0, 1.0);
  6478. };
  6479. /**
  6480. * Returns a new normalized Vector4 from the given one.
  6481. * @param vector the vector to normalize
  6482. * @returns the vector
  6483. */
  6484. Vector4.Normalize = function (vector) {
  6485. var result = Vector4.Zero();
  6486. Vector4.NormalizeToRef(vector, result);
  6487. return result;
  6488. };
  6489. /**
  6490. * Updates the given vector "result" from the normalization of the given one.
  6491. * @param vector the vector to normalize
  6492. * @param result the vector to store the result in
  6493. */
  6494. Vector4.NormalizeToRef = function (vector, result) {
  6495. result.copyFrom(vector);
  6496. result.normalize();
  6497. };
  6498. /**
  6499. * Returns a vector with the minimum values from the left and right vectors
  6500. * @param left left vector to minimize
  6501. * @param right right vector to minimize
  6502. * @returns a new vector with the minimum of the left and right vector values
  6503. */
  6504. Vector4.Minimize = function (left, right) {
  6505. var min = left.clone();
  6506. min.minimizeInPlace(right);
  6507. return min;
  6508. };
  6509. /**
  6510. * Returns a vector with the maximum values from the left and right vectors
  6511. * @param left left vector to maximize
  6512. * @param right right vector to maximize
  6513. * @returns a new vector with the maximum of the left and right vector values
  6514. */
  6515. Vector4.Maximize = function (left, right) {
  6516. var max = left.clone();
  6517. max.maximizeInPlace(right);
  6518. return max;
  6519. };
  6520. /**
  6521. * Returns the distance (float) between the vectors "value1" and "value2".
  6522. * @param value1 value to calulate the distance between
  6523. * @param value2 value to calulate the distance between
  6524. * @return the distance between the two vectors
  6525. */
  6526. Vector4.Distance = function (value1, value2) {
  6527. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  6528. };
  6529. /**
  6530. * Returns the squared distance (float) between the vectors "value1" and "value2".
  6531. * @param value1 value to calulate the distance between
  6532. * @param value2 value to calulate the distance between
  6533. * @return the distance between the two vectors squared
  6534. */
  6535. Vector4.DistanceSquared = function (value1, value2) {
  6536. var x = value1.x - value2.x;
  6537. var y = value1.y - value2.y;
  6538. var z = value1.z - value2.z;
  6539. var w = value1.w - value2.w;
  6540. return (x * x) + (y * y) + (z * z) + (w * w);
  6541. };
  6542. /**
  6543. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  6544. * @param value1 value to calulate the center between
  6545. * @param value2 value to calulate the center between
  6546. * @return the center between the two vectors
  6547. */
  6548. Vector4.Center = function (value1, value2) {
  6549. var center = value1.add(value2);
  6550. center.scaleInPlace(0.5);
  6551. return center;
  6552. };
  6553. /**
  6554. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  6555. * This methods computes transformed normalized direction vectors only.
  6556. * @param vector the vector to transform
  6557. * @param transformation the transformation matrix to apply
  6558. * @returns the new vector
  6559. */
  6560. Vector4.TransformNormal = function (vector, transformation) {
  6561. var result = Vector4.Zero();
  6562. Vector4.TransformNormalToRef(vector, transformation, result);
  6563. return result;
  6564. };
  6565. /**
  6566. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  6567. * This methods computes transformed normalized direction vectors only.
  6568. * @param vector the vector to transform
  6569. * @param transformation the transformation matrix to apply
  6570. * @param result the vector to store the result in
  6571. */
  6572. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  6573. var m = transformation.m;
  6574. var x = (vector.x * m[0]) + (vector.y * m[4]) + (vector.z * m[8]);
  6575. var y = (vector.x * m[1]) + (vector.y * m[5]) + (vector.z * m[9]);
  6576. var z = (vector.x * m[2]) + (vector.y * m[6]) + (vector.z * m[10]);
  6577. result.x = x;
  6578. result.y = y;
  6579. result.z = z;
  6580. result.w = vector.w;
  6581. };
  6582. /**
  6583. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  6584. * This methods computes transformed normalized direction vectors only.
  6585. * @param x value to transform
  6586. * @param y value to transform
  6587. * @param z value to transform
  6588. * @param w value to transform
  6589. * @param transformation the transformation matrix to apply
  6590. * @param result the vector to store the results in
  6591. */
  6592. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  6593. var m = transformation.m;
  6594. result.x = (x * m[0]) + (y * m[4]) + (z * m[8]);
  6595. result.y = (x * m[1]) + (y * m[5]) + (z * m[9]);
  6596. result.z = (x * m[2]) + (y * m[6]) + (z * m[10]);
  6597. result.w = w;
  6598. };
  6599. return Vector4;
  6600. }());
  6601. BABYLON.Vector4 = Vector4;
  6602. /**
  6603. * Size containing widht and height
  6604. */
  6605. var Size = /** @class */ (function () {
  6606. /**
  6607. * Creates a Size object from the given width and height (floats).
  6608. * @param width width of the new size
  6609. * @param height height of the new size
  6610. */
  6611. function Size(width, height) {
  6612. this.width = width;
  6613. this.height = height;
  6614. }
  6615. /**
  6616. * Returns a string with the Size width and height
  6617. * @returns a string with the Size width and height
  6618. */
  6619. Size.prototype.toString = function () {
  6620. return "{W: " + this.width + ", H: " + this.height + "}";
  6621. };
  6622. /**
  6623. * "Size"
  6624. * @returns the string "Size"
  6625. */
  6626. Size.prototype.getClassName = function () {
  6627. return "Size";
  6628. };
  6629. /**
  6630. * Returns the Size hash code.
  6631. * @returns a hash code for a unique width and height
  6632. */
  6633. Size.prototype.getHashCode = function () {
  6634. var hash = this.width || 0;
  6635. hash = (hash * 397) ^ (this.height || 0);
  6636. return hash;
  6637. };
  6638. /**
  6639. * Updates the current size from the given one.
  6640. * @param src the given size
  6641. */
  6642. Size.prototype.copyFrom = function (src) {
  6643. this.width = src.width;
  6644. this.height = src.height;
  6645. };
  6646. /**
  6647. * Updates in place the current Size from the given floats.
  6648. * @param width width of the new size
  6649. * @param height height of the new size
  6650. * @returns the updated Size.
  6651. */
  6652. Size.prototype.copyFromFloats = function (width, height) {
  6653. this.width = width;
  6654. this.height = height;
  6655. return this;
  6656. };
  6657. /**
  6658. * Updates in place the current Size from the given floats.
  6659. * @param width width to set
  6660. * @param height height to set
  6661. * @returns the updated Size.
  6662. */
  6663. Size.prototype.set = function (width, height) {
  6664. return this.copyFromFloats(width, height);
  6665. };
  6666. /**
  6667. * Multiplies the width and height by numbers
  6668. * @param w factor to multiple the width by
  6669. * @param h factor to multiple the height by
  6670. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  6671. */
  6672. Size.prototype.multiplyByFloats = function (w, h) {
  6673. return new Size(this.width * w, this.height * h);
  6674. };
  6675. /**
  6676. * Clones the size
  6677. * @returns a new Size copied from the given one.
  6678. */
  6679. Size.prototype.clone = function () {
  6680. return new Size(this.width, this.height);
  6681. };
  6682. /**
  6683. * True if the current Size and the given one width and height are strictly equal.
  6684. * @param other the other size to compare against
  6685. * @returns True if the current Size and the given one width and height are strictly equal.
  6686. */
  6687. Size.prototype.equals = function (other) {
  6688. if (!other) {
  6689. return false;
  6690. }
  6691. return (this.width === other.width) && (this.height === other.height);
  6692. };
  6693. Object.defineProperty(Size.prototype, "surface", {
  6694. /**
  6695. * The surface of the Size : width * height (float).
  6696. */
  6697. get: function () {
  6698. return this.width * this.height;
  6699. },
  6700. enumerable: true,
  6701. configurable: true
  6702. });
  6703. /**
  6704. * Create a new size of zero
  6705. * @returns a new Size set to (0.0, 0.0)
  6706. */
  6707. Size.Zero = function () {
  6708. return new Size(0.0, 0.0);
  6709. };
  6710. /**
  6711. * Sums the width and height of two sizes
  6712. * @param otherSize size to add to this size
  6713. * @returns a new Size set as the addition result of the current Size and the given one.
  6714. */
  6715. Size.prototype.add = function (otherSize) {
  6716. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  6717. return r;
  6718. };
  6719. /**
  6720. * Subtracts the width and height of two
  6721. * @param otherSize size to subtract to this size
  6722. * @returns a new Size set as the subtraction result of the given one from the current Size.
  6723. */
  6724. Size.prototype.subtract = function (otherSize) {
  6725. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  6726. return r;
  6727. };
  6728. /**
  6729. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  6730. * @param start starting size to lerp between
  6731. * @param end end size to lerp between
  6732. * @param amount amount to lerp between the start and end values
  6733. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  6734. */
  6735. Size.Lerp = function (start, end, amount) {
  6736. var w = start.width + ((end.width - start.width) * amount);
  6737. var h = start.height + ((end.height - start.height) * amount);
  6738. return new Size(w, h);
  6739. };
  6740. return Size;
  6741. }());
  6742. BABYLON.Size = Size;
  6743. /**
  6744. * Class used to store quaternion data
  6745. * @see https://en.wikipedia.org/wiki/Quaternion
  6746. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  6747. */
  6748. var Quaternion = /** @class */ (function () {
  6749. /**
  6750. * Creates a new Quaternion from the given floats
  6751. * @param x defines the first component (0 by default)
  6752. * @param y defines the second component (0 by default)
  6753. * @param z defines the third component (0 by default)
  6754. * @param w defines the fourth component (1.0 by default)
  6755. */
  6756. function Quaternion(
  6757. /** defines the first component (0 by default) */
  6758. x,
  6759. /** defines the second component (0 by default) */
  6760. y,
  6761. /** defines the third component (0 by default) */
  6762. z,
  6763. /** defines the fourth component (1.0 by default) */
  6764. w) {
  6765. if (x === void 0) { x = 0.0; }
  6766. if (y === void 0) { y = 0.0; }
  6767. if (z === void 0) { z = 0.0; }
  6768. if (w === void 0) { w = 1.0; }
  6769. this.x = x;
  6770. this.y = y;
  6771. this.z = z;
  6772. this.w = w;
  6773. }
  6774. /**
  6775. * Gets a string representation for the current quaternion
  6776. * @returns a string with the Quaternion coordinates
  6777. */
  6778. Quaternion.prototype.toString = function () {
  6779. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  6780. };
  6781. /**
  6782. * Gets the class name of the quaternion
  6783. * @returns the string "Quaternion"
  6784. */
  6785. Quaternion.prototype.getClassName = function () {
  6786. return "Quaternion";
  6787. };
  6788. /**
  6789. * Gets a hash code for this quaternion
  6790. * @returns the quaternion hash code
  6791. */
  6792. Quaternion.prototype.getHashCode = function () {
  6793. var hash = this.x || 0;
  6794. hash = (hash * 397) ^ (this.y || 0);
  6795. hash = (hash * 397) ^ (this.z || 0);
  6796. hash = (hash * 397) ^ (this.w || 0);
  6797. return hash;
  6798. };
  6799. /**
  6800. * Copy the quaternion to an array
  6801. * @returns a new array populated with 4 elements from the quaternion coordinates
  6802. */
  6803. Quaternion.prototype.asArray = function () {
  6804. return [this.x, this.y, this.z, this.w];
  6805. };
  6806. /**
  6807. * Check if two quaternions are equals
  6808. * @param otherQuaternion defines the second operand
  6809. * @return true if the current quaternion and the given one coordinates are strictly equals
  6810. */
  6811. Quaternion.prototype.equals = function (otherQuaternion) {
  6812. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  6813. };
  6814. /**
  6815. * Clone the current quaternion
  6816. * @returns a new quaternion copied from the current one
  6817. */
  6818. Quaternion.prototype.clone = function () {
  6819. return new Quaternion(this.x, this.y, this.z, this.w);
  6820. };
  6821. /**
  6822. * Copy a quaternion to the current one
  6823. * @param other defines the other quaternion
  6824. * @returns the updated current quaternion
  6825. */
  6826. Quaternion.prototype.copyFrom = function (other) {
  6827. this.x = other.x;
  6828. this.y = other.y;
  6829. this.z = other.z;
  6830. this.w = other.w;
  6831. return this;
  6832. };
  6833. /**
  6834. * Updates the current quaternion with the given float coordinates
  6835. * @param x defines the x coordinate
  6836. * @param y defines the y coordinate
  6837. * @param z defines the z coordinate
  6838. * @param w defines the w coordinate
  6839. * @returns the updated current quaternion
  6840. */
  6841. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  6842. this.x = x;
  6843. this.y = y;
  6844. this.z = z;
  6845. this.w = w;
  6846. return this;
  6847. };
  6848. /**
  6849. * Updates the current quaternion from the given float coordinates
  6850. * @param x defines the x coordinate
  6851. * @param y defines the y coordinate
  6852. * @param z defines the z coordinate
  6853. * @param w defines the w coordinate
  6854. * @returns the updated current quaternion
  6855. */
  6856. Quaternion.prototype.set = function (x, y, z, w) {
  6857. return this.copyFromFloats(x, y, z, w);
  6858. };
  6859. /**
  6860. * Adds two quaternions
  6861. * @param other defines the second operand
  6862. * @returns a new quaternion as the addition result of the given one and the current quaternion
  6863. */
  6864. Quaternion.prototype.add = function (other) {
  6865. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  6866. };
  6867. /**
  6868. * Add a quaternion to the current one
  6869. * @param other defines the quaternion to add
  6870. * @returns the current quaternion
  6871. */
  6872. Quaternion.prototype.addInPlace = function (other) {
  6873. this.x += other.x;
  6874. this.y += other.y;
  6875. this.z += other.z;
  6876. this.w += other.w;
  6877. return this;
  6878. };
  6879. /**
  6880. * Subtract two quaternions
  6881. * @param other defines the second operand
  6882. * @returns a new quaternion as the subtraction result of the given one from the current one
  6883. */
  6884. Quaternion.prototype.subtract = function (other) {
  6885. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  6886. };
  6887. /**
  6888. * Multiplies the current quaternion by a scale factor
  6889. * @param value defines the scale factor
  6890. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  6891. */
  6892. Quaternion.prototype.scale = function (value) {
  6893. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  6894. };
  6895. /**
  6896. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  6897. * @param scale defines the scale factor
  6898. * @param result defines the Quaternion object where to store the result
  6899. * @returns the unmodified current quaternion
  6900. */
  6901. Quaternion.prototype.scaleToRef = function (scale, result) {
  6902. result.x = this.x * scale;
  6903. result.y = this.y * scale;
  6904. result.z = this.z * scale;
  6905. result.w = this.w * scale;
  6906. return this;
  6907. };
  6908. /**
  6909. * Multiplies in place the current quaternion by a scale factor
  6910. * @param value defines the scale factor
  6911. * @returns the current modified quaternion
  6912. */
  6913. Quaternion.prototype.scaleInPlace = function (value) {
  6914. this.x *= value;
  6915. this.y *= value;
  6916. this.z *= value;
  6917. this.w *= value;
  6918. return this;
  6919. };
  6920. /**
  6921. * Scale the current quaternion values by a factor and add the result to a given quaternion
  6922. * @param scale defines the scale factor
  6923. * @param result defines the Quaternion object where to store the result
  6924. * @returns the unmodified current quaternion
  6925. */
  6926. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  6927. result.x += this.x * scale;
  6928. result.y += this.y * scale;
  6929. result.z += this.z * scale;
  6930. result.w += this.w * scale;
  6931. return this;
  6932. };
  6933. /**
  6934. * Multiplies two quaternions
  6935. * @param q1 defines the second operand
  6936. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  6937. */
  6938. Quaternion.prototype.multiply = function (q1) {
  6939. var result = new Quaternion(0, 0, 0, 1.0);
  6940. this.multiplyToRef(q1, result);
  6941. return result;
  6942. };
  6943. /**
  6944. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  6945. * @param q1 defines the second operand
  6946. * @param result defines the target quaternion
  6947. * @returns the current quaternion
  6948. */
  6949. Quaternion.prototype.multiplyToRef = function (q1, result) {
  6950. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  6951. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  6952. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  6953. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  6954. result.copyFromFloats(x, y, z, w);
  6955. return this;
  6956. };
  6957. /**
  6958. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  6959. * @param q1 defines the second operand
  6960. * @returns the currentupdated quaternion
  6961. */
  6962. Quaternion.prototype.multiplyInPlace = function (q1) {
  6963. this.multiplyToRef(q1, this);
  6964. return this;
  6965. };
  6966. /**
  6967. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  6968. * @param ref defines the target quaternion
  6969. * @returns the current quaternion
  6970. */
  6971. Quaternion.prototype.conjugateToRef = function (ref) {
  6972. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  6973. return this;
  6974. };
  6975. /**
  6976. * Conjugates in place (1-q) the current quaternion
  6977. * @returns the current updated quaternion
  6978. */
  6979. Quaternion.prototype.conjugateInPlace = function () {
  6980. this.x *= -1;
  6981. this.y *= -1;
  6982. this.z *= -1;
  6983. return this;
  6984. };
  6985. /**
  6986. * Conjugates in place (1-q) the current quaternion
  6987. * @returns a new quaternion
  6988. */
  6989. Quaternion.prototype.conjugate = function () {
  6990. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  6991. return result;
  6992. };
  6993. /**
  6994. * Gets length of current quaternion
  6995. * @returns the quaternion length (float)
  6996. */
  6997. Quaternion.prototype.length = function () {
  6998. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  6999. };
  7000. /**
  7001. * Normalize in place the current quaternion
  7002. * @returns the current updated quaternion
  7003. */
  7004. Quaternion.prototype.normalize = function () {
  7005. var length = 1.0 / this.length();
  7006. this.x *= length;
  7007. this.y *= length;
  7008. this.z *= length;
  7009. this.w *= length;
  7010. return this;
  7011. };
  7012. /**
  7013. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  7014. * @param order is a reserved parameter and is ignore for now
  7015. * @returns a new Vector3 containing the Euler angles
  7016. */
  7017. Quaternion.prototype.toEulerAngles = function (order) {
  7018. if (order === void 0) { order = "YZX"; }
  7019. var result = Vector3.Zero();
  7020. this.toEulerAnglesToRef(result, order);
  7021. return result;
  7022. };
  7023. /**
  7024. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  7025. * @param result defines the vector which will be filled with the Euler angles
  7026. * @param order is a reserved parameter and is ignore for now
  7027. * @returns the current unchanged quaternion
  7028. */
  7029. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  7030. if (order === void 0) { order = "YZX"; }
  7031. var qz = this.z;
  7032. var qx = this.x;
  7033. var qy = this.y;
  7034. var qw = this.w;
  7035. var sqw = qw * qw;
  7036. var sqz = qz * qz;
  7037. var sqx = qx * qx;
  7038. var sqy = qy * qy;
  7039. var zAxisY = qy * qz - qx * qw;
  7040. var limit = .4999999;
  7041. if (zAxisY < -limit) {
  7042. result.y = 2 * Math.atan2(qy, qw);
  7043. result.x = Math.PI / 2;
  7044. result.z = 0;
  7045. }
  7046. else if (zAxisY > limit) {
  7047. result.y = 2 * Math.atan2(qy, qw);
  7048. result.x = -Math.PI / 2;
  7049. result.z = 0;
  7050. }
  7051. else {
  7052. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  7053. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  7054. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  7055. }
  7056. return this;
  7057. };
  7058. /**
  7059. * Updates the given rotation matrix with the current quaternion values
  7060. * @param result defines the target matrix
  7061. * @returns the current unchanged quaternion
  7062. */
  7063. Quaternion.prototype.toRotationMatrix = function (result) {
  7064. Matrix.FromQuaternionToRef(this, result);
  7065. return this;
  7066. };
  7067. /**
  7068. * Updates the current quaternion from the given rotation matrix values
  7069. * @param matrix defines the source matrix
  7070. * @returns the current updated quaternion
  7071. */
  7072. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  7073. Quaternion.FromRotationMatrixToRef(matrix, this);
  7074. return this;
  7075. };
  7076. // Statics
  7077. /**
  7078. * Creates a new quaternion from a rotation matrix
  7079. * @param matrix defines the source matrix
  7080. * @returns a new quaternion created from the given rotation matrix values
  7081. */
  7082. Quaternion.FromRotationMatrix = function (matrix) {
  7083. var result = new Quaternion();
  7084. Quaternion.FromRotationMatrixToRef(matrix, result);
  7085. return result;
  7086. };
  7087. /**
  7088. * Updates the given quaternion with the given rotation matrix values
  7089. * @param matrix defines the source matrix
  7090. * @param result defines the target quaternion
  7091. */
  7092. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  7093. var data = matrix.m;
  7094. var m11 = data[0], m12 = data[4], m13 = data[8];
  7095. var m21 = data[1], m22 = data[5], m23 = data[9];
  7096. var m31 = data[2], m32 = data[6], m33 = data[10];
  7097. var trace = m11 + m22 + m33;
  7098. var s;
  7099. if (trace > 0) {
  7100. s = 0.5 / Math.sqrt(trace + 1.0);
  7101. result.w = 0.25 / s;
  7102. result.x = (m32 - m23) * s;
  7103. result.y = (m13 - m31) * s;
  7104. result.z = (m21 - m12) * s;
  7105. }
  7106. else if (m11 > m22 && m11 > m33) {
  7107. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  7108. result.w = (m32 - m23) / s;
  7109. result.x = 0.25 * s;
  7110. result.y = (m12 + m21) / s;
  7111. result.z = (m13 + m31) / s;
  7112. }
  7113. else if (m22 > m33) {
  7114. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  7115. result.w = (m13 - m31) / s;
  7116. result.x = (m12 + m21) / s;
  7117. result.y = 0.25 * s;
  7118. result.z = (m23 + m32) / s;
  7119. }
  7120. else {
  7121. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  7122. result.w = (m21 - m12) / s;
  7123. result.x = (m13 + m31) / s;
  7124. result.y = (m23 + m32) / s;
  7125. result.z = 0.25 * s;
  7126. }
  7127. };
  7128. /**
  7129. * Returns the dot product (float) between the quaternions "left" and "right"
  7130. * @param left defines the left operand
  7131. * @param right defines the right operand
  7132. * @returns the dot product
  7133. */
  7134. Quaternion.Dot = function (left, right) {
  7135. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  7136. };
  7137. /**
  7138. * Checks if the two quaternions are close to each other
  7139. * @param quat0 defines the first quaternion to check
  7140. * @param quat1 defines the second quaternion to check
  7141. * @returns true if the two quaternions are close to each other
  7142. */
  7143. Quaternion.AreClose = function (quat0, quat1) {
  7144. var dot = Quaternion.Dot(quat0, quat1);
  7145. return dot >= 0;
  7146. };
  7147. /**
  7148. * Creates an empty quaternion
  7149. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  7150. */
  7151. Quaternion.Zero = function () {
  7152. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  7153. };
  7154. /**
  7155. * Inverse a given quaternion
  7156. * @param q defines the source quaternion
  7157. * @returns a new quaternion as the inverted current quaternion
  7158. */
  7159. Quaternion.Inverse = function (q) {
  7160. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  7161. };
  7162. /**
  7163. * Creates an identity quaternion
  7164. * @returns the identity quaternion
  7165. */
  7166. Quaternion.Identity = function () {
  7167. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  7168. };
  7169. /**
  7170. * Gets a boolean indicating if the given quaternion is identity
  7171. * @param quaternion defines the quaternion to check
  7172. * @returns true if the quaternion is identity
  7173. */
  7174. Quaternion.IsIdentity = function (quaternion) {
  7175. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  7176. };
  7177. /**
  7178. * Creates a quaternion from a rotation around an axis
  7179. * @param axis defines the axis to use
  7180. * @param angle defines the angle to use
  7181. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  7182. */
  7183. Quaternion.RotationAxis = function (axis, angle) {
  7184. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  7185. };
  7186. /**
  7187. * Creates a rotation around an axis and stores it into the given quaternion
  7188. * @param axis defines the axis to use
  7189. * @param angle defines the angle to use
  7190. * @param result defines the target quaternion
  7191. * @returns the target quaternion
  7192. */
  7193. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  7194. var sin = Math.sin(angle / 2);
  7195. axis.normalize();
  7196. result.w = Math.cos(angle / 2);
  7197. result.x = axis.x * sin;
  7198. result.y = axis.y * sin;
  7199. result.z = axis.z * sin;
  7200. return result;
  7201. };
  7202. /**
  7203. * Creates a new quaternion from data stored into an array
  7204. * @param array defines the data source
  7205. * @param offset defines the offset in the source array where the data starts
  7206. * @returns a new quaternion
  7207. */
  7208. Quaternion.FromArray = function (array, offset) {
  7209. if (!offset) {
  7210. offset = 0;
  7211. }
  7212. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  7213. };
  7214. /**
  7215. * Creates a new quaternion from the given Euler float angles (y, x, z)
  7216. * @param yaw defines the rotation around Y axis
  7217. * @param pitch defines the rotation around X axis
  7218. * @param roll defines the rotation around Z axis
  7219. * @returns the new quaternion
  7220. */
  7221. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  7222. var q = new Quaternion();
  7223. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  7224. return q;
  7225. };
  7226. /**
  7227. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  7228. * @param yaw defines the rotation around Y axis
  7229. * @param pitch defines the rotation around X axis
  7230. * @param roll defines the rotation around Z axis
  7231. * @param result defines the target quaternion
  7232. */
  7233. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  7234. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  7235. var halfRoll = roll * 0.5;
  7236. var halfPitch = pitch * 0.5;
  7237. var halfYaw = yaw * 0.5;
  7238. var sinRoll = Math.sin(halfRoll);
  7239. var cosRoll = Math.cos(halfRoll);
  7240. var sinPitch = Math.sin(halfPitch);
  7241. var cosPitch = Math.cos(halfPitch);
  7242. var sinYaw = Math.sin(halfYaw);
  7243. var cosYaw = Math.cos(halfYaw);
  7244. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  7245. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  7246. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  7247. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  7248. };
  7249. /**
  7250. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  7251. * @param alpha defines the rotation around first axis
  7252. * @param beta defines the rotation around second axis
  7253. * @param gamma defines the rotation around third axis
  7254. * @returns the new quaternion
  7255. */
  7256. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  7257. var result = new Quaternion();
  7258. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  7259. return result;
  7260. };
  7261. /**
  7262. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  7263. * @param alpha defines the rotation around first axis
  7264. * @param beta defines the rotation around second axis
  7265. * @param gamma defines the rotation around third axis
  7266. * @param result defines the target quaternion
  7267. */
  7268. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  7269. // Produces a quaternion from Euler angles in the z-x-z orientation
  7270. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  7271. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  7272. var halfBeta = beta * 0.5;
  7273. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  7274. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  7275. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  7276. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  7277. };
  7278. /**
  7279. * 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)
  7280. * @param axis1 defines the first axis
  7281. * @param axis2 defines the second axis
  7282. * @param axis3 defines the third axis
  7283. * @returns the new quaternion
  7284. */
  7285. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  7286. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  7287. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  7288. return quat;
  7289. };
  7290. /**
  7291. * 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
  7292. * @param axis1 defines the first axis
  7293. * @param axis2 defines the second axis
  7294. * @param axis3 defines the third axis
  7295. * @param ref defines the target quaternion
  7296. */
  7297. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  7298. var rotMat = MathTmp.Matrix[0];
  7299. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  7300. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  7301. };
  7302. /**
  7303. * Interpolates between two quaternions
  7304. * @param left defines first quaternion
  7305. * @param right defines second quaternion
  7306. * @param amount defines the gradient to use
  7307. * @returns the new interpolated quaternion
  7308. */
  7309. Quaternion.Slerp = function (left, right, amount) {
  7310. var result = Quaternion.Identity();
  7311. Quaternion.SlerpToRef(left, right, amount, result);
  7312. return result;
  7313. };
  7314. /**
  7315. * Interpolates between two quaternions and stores it into a target quaternion
  7316. * @param left defines first quaternion
  7317. * @param right defines second quaternion
  7318. * @param amount defines the gradient to use
  7319. * @param result defines the target quaternion
  7320. */
  7321. Quaternion.SlerpToRef = function (left, right, amount, result) {
  7322. var num2;
  7323. var num3;
  7324. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  7325. var flag = false;
  7326. if (num4 < 0) {
  7327. flag = true;
  7328. num4 = -num4;
  7329. }
  7330. if (num4 > 0.999999) {
  7331. num3 = 1 - amount;
  7332. num2 = flag ? -amount : amount;
  7333. }
  7334. else {
  7335. var num5 = Math.acos(num4);
  7336. var num6 = (1.0 / Math.sin(num5));
  7337. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  7338. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  7339. }
  7340. result.x = (num3 * left.x) + (num2 * right.x);
  7341. result.y = (num3 * left.y) + (num2 * right.y);
  7342. result.z = (num3 * left.z) + (num2 * right.z);
  7343. result.w = (num3 * left.w) + (num2 * right.w);
  7344. };
  7345. /**
  7346. * Interpolate between two quaternions using Hermite interpolation
  7347. * @param value1 defines first quaternion
  7348. * @param tangent1 defines the incoming tangent
  7349. * @param value2 defines second quaternion
  7350. * @param tangent2 defines the outgoing tangent
  7351. * @param amount defines the target quaternion
  7352. * @returns the new interpolated quaternion
  7353. */
  7354. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7355. var squared = amount * amount;
  7356. var cubed = amount * squared;
  7357. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7358. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7359. var part3 = (cubed - (2.0 * squared)) + amount;
  7360. var part4 = cubed - squared;
  7361. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  7362. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  7363. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  7364. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  7365. return new Quaternion(x, y, z, w);
  7366. };
  7367. return Quaternion;
  7368. }());
  7369. BABYLON.Quaternion = Quaternion;
  7370. /**
  7371. * Class used to store matrix data (4x4)
  7372. */
  7373. var Matrix = /** @class */ (function () {
  7374. /**
  7375. * Creates an empty matrix (filled with zeros)
  7376. */
  7377. function Matrix() {
  7378. this._isIdentity = false;
  7379. this._isIdentityDirty = true;
  7380. this._isIdentity3x2 = true;
  7381. this._isIdentity3x2Dirty = true;
  7382. this._m = new Float32Array(16);
  7383. this._updateIdentityStatus(false);
  7384. }
  7385. Object.defineProperty(Matrix.prototype, "m", {
  7386. /**
  7387. * Gets the internal data of the matrix
  7388. */
  7389. get: function () { return this._m; },
  7390. enumerable: true,
  7391. configurable: true
  7392. });
  7393. /** @hidden */
  7394. Matrix.prototype._markAsUpdated = function () {
  7395. this.updateFlag = Matrix._updateFlagSeed++;
  7396. this._isIdentity = false;
  7397. this._isIdentity3x2 = false;
  7398. this._isIdentityDirty = true;
  7399. this._isIdentity3x2Dirty = true;
  7400. };
  7401. /** @hidden */
  7402. Matrix.prototype._updateIdentityStatus = function (isIdentity, isIdentityDirty, isIdentity3x2, isIdentity3x2Dirty) {
  7403. if (isIdentityDirty === void 0) { isIdentityDirty = false; }
  7404. if (isIdentity3x2 === void 0) { isIdentity3x2 = false; }
  7405. if (isIdentity3x2Dirty === void 0) { isIdentity3x2Dirty = true; }
  7406. this.updateFlag = Matrix._updateFlagSeed++;
  7407. this._isIdentity = isIdentity;
  7408. this._isIdentity3x2 = isIdentity || isIdentity3x2;
  7409. this._isIdentityDirty = this._isIdentity ? false : isIdentityDirty;
  7410. this._isIdentity3x2Dirty = this._isIdentity3x2 ? false : isIdentity3x2Dirty;
  7411. };
  7412. // Properties
  7413. /**
  7414. * Check if the current matrix is identity
  7415. * @returns true is the matrix is the identity matrix
  7416. */
  7417. Matrix.prototype.isIdentity = function () {
  7418. if (this._isIdentityDirty) {
  7419. this._isIdentityDirty = false;
  7420. var m = this._m;
  7421. this._isIdentity = (m[0] === 1.0 && m[1] === 0.0 && m[2] === 0.0 && m[3] === 0.0 &&
  7422. m[4] === 0.0 && m[5] === 1.0 && m[6] === 0.0 && m[7] === 0.0 &&
  7423. m[8] === 0.0 && m[9] === 0.0 && m[10] === 1.0 && m[11] === 0.0 &&
  7424. m[12] === 0.0 && m[13] === 0.0 && m[14] === 0.0 && m[15] === 1.0);
  7425. }
  7426. return this._isIdentity;
  7427. };
  7428. /**
  7429. * Check if the current matrix is identity as a texture matrix (3x2 store in 4x4)
  7430. * @returns true is the matrix is the identity matrix
  7431. */
  7432. Matrix.prototype.isIdentityAs3x2 = function () {
  7433. if (this._isIdentity3x2Dirty) {
  7434. this._isIdentity3x2Dirty = false;
  7435. if (this._m[0] !== 1.0 || this._m[5] !== 1.0 || this._m[15] !== 1.0) {
  7436. this._isIdentity3x2 = false;
  7437. }
  7438. else if (this._m[1] !== 0.0 || this._m[2] !== 0.0 || this._m[3] !== 0.0 ||
  7439. this._m[4] !== 0.0 || this._m[6] !== 0.0 || this._m[7] !== 0.0 ||
  7440. this._m[8] !== 0.0 || this._m[9] !== 0.0 || this._m[10] !== 0.0 || this._m[11] !== 0.0 ||
  7441. this._m[12] !== 0.0 || this._m[13] !== 0.0 || this._m[14] !== 0.0) {
  7442. this._isIdentity3x2 = false;
  7443. }
  7444. else {
  7445. this._isIdentity3x2 = true;
  7446. }
  7447. }
  7448. return this._isIdentity3x2;
  7449. };
  7450. /**
  7451. * Gets the determinant of the matrix
  7452. * @returns the matrix determinant
  7453. */
  7454. Matrix.prototype.determinant = function () {
  7455. if (this._isIdentity === true) {
  7456. return 1;
  7457. }
  7458. var m = this._m;
  7459. var m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
  7460. var m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
  7461. var m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
  7462. var m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
  7463. // https://en.wikipedia.org/wiki/Laplace_expansion
  7464. // to compute the deterrminant of a 4x4 Matrix we compute the cofactors of any row or column,
  7465. // then we multiply each Cofactor by its corresponding matrix value and sum them all to get the determinant
  7466. // Cofactor(i, j) = sign(i,j) * det(Minor(i, j))
  7467. // where
  7468. // - sign(i,j) = (i+j) % 2 === 0 ? 1 : -1
  7469. // - Minor(i, j) is the 3x3 matrix we get by removing row i and column j from current Matrix
  7470. //
  7471. // Here we do that for the 1st row.
  7472. var det_22_33 = m22 * m33 - m32 * m23;
  7473. var det_21_33 = m21 * m33 - m31 * m23;
  7474. var det_21_32 = m21 * m32 - m31 * m22;
  7475. var det_20_33 = m20 * m33 - m30 * m23;
  7476. var det_20_32 = m20 * m32 - m22 * m30;
  7477. var det_20_31 = m20 * m31 - m30 * m21;
  7478. var cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
  7479. var cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
  7480. var cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
  7481. var cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
  7482. return m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
  7483. };
  7484. // Methods
  7485. /**
  7486. * Returns the matrix as a Float32Array
  7487. * @returns the matrix underlying array
  7488. */
  7489. Matrix.prototype.toArray = function () {
  7490. return this._m;
  7491. };
  7492. /**
  7493. * Returns the matrix as a Float32Array
  7494. * @returns the matrix underlying array.
  7495. */
  7496. Matrix.prototype.asArray = function () {
  7497. return this._m;
  7498. };
  7499. /**
  7500. * Inverts the current matrix in place
  7501. * @returns the current inverted matrix
  7502. */
  7503. Matrix.prototype.invert = function () {
  7504. this.invertToRef(this);
  7505. return this;
  7506. };
  7507. /**
  7508. * Sets all the matrix elements to zero
  7509. * @returns the current matrix
  7510. */
  7511. Matrix.prototype.reset = function () {
  7512. 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);
  7513. this._updateIdentityStatus(false);
  7514. return this;
  7515. };
  7516. /**
  7517. * Adds the current matrix with a second one
  7518. * @param other defines the matrix to add
  7519. * @returns a new matrix as the addition of the current matrix and the given one
  7520. */
  7521. Matrix.prototype.add = function (other) {
  7522. var result = new Matrix();
  7523. this.addToRef(other, result);
  7524. return result;
  7525. };
  7526. /**
  7527. * Sets the given matrix "result" to the addition of the current matrix and the given one
  7528. * @param other defines the matrix to add
  7529. * @param result defines the target matrix
  7530. * @returns the current matrix
  7531. */
  7532. Matrix.prototype.addToRef = function (other, result) {
  7533. for (var index = 0; index < 16; index++) {
  7534. result._m[index] = this._m[index] + other._m[index];
  7535. }
  7536. result._markAsUpdated();
  7537. return this;
  7538. };
  7539. /**
  7540. * Adds in place the given matrix to the current matrix
  7541. * @param other defines the second operand
  7542. * @returns the current updated matrix
  7543. */
  7544. Matrix.prototype.addToSelf = function (other) {
  7545. for (var index = 0; index < 16; index++) {
  7546. this._m[index] += other._m[index];
  7547. }
  7548. this._markAsUpdated();
  7549. return this;
  7550. };
  7551. /**
  7552. * Sets the given matrix to the current inverted Matrix
  7553. * @param other defines the target matrix
  7554. * @returns the unmodified current matrix
  7555. */
  7556. Matrix.prototype.invertToRef = function (other) {
  7557. if (this._isIdentity === true) {
  7558. Matrix.IdentityToRef(other);
  7559. return this;
  7560. }
  7561. // the inverse of a Matrix is the transpose of cofactor matrix divided by the determinant
  7562. var m = this._m;
  7563. var m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
  7564. var m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
  7565. var m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
  7566. var m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
  7567. var det_22_33 = m22 * m33 - m32 * m23;
  7568. var det_21_33 = m21 * m33 - m31 * m23;
  7569. var det_21_32 = m21 * m32 - m31 * m22;
  7570. var det_20_33 = m20 * m33 - m30 * m23;
  7571. var det_20_32 = m20 * m32 - m22 * m30;
  7572. var det_20_31 = m20 * m31 - m30 * m21;
  7573. var cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
  7574. var cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
  7575. var cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
  7576. var cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
  7577. var det = m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
  7578. if (det === 0) {
  7579. // not invertible
  7580. other.copyFrom(this);
  7581. return this;
  7582. }
  7583. var detInv = 1 / det;
  7584. var det_12_33 = m12 * m33 - m32 * m13;
  7585. var det_11_33 = m11 * m33 - m31 * m13;
  7586. var det_11_32 = m11 * m32 - m31 * m12;
  7587. var det_10_33 = m10 * m33 - m30 * m13;
  7588. var det_10_32 = m10 * m32 - m30 * m12;
  7589. var det_10_31 = m10 * m31 - m30 * m11;
  7590. var det_12_23 = m12 * m23 - m22 * m13;
  7591. var det_11_23 = m11 * m23 - m21 * m13;
  7592. var det_11_22 = m11 * m22 - m21 * m12;
  7593. var det_10_23 = m10 * m23 - m20 * m13;
  7594. var det_10_22 = m10 * m22 - m20 * m12;
  7595. var det_10_21 = m10 * m21 - m20 * m11;
  7596. var cofact_10 = -(m01 * det_22_33 - m02 * det_21_33 + m03 * det_21_32);
  7597. var cofact_11 = +(m00 * det_22_33 - m02 * det_20_33 + m03 * det_20_32);
  7598. var cofact_12 = -(m00 * det_21_33 - m01 * det_20_33 + m03 * det_20_31);
  7599. var cofact_13 = +(m00 * det_21_32 - m01 * det_20_32 + m02 * det_20_31);
  7600. var cofact_20 = +(m01 * det_12_33 - m02 * det_11_33 + m03 * det_11_32);
  7601. var cofact_21 = -(m00 * det_12_33 - m02 * det_10_33 + m03 * det_10_32);
  7602. var cofact_22 = +(m00 * det_11_33 - m01 * det_10_33 + m03 * det_10_31);
  7603. var cofact_23 = -(m00 * det_11_32 - m01 * det_10_32 + m02 * det_10_31);
  7604. var cofact_30 = -(m01 * det_12_23 - m02 * det_11_23 + m03 * det_11_22);
  7605. var cofact_31 = +(m00 * det_12_23 - m02 * det_10_23 + m03 * det_10_22);
  7606. var cofact_32 = -(m00 * det_11_23 - m01 * det_10_23 + m03 * det_10_21);
  7607. var cofact_33 = +(m00 * det_11_22 - m01 * det_10_22 + m02 * det_10_21);
  7608. 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);
  7609. return this;
  7610. };
  7611. /**
  7612. * add a value at the specified position in the current Matrix
  7613. * @param index the index of the value within the matrix. between 0 and 15.
  7614. * @param value the value to be added
  7615. * @returns the current updated matrix
  7616. */
  7617. Matrix.prototype.addAtIndex = function (index, value) {
  7618. this._m[index] += value;
  7619. this._markAsUpdated();
  7620. return this;
  7621. };
  7622. /**
  7623. * mutiply the specified position in the current Matrix by a value
  7624. * @param index the index of the value within the matrix. between 0 and 15.
  7625. * @param value the value to be added
  7626. * @returns the current updated matrix
  7627. */
  7628. Matrix.prototype.multiplyAtIndex = function (index, value) {
  7629. this._m[index] *= value;
  7630. this._markAsUpdated();
  7631. return this;
  7632. };
  7633. /**
  7634. * Inserts the translation vector (using 3 floats) in the current matrix
  7635. * @param x defines the 1st component of the translation
  7636. * @param y defines the 2nd component of the translation
  7637. * @param z defines the 3rd component of the translation
  7638. * @returns the current updated matrix
  7639. */
  7640. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  7641. this._m[12] = x;
  7642. this._m[13] = y;
  7643. this._m[14] = z;
  7644. this._markAsUpdated();
  7645. return this;
  7646. };
  7647. /**
  7648. * Inserts the translation vector in the current matrix
  7649. * @param vector3 defines the translation to insert
  7650. * @returns the current updated matrix
  7651. */
  7652. Matrix.prototype.setTranslation = function (vector3) {
  7653. return this.setTranslationFromFloats(vector3.x, vector3.y, vector3.z);
  7654. };
  7655. /**
  7656. * Gets the translation value of the current matrix
  7657. * @returns a new Vector3 as the extracted translation from the matrix
  7658. */
  7659. Matrix.prototype.getTranslation = function () {
  7660. return new Vector3(this._m[12], this._m[13], this._m[14]);
  7661. };
  7662. /**
  7663. * Fill a Vector3 with the extracted translation from the matrix
  7664. * @param result defines the Vector3 where to store the translation
  7665. * @returns the current matrix
  7666. */
  7667. Matrix.prototype.getTranslationToRef = function (result) {
  7668. result.x = this._m[12];
  7669. result.y = this._m[13];
  7670. result.z = this._m[14];
  7671. return this;
  7672. };
  7673. /**
  7674. * Remove rotation and scaling part from the matrix
  7675. * @returns the updated matrix
  7676. */
  7677. Matrix.prototype.removeRotationAndScaling = function () {
  7678. var m = this.m;
  7679. 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);
  7680. this._updateIdentityStatus(m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1);
  7681. return this;
  7682. };
  7683. /**
  7684. * Multiply two matrices
  7685. * @param other defines the second operand
  7686. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  7687. */
  7688. Matrix.prototype.multiply = function (other) {
  7689. var result = new Matrix();
  7690. this.multiplyToRef(other, result);
  7691. return result;
  7692. };
  7693. /**
  7694. * Copy the current matrix from the given one
  7695. * @param other defines the source matrix
  7696. * @returns the current updated matrix
  7697. */
  7698. Matrix.prototype.copyFrom = function (other) {
  7699. other.copyToArray(this._m);
  7700. var o = other;
  7701. this._updateIdentityStatus(o._isIdentity, o._isIdentityDirty, o._isIdentity3x2, o._isIdentity3x2Dirty);
  7702. return this;
  7703. };
  7704. /**
  7705. * Populates the given array from the starting index with the current matrix values
  7706. * @param array defines the target array
  7707. * @param offset defines the offset in the target array where to start storing values
  7708. * @returns the current matrix
  7709. */
  7710. Matrix.prototype.copyToArray = function (array, offset) {
  7711. if (offset === void 0) { offset = 0; }
  7712. for (var index = 0; index < 16; index++) {
  7713. array[offset + index] = this._m[index];
  7714. }
  7715. return this;
  7716. };
  7717. /**
  7718. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  7719. * @param other defines the second operand
  7720. * @param result defines the matrix where to store the multiplication
  7721. * @returns the current matrix
  7722. */
  7723. Matrix.prototype.multiplyToRef = function (other, result) {
  7724. if (this._isIdentity) {
  7725. result.copyFrom(other);
  7726. return this;
  7727. }
  7728. if (other._isIdentity) {
  7729. result.copyFrom(this);
  7730. return this;
  7731. }
  7732. this.multiplyToArray(other, result._m, 0);
  7733. result._markAsUpdated();
  7734. return this;
  7735. };
  7736. /**
  7737. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  7738. * @param other defines the second operand
  7739. * @param result defines the array where to store the multiplication
  7740. * @param offset defines the offset in the target array where to start storing values
  7741. * @returns the current matrix
  7742. */
  7743. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  7744. var m = this._m;
  7745. var otherM = other.m;
  7746. var tm0 = m[0], tm1 = m[1], tm2 = m[2], tm3 = m[3];
  7747. var tm4 = m[4], tm5 = m[5], tm6 = m[6], tm7 = m[7];
  7748. var tm8 = m[8], tm9 = m[9], tm10 = m[10], tm11 = m[11];
  7749. var tm12 = m[12], tm13 = m[13], tm14 = m[14], tm15 = m[15];
  7750. var om0 = otherM[0], om1 = otherM[1], om2 = otherM[2], om3 = otherM[3];
  7751. var om4 = otherM[4], om5 = otherM[5], om6 = otherM[6], om7 = otherM[7];
  7752. var om8 = otherM[8], om9 = otherM[9], om10 = otherM[10], om11 = otherM[11];
  7753. var om12 = otherM[12], om13 = otherM[13], om14 = otherM[14], om15 = otherM[15];
  7754. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  7755. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  7756. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  7757. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  7758. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  7759. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  7760. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  7761. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  7762. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  7763. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  7764. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  7765. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  7766. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  7767. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  7768. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  7769. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  7770. return this;
  7771. };
  7772. /**
  7773. * Check equality between this matrix and a second one
  7774. * @param value defines the second matrix to compare
  7775. * @returns true is the current matrix and the given one values are strictly equal
  7776. */
  7777. Matrix.prototype.equals = function (value) {
  7778. var other = value;
  7779. if (!other) {
  7780. return false;
  7781. }
  7782. if (this._isIdentity || other._isIdentity) {
  7783. if (!this._isIdentityDirty && !other._isIdentityDirty) {
  7784. return this._isIdentity && other._isIdentity;
  7785. }
  7786. }
  7787. var m = this.m;
  7788. var om = other.m;
  7789. return (m[0] === om[0] && m[1] === om[1] && m[2] === om[2] && m[3] === om[3] &&
  7790. m[4] === om[4] && m[5] === om[5] && m[6] === om[6] && m[7] === om[7] &&
  7791. m[8] === om[8] && m[9] === om[9] && m[10] === om[10] && m[11] === om[11] &&
  7792. m[12] === om[12] && m[13] === om[13] && m[14] === om[14] && m[15] === om[15]);
  7793. };
  7794. /**
  7795. * Clone the current matrix
  7796. * @returns a new matrix from the current matrix
  7797. */
  7798. Matrix.prototype.clone = function () {
  7799. var matrix = new Matrix();
  7800. matrix.copyFrom(this);
  7801. return matrix;
  7802. };
  7803. /**
  7804. * Returns the name of the current matrix class
  7805. * @returns the string "Matrix"
  7806. */
  7807. Matrix.prototype.getClassName = function () {
  7808. return "Matrix";
  7809. };
  7810. /**
  7811. * Gets the hash code of the current matrix
  7812. * @returns the hash code
  7813. */
  7814. Matrix.prototype.getHashCode = function () {
  7815. var hash = this._m[0] || 0;
  7816. for (var i = 1; i < 16; i++) {
  7817. hash = (hash * 397) ^ (this._m[i] || 0);
  7818. }
  7819. return hash;
  7820. };
  7821. /**
  7822. * Decomposes the current Matrix into a translation, rotation and scaling components
  7823. * @param scale defines the scale vector3 given as a reference to update
  7824. * @param rotation defines the rotation quaternion given as a reference to update
  7825. * @param translation defines the translation vector3 given as a reference to update
  7826. * @returns true if operation was successful
  7827. */
  7828. Matrix.prototype.decompose = function (scale, rotation, translation) {
  7829. if (this._isIdentity) {
  7830. if (translation) {
  7831. translation.setAll(0);
  7832. }
  7833. if (scale) {
  7834. scale.setAll(1);
  7835. }
  7836. if (rotation) {
  7837. rotation.copyFromFloats(0, 0, 0, 1);
  7838. }
  7839. return true;
  7840. }
  7841. var m = this._m;
  7842. if (translation) {
  7843. translation.copyFromFloats(m[12], m[13], m[14]);
  7844. }
  7845. scale = scale || MathTmp.Vector3[0];
  7846. scale.x = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  7847. scale.y = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  7848. scale.z = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  7849. if (this.determinant() <= 0) {
  7850. scale.y *= -1;
  7851. }
  7852. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  7853. if (rotation) {
  7854. rotation.copyFromFloats(0.0, 0.0, 0.0, 1.0);
  7855. }
  7856. return false;
  7857. }
  7858. if (rotation) {
  7859. var sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;
  7860. 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]);
  7861. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  7862. }
  7863. return true;
  7864. };
  7865. /**
  7866. * Gets specific row of the matrix
  7867. * @param index defines the number of the row to get
  7868. * @returns the index-th row of the current matrix as a new Vector4
  7869. */
  7870. Matrix.prototype.getRow = function (index) {
  7871. if (index < 0 || index > 3) {
  7872. return null;
  7873. }
  7874. var i = index * 4;
  7875. return new Vector4(this._m[i + 0], this._m[i + 1], this._m[i + 2], this._m[i + 3]);
  7876. };
  7877. /**
  7878. * Sets the index-th row of the current matrix to the vector4 values
  7879. * @param index defines the number of the row to set
  7880. * @param row defines the target vector4
  7881. * @returns the updated current matrix
  7882. */
  7883. Matrix.prototype.setRow = function (index, row) {
  7884. return this.setRowFromFloats(index, row.x, row.y, row.z, row.w);
  7885. };
  7886. /**
  7887. * Compute the transpose of the matrix
  7888. * @returns the new transposed matrix
  7889. */
  7890. Matrix.prototype.transpose = function () {
  7891. return Matrix.Transpose(this);
  7892. };
  7893. /**
  7894. * Compute the transpose of the matrix and store it in a given matrix
  7895. * @param result defines the target matrix
  7896. * @returns the current matrix
  7897. */
  7898. Matrix.prototype.transposeToRef = function (result) {
  7899. Matrix.TransposeToRef(this, result);
  7900. return this;
  7901. };
  7902. /**
  7903. * Sets the index-th row of the current matrix with the given 4 x float values
  7904. * @param index defines the row index
  7905. * @param x defines the x component to set
  7906. * @param y defines the y component to set
  7907. * @param z defines the z component to set
  7908. * @param w defines the w component to set
  7909. * @returns the updated current matrix
  7910. */
  7911. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  7912. if (index < 0 || index > 3) {
  7913. return this;
  7914. }
  7915. var i = index * 4;
  7916. this._m[i + 0] = x;
  7917. this._m[i + 1] = y;
  7918. this._m[i + 2] = z;
  7919. this._m[i + 3] = w;
  7920. this._markAsUpdated();
  7921. return this;
  7922. };
  7923. /**
  7924. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  7925. * @param scale defines the scale factor
  7926. * @returns a new matrix
  7927. */
  7928. Matrix.prototype.scale = function (scale) {
  7929. var result = new Matrix();
  7930. this.scaleToRef(scale, result);
  7931. return result;
  7932. };
  7933. /**
  7934. * Scale the current matrix values by a factor to a given result matrix
  7935. * @param scale defines the scale factor
  7936. * @param result defines the matrix to store the result
  7937. * @returns the current matrix
  7938. */
  7939. Matrix.prototype.scaleToRef = function (scale, result) {
  7940. for (var index = 0; index < 16; index++) {
  7941. result._m[index] = this._m[index] * scale;
  7942. }
  7943. result._markAsUpdated();
  7944. return this;
  7945. };
  7946. /**
  7947. * Scale the current matrix values by a factor and add the result to a given matrix
  7948. * @param scale defines the scale factor
  7949. * @param result defines the Matrix to store the result
  7950. * @returns the current matrix
  7951. */
  7952. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  7953. for (var index = 0; index < 16; index++) {
  7954. result._m[index] += this._m[index] * scale;
  7955. }
  7956. result._markAsUpdated();
  7957. return this;
  7958. };
  7959. /**
  7960. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  7961. * @param ref matrix to store the result
  7962. */
  7963. Matrix.prototype.toNormalMatrix = function (ref) {
  7964. var tmp = MathTmp.Matrix[0];
  7965. this.invertToRef(tmp);
  7966. tmp.transposeToRef(ref);
  7967. var m = ref._m;
  7968. 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);
  7969. };
  7970. /**
  7971. * Gets only rotation part of the current matrix
  7972. * @returns a new matrix sets to the extracted rotation matrix from the current one
  7973. */
  7974. Matrix.prototype.getRotationMatrix = function () {
  7975. var result = new Matrix();
  7976. this.getRotationMatrixToRef(result);
  7977. return result;
  7978. };
  7979. /**
  7980. * Extracts the rotation matrix from the current one and sets it as the given "result"
  7981. * @param result defines the target matrix to store data to
  7982. * @returns the current matrix
  7983. */
  7984. Matrix.prototype.getRotationMatrixToRef = function (result) {
  7985. var scale = MathTmp.Vector3[0];
  7986. if (!this.decompose(scale)) {
  7987. Matrix.IdentityToRef(result);
  7988. return this;
  7989. }
  7990. var m = this._m;
  7991. var sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;
  7992. 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);
  7993. return this;
  7994. };
  7995. /**
  7996. * Toggles model matrix from being right handed to left handed in place and vice versa
  7997. */
  7998. Matrix.prototype.toggleModelMatrixHandInPlace = function () {
  7999. var m = this._m;
  8000. m[2] *= -1;
  8001. m[6] *= -1;
  8002. m[8] *= -1;
  8003. m[9] *= -1;
  8004. m[14] *= -1;
  8005. this._markAsUpdated();
  8006. };
  8007. /**
  8008. * Toggles projection matrix from being right handed to left handed in place and vice versa
  8009. */
  8010. Matrix.prototype.toggleProjectionMatrixHandInPlace = function () {
  8011. var m = this._m;
  8012. m[8] *= -1;
  8013. m[9] *= -1;
  8014. m[10] *= -1;
  8015. m[11] *= -1;
  8016. this._markAsUpdated();
  8017. };
  8018. // Statics
  8019. /**
  8020. * Creates a matrix from an array
  8021. * @param array defines the source array
  8022. * @param offset defines an offset in the source array
  8023. * @returns a new Matrix set from the starting index of the given array
  8024. */
  8025. Matrix.FromArray = function (array, offset) {
  8026. if (offset === void 0) { offset = 0; }
  8027. var result = new Matrix();
  8028. Matrix.FromArrayToRef(array, offset, result);
  8029. return result;
  8030. };
  8031. /**
  8032. * Copy the content of an array into a given matrix
  8033. * @param array defines the source array
  8034. * @param offset defines an offset in the source array
  8035. * @param result defines the target matrix
  8036. */
  8037. Matrix.FromArrayToRef = function (array, offset, result) {
  8038. for (var index = 0; index < 16; index++) {
  8039. result._m[index] = array[index + offset];
  8040. }
  8041. result._markAsUpdated();
  8042. };
  8043. /**
  8044. * Stores an array into a matrix after having multiplied each component by a given factor
  8045. * @param array defines the source array
  8046. * @param offset defines the offset in the source array
  8047. * @param scale defines the scaling factor
  8048. * @param result defines the target matrix
  8049. */
  8050. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  8051. for (var index = 0; index < 16; index++) {
  8052. result._m[index] = array[index + offset] * scale;
  8053. }
  8054. result._markAsUpdated();
  8055. };
  8056. Object.defineProperty(Matrix, "IdentityReadOnly", {
  8057. /**
  8058. * Gets an identity matrix that must not be updated
  8059. */
  8060. get: function () {
  8061. return Matrix._identityReadOnly;
  8062. },
  8063. enumerable: true,
  8064. configurable: true
  8065. });
  8066. /**
  8067. * Stores a list of values (16) inside a given matrix
  8068. * @param initialM11 defines 1st value of 1st row
  8069. * @param initialM12 defines 2nd value of 1st row
  8070. * @param initialM13 defines 3rd value of 1st row
  8071. * @param initialM14 defines 4th value of 1st row
  8072. * @param initialM21 defines 1st value of 2nd row
  8073. * @param initialM22 defines 2nd value of 2nd row
  8074. * @param initialM23 defines 3rd value of 2nd row
  8075. * @param initialM24 defines 4th value of 2nd row
  8076. * @param initialM31 defines 1st value of 3rd row
  8077. * @param initialM32 defines 2nd value of 3rd row
  8078. * @param initialM33 defines 3rd value of 3rd row
  8079. * @param initialM34 defines 4th value of 3rd row
  8080. * @param initialM41 defines 1st value of 4th row
  8081. * @param initialM42 defines 2nd value of 4th row
  8082. * @param initialM43 defines 3rd value of 4th row
  8083. * @param initialM44 defines 4th value of 4th row
  8084. * @param result defines the target matrix
  8085. */
  8086. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  8087. var m = result._m;
  8088. m[0] = initialM11;
  8089. m[1] = initialM12;
  8090. m[2] = initialM13;
  8091. m[3] = initialM14;
  8092. m[4] = initialM21;
  8093. m[5] = initialM22;
  8094. m[6] = initialM23;
  8095. m[7] = initialM24;
  8096. m[8] = initialM31;
  8097. m[9] = initialM32;
  8098. m[10] = initialM33;
  8099. m[11] = initialM34;
  8100. m[12] = initialM41;
  8101. m[13] = initialM42;
  8102. m[14] = initialM43;
  8103. m[15] = initialM44;
  8104. result._markAsUpdated();
  8105. };
  8106. /**
  8107. * Creates new matrix from a list of values (16)
  8108. * @param initialM11 defines 1st value of 1st row
  8109. * @param initialM12 defines 2nd value of 1st row
  8110. * @param initialM13 defines 3rd value of 1st row
  8111. * @param initialM14 defines 4th value of 1st row
  8112. * @param initialM21 defines 1st value of 2nd row
  8113. * @param initialM22 defines 2nd value of 2nd row
  8114. * @param initialM23 defines 3rd value of 2nd row
  8115. * @param initialM24 defines 4th value of 2nd row
  8116. * @param initialM31 defines 1st value of 3rd row
  8117. * @param initialM32 defines 2nd value of 3rd row
  8118. * @param initialM33 defines 3rd value of 3rd row
  8119. * @param initialM34 defines 4th value of 3rd row
  8120. * @param initialM41 defines 1st value of 4th row
  8121. * @param initialM42 defines 2nd value of 4th row
  8122. * @param initialM43 defines 3rd value of 4th row
  8123. * @param initialM44 defines 4th value of 4th row
  8124. * @returns the new matrix
  8125. */
  8126. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  8127. var result = new Matrix();
  8128. var m = result._m;
  8129. m[0] = initialM11;
  8130. m[1] = initialM12;
  8131. m[2] = initialM13;
  8132. m[3] = initialM14;
  8133. m[4] = initialM21;
  8134. m[5] = initialM22;
  8135. m[6] = initialM23;
  8136. m[7] = initialM24;
  8137. m[8] = initialM31;
  8138. m[9] = initialM32;
  8139. m[10] = initialM33;
  8140. m[11] = initialM34;
  8141. m[12] = initialM41;
  8142. m[13] = initialM42;
  8143. m[14] = initialM43;
  8144. m[15] = initialM44;
  8145. result._markAsUpdated();
  8146. return result;
  8147. };
  8148. /**
  8149. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  8150. * @param scale defines the scale vector3
  8151. * @param rotation defines the rotation quaternion
  8152. * @param translation defines the translation vector3
  8153. * @returns a new matrix
  8154. */
  8155. Matrix.Compose = function (scale, rotation, translation) {
  8156. var result = new Matrix();
  8157. Matrix.ComposeToRef(scale, rotation, translation, result);
  8158. return result;
  8159. };
  8160. /**
  8161. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  8162. * @param scale defines the scale vector3
  8163. * @param rotation defines the rotation quaternion
  8164. * @param translation defines the translation vector3
  8165. * @param result defines the target matrix
  8166. */
  8167. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  8168. Matrix.ScalingToRef(scale.x, scale.y, scale.z, MathTmp.Matrix[1]);
  8169. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  8170. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  8171. result.setTranslation(translation);
  8172. };
  8173. /**
  8174. * Creates a new identity matrix
  8175. * @returns a new identity matrix
  8176. */
  8177. Matrix.Identity = function () {
  8178. 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);
  8179. identity._updateIdentityStatus(true);
  8180. return identity;
  8181. };
  8182. /**
  8183. * Creates a new identity matrix and stores the result in a given matrix
  8184. * @param result defines the target matrix
  8185. */
  8186. Matrix.IdentityToRef = function (result) {
  8187. 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);
  8188. result._updateIdentityStatus(true);
  8189. };
  8190. /**
  8191. * Creates a new zero matrix
  8192. * @returns a new zero matrix
  8193. */
  8194. Matrix.Zero = function () {
  8195. 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);
  8196. zero._updateIdentityStatus(false);
  8197. return zero;
  8198. };
  8199. /**
  8200. * Creates a new rotation matrix for "angle" radians around the X axis
  8201. * @param angle defines the angle (in radians) to use
  8202. * @return the new matrix
  8203. */
  8204. Matrix.RotationX = function (angle) {
  8205. var result = new Matrix();
  8206. Matrix.RotationXToRef(angle, result);
  8207. return result;
  8208. };
  8209. /**
  8210. * Creates a new matrix as the invert of a given matrix
  8211. * @param source defines the source matrix
  8212. * @returns the new matrix
  8213. */
  8214. Matrix.Invert = function (source) {
  8215. var result = new Matrix();
  8216. source.invertToRef(result);
  8217. return result;
  8218. };
  8219. /**
  8220. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  8221. * @param angle defines the angle (in radians) to use
  8222. * @param result defines the target matrix
  8223. */
  8224. Matrix.RotationXToRef = function (angle, result) {
  8225. var s = Math.sin(angle);
  8226. var c = Math.cos(angle);
  8227. 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);
  8228. result._updateIdentityStatus(c === 1 && s === 0);
  8229. };
  8230. /**
  8231. * Creates a new rotation matrix for "angle" radians around the Y axis
  8232. * @param angle defines the angle (in radians) to use
  8233. * @return the new matrix
  8234. */
  8235. Matrix.RotationY = function (angle) {
  8236. var result = new Matrix();
  8237. Matrix.RotationYToRef(angle, result);
  8238. return result;
  8239. };
  8240. /**
  8241. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  8242. * @param angle defines the angle (in radians) to use
  8243. * @param result defines the target matrix
  8244. */
  8245. Matrix.RotationYToRef = function (angle, result) {
  8246. var s = Math.sin(angle);
  8247. var c = Math.cos(angle);
  8248. 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);
  8249. result._updateIdentityStatus(c === 1 && s === 0);
  8250. };
  8251. /**
  8252. * Creates a new rotation matrix for "angle" radians around the Z axis
  8253. * @param angle defines the angle (in radians) to use
  8254. * @return the new matrix
  8255. */
  8256. Matrix.RotationZ = function (angle) {
  8257. var result = new Matrix();
  8258. Matrix.RotationZToRef(angle, result);
  8259. return result;
  8260. };
  8261. /**
  8262. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  8263. * @param angle defines the angle (in radians) to use
  8264. * @param result defines the target matrix
  8265. */
  8266. Matrix.RotationZToRef = function (angle, result) {
  8267. var s = Math.sin(angle);
  8268. var c = Math.cos(angle);
  8269. 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);
  8270. result._updateIdentityStatus(c === 1 && s === 0);
  8271. };
  8272. /**
  8273. * Creates a new rotation matrix for "angle" radians around the given axis
  8274. * @param axis defines the axis to use
  8275. * @param angle defines the angle (in radians) to use
  8276. * @return the new matrix
  8277. */
  8278. Matrix.RotationAxis = function (axis, angle) {
  8279. var result = new Matrix();
  8280. Matrix.RotationAxisToRef(axis, angle, result);
  8281. return result;
  8282. };
  8283. /**
  8284. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  8285. * @param axis defines the axis to use
  8286. * @param angle defines the angle (in radians) to use
  8287. * @param result defines the target matrix
  8288. */
  8289. Matrix.RotationAxisToRef = function (axis, angle, result) {
  8290. var s = Math.sin(-angle);
  8291. var c = Math.cos(-angle);
  8292. var c1 = 1 - c;
  8293. axis.normalize();
  8294. var m = result._m;
  8295. m[0] = (axis.x * axis.x) * c1 + c;
  8296. m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  8297. m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  8298. m[3] = 0.0;
  8299. m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  8300. m[5] = (axis.y * axis.y) * c1 + c;
  8301. m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  8302. m[7] = 0.0;
  8303. m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  8304. m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  8305. m[10] = (axis.z * axis.z) * c1 + c;
  8306. m[11] = 0.0;
  8307. m[12] = 0.0;
  8308. m[13] = 0.0;
  8309. m[14] = 0.0;
  8310. m[15] = 1.0;
  8311. result._markAsUpdated();
  8312. };
  8313. /**
  8314. * Creates a rotation matrix
  8315. * @param yaw defines the yaw angle in radians (Y axis)
  8316. * @param pitch defines the pitch angle in radians (X axis)
  8317. * @param roll defines the roll angle in radians (X axis)
  8318. * @returns the new rotation matrix
  8319. */
  8320. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  8321. var result = new Matrix();
  8322. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  8323. return result;
  8324. };
  8325. /**
  8326. * Creates a rotation matrix and stores it in a given matrix
  8327. * @param yaw defines the yaw angle in radians (Y axis)
  8328. * @param pitch defines the pitch angle in radians (X axis)
  8329. * @param roll defines the roll angle in radians (X axis)
  8330. * @param result defines the target matrix
  8331. */
  8332. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  8333. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, MathTmp.Quaternion[0]);
  8334. MathTmp.Quaternion[0].toRotationMatrix(result);
  8335. };
  8336. /**
  8337. * Creates a scaling matrix
  8338. * @param x defines the scale factor on X axis
  8339. * @param y defines the scale factor on Y axis
  8340. * @param z defines the scale factor on Z axis
  8341. * @returns the new matrix
  8342. */
  8343. Matrix.Scaling = function (x, y, z) {
  8344. var result = new Matrix();
  8345. Matrix.ScalingToRef(x, y, z, result);
  8346. return result;
  8347. };
  8348. /**
  8349. * Creates a scaling matrix and stores it in a given matrix
  8350. * @param x defines the scale factor on X axis
  8351. * @param y defines the scale factor on Y axis
  8352. * @param z defines the scale factor on Z axis
  8353. * @param result defines the target matrix
  8354. */
  8355. Matrix.ScalingToRef = function (x, y, z, result) {
  8356. 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);
  8357. result._updateIdentityStatus(x === 1 && y === 1 && z === 1);
  8358. };
  8359. /**
  8360. * Creates a translation matrix
  8361. * @param x defines the translation on X axis
  8362. * @param y defines the translation on Y axis
  8363. * @param z defines the translationon Z axis
  8364. * @returns the new matrix
  8365. */
  8366. Matrix.Translation = function (x, y, z) {
  8367. var result = new Matrix();
  8368. Matrix.TranslationToRef(x, y, z, result);
  8369. return result;
  8370. };
  8371. /**
  8372. * Creates a translation matrix and stores it in a given matrix
  8373. * @param x defines the translation on X axis
  8374. * @param y defines the translation on Y axis
  8375. * @param z defines the translationon Z axis
  8376. * @param result defines the target matrix
  8377. */
  8378. Matrix.TranslationToRef = function (x, y, z, result) {
  8379. 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);
  8380. result._updateIdentityStatus(x === 0 && y === 0 && z === 0);
  8381. };
  8382. /**
  8383. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  8384. * @param startValue defines the start value
  8385. * @param endValue defines the end value
  8386. * @param gradient defines the gradient factor
  8387. * @returns the new matrix
  8388. */
  8389. Matrix.Lerp = function (startValue, endValue, gradient) {
  8390. var result = new Matrix();
  8391. Matrix.LerpToRef(startValue, endValue, gradient, result);
  8392. return result;
  8393. };
  8394. /**
  8395. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  8396. * @param startValue defines the start value
  8397. * @param endValue defines the end value
  8398. * @param gradient defines the gradient factor
  8399. * @param result defines the Matrix object where to store data
  8400. */
  8401. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  8402. for (var index = 0; index < 16; index++) {
  8403. result._m[index] = startValue._m[index] * (1.0 - gradient) + endValue._m[index] * gradient;
  8404. }
  8405. result._markAsUpdated();
  8406. };
  8407. /**
  8408. * Builds a new matrix whose values are computed by:
  8409. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  8410. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  8411. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  8412. * @param startValue defines the first matrix
  8413. * @param endValue defines the second matrix
  8414. * @param gradient defines the gradient between the two matrices
  8415. * @returns the new matrix
  8416. */
  8417. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  8418. var result = new Matrix();
  8419. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  8420. return result;
  8421. };
  8422. /**
  8423. * Update a matrix to values which are computed by:
  8424. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  8425. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  8426. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  8427. * @param startValue defines the first matrix
  8428. * @param endValue defines the second matrix
  8429. * @param gradient defines the gradient between the two matrices
  8430. * @param result defines the target matrix
  8431. */
  8432. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  8433. var startScale = MathTmp.Vector3[0];
  8434. var startRotation = MathTmp.Quaternion[0];
  8435. var startTranslation = MathTmp.Vector3[1];
  8436. startValue.decompose(startScale, startRotation, startTranslation);
  8437. var endScale = MathTmp.Vector3[2];
  8438. var endRotation = MathTmp.Quaternion[1];
  8439. var endTranslation = MathTmp.Vector3[3];
  8440. endValue.decompose(endScale, endRotation, endTranslation);
  8441. var resultScale = MathTmp.Vector3[4];
  8442. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  8443. var resultRotation = MathTmp.Quaternion[2];
  8444. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  8445. var resultTranslation = MathTmp.Vector3[5];
  8446. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  8447. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  8448. };
  8449. /**
  8450. * 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"
  8451. * This function works in left handed mode
  8452. * @param eye defines the final position of the entity
  8453. * @param target defines where the entity should look at
  8454. * @param up defines the up vector for the entity
  8455. * @returns the new matrix
  8456. */
  8457. Matrix.LookAtLH = function (eye, target, up) {
  8458. var result = new Matrix();
  8459. Matrix.LookAtLHToRef(eye, target, up, result);
  8460. return result;
  8461. };
  8462. /**
  8463. * 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".
  8464. * This function works in left handed mode
  8465. * @param eye defines the final position of the entity
  8466. * @param target defines where the entity should look at
  8467. * @param up defines the up vector for the entity
  8468. * @param result defines the target matrix
  8469. */
  8470. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  8471. var xAxis = MathTmp.Vector3[0];
  8472. var yAxis = MathTmp.Vector3[1];
  8473. var zAxis = MathTmp.Vector3[2];
  8474. // Z axis
  8475. target.subtractToRef(eye, zAxis);
  8476. zAxis.normalize();
  8477. // X axis
  8478. Vector3.CrossToRef(up, zAxis, xAxis);
  8479. var xSquareLength = xAxis.lengthSquared();
  8480. if (xSquareLength === 0) {
  8481. xAxis.x = 1.0;
  8482. }
  8483. else {
  8484. xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
  8485. }
  8486. // Y axis
  8487. Vector3.CrossToRef(zAxis, xAxis, yAxis);
  8488. yAxis.normalize();
  8489. // Eye angles
  8490. var ex = -Vector3.Dot(xAxis, eye);
  8491. var ey = -Vector3.Dot(yAxis, eye);
  8492. var ez = -Vector3.Dot(zAxis, eye);
  8493. 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);
  8494. };
  8495. /**
  8496. * 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"
  8497. * This function works in right handed mode
  8498. * @param eye defines the final position of the entity
  8499. * @param target defines where the entity should look at
  8500. * @param up defines the up vector for the entity
  8501. * @returns the new matrix
  8502. */
  8503. Matrix.LookAtRH = function (eye, target, up) {
  8504. var result = new Matrix();
  8505. Matrix.LookAtRHToRef(eye, target, up, result);
  8506. return result;
  8507. };
  8508. /**
  8509. * 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".
  8510. * This function works in right handed mode
  8511. * @param eye defines the final position of the entity
  8512. * @param target defines where the entity should look at
  8513. * @param up defines the up vector for the entity
  8514. * @param result defines the target matrix
  8515. */
  8516. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  8517. var xAxis = MathTmp.Vector3[0];
  8518. var yAxis = MathTmp.Vector3[1];
  8519. var zAxis = MathTmp.Vector3[2];
  8520. // Z axis
  8521. eye.subtractToRef(target, zAxis);
  8522. zAxis.normalize();
  8523. // X axis
  8524. Vector3.CrossToRef(up, zAxis, xAxis);
  8525. var xSquareLength = xAxis.lengthSquared();
  8526. if (xSquareLength === 0) {
  8527. xAxis.x = 1.0;
  8528. }
  8529. else {
  8530. xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
  8531. }
  8532. // Y axis
  8533. Vector3.CrossToRef(zAxis, xAxis, yAxis);
  8534. yAxis.normalize();
  8535. // Eye angles
  8536. var ex = -Vector3.Dot(xAxis, eye);
  8537. var ey = -Vector3.Dot(yAxis, eye);
  8538. var ez = -Vector3.Dot(zAxis, eye);
  8539. 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);
  8540. };
  8541. /**
  8542. * Create a left-handed orthographic projection matrix
  8543. * @param width defines the viewport width
  8544. * @param height defines the viewport height
  8545. * @param znear defines the near clip plane
  8546. * @param zfar defines the far clip plane
  8547. * @returns a new matrix as a left-handed orthographic projection matrix
  8548. */
  8549. Matrix.OrthoLH = function (width, height, znear, zfar) {
  8550. var matrix = new Matrix();
  8551. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  8552. return matrix;
  8553. };
  8554. /**
  8555. * Store a left-handed orthographic projection to a given matrix
  8556. * @param width defines the viewport width
  8557. * @param height defines the viewport height
  8558. * @param znear defines the near clip plane
  8559. * @param zfar defines the far clip plane
  8560. * @param result defines the target matrix
  8561. */
  8562. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  8563. var n = znear;
  8564. var f = zfar;
  8565. var a = 2.0 / width;
  8566. var b = 2.0 / height;
  8567. var c = 2.0 / (f - n);
  8568. var d = -(f + n) / (f - n);
  8569. 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);
  8570. result._updateIdentityStatus(a === 1 && b === 1 && c === 1 && d === 0);
  8571. };
  8572. /**
  8573. * Create a left-handed orthographic projection matrix
  8574. * @param left defines the viewport left coordinate
  8575. * @param right defines the viewport right coordinate
  8576. * @param bottom defines the viewport bottom coordinate
  8577. * @param top defines the viewport top coordinate
  8578. * @param znear defines the near clip plane
  8579. * @param zfar defines the far clip plane
  8580. * @returns a new matrix as a left-handed orthographic projection matrix
  8581. */
  8582. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  8583. var matrix = new Matrix();
  8584. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  8585. return matrix;
  8586. };
  8587. /**
  8588. * Stores a left-handed orthographic projection into a given matrix
  8589. * @param left defines the viewport left coordinate
  8590. * @param right defines the viewport right coordinate
  8591. * @param bottom defines the viewport bottom coordinate
  8592. * @param top defines the viewport top coordinate
  8593. * @param znear defines the near clip plane
  8594. * @param zfar defines the far clip plane
  8595. * @param result defines the target matrix
  8596. */
  8597. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  8598. var n = znear;
  8599. var f = zfar;
  8600. var a = 2.0 / (right - left);
  8601. var b = 2.0 / (top - bottom);
  8602. var c = 2.0 / (f - n);
  8603. var d = -(f + n) / (f - n);
  8604. var i0 = (left + right) / (left - right);
  8605. var i1 = (top + bottom) / (bottom - top);
  8606. 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);
  8607. result._markAsUpdated();
  8608. };
  8609. /**
  8610. * Creates a right-handed orthographic projection matrix
  8611. * @param left defines the viewport left coordinate
  8612. * @param right defines the viewport right coordinate
  8613. * @param bottom defines the viewport bottom coordinate
  8614. * @param top defines the viewport top coordinate
  8615. * @param znear defines the near clip plane
  8616. * @param zfar defines the far clip plane
  8617. * @returns a new matrix as a right-handed orthographic projection matrix
  8618. */
  8619. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  8620. var matrix = new Matrix();
  8621. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  8622. return matrix;
  8623. };
  8624. /**
  8625. * Stores a right-handed orthographic projection into a given matrix
  8626. * @param left defines the viewport left coordinate
  8627. * @param right defines the viewport right coordinate
  8628. * @param bottom defines the viewport bottom coordinate
  8629. * @param top defines the viewport top coordinate
  8630. * @param znear defines the near clip plane
  8631. * @param zfar defines the far clip plane
  8632. * @param result defines the target matrix
  8633. */
  8634. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  8635. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  8636. result._m[10] *= -1; // No need to call _markAsUpdated as previous function already called it and let _isIdentityDirty to true
  8637. };
  8638. /**
  8639. * Creates a left-handed perspective projection matrix
  8640. * @param width defines the viewport width
  8641. * @param height defines the viewport height
  8642. * @param znear defines the near clip plane
  8643. * @param zfar defines the far clip plane
  8644. * @returns a new matrix as a left-handed perspective projection matrix
  8645. */
  8646. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  8647. var matrix = new Matrix();
  8648. var n = znear;
  8649. var f = zfar;
  8650. var a = 2.0 * n / width;
  8651. var b = 2.0 * n / height;
  8652. var c = (f + n) / (f - n);
  8653. var d = -2.0 * f * n / (f - n);
  8654. 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);
  8655. matrix._updateIdentityStatus(false);
  8656. return matrix;
  8657. };
  8658. /**
  8659. * Creates a left-handed perspective projection matrix
  8660. * @param fov defines the horizontal field of view
  8661. * @param aspect defines the aspect ratio
  8662. * @param znear defines the near clip plane
  8663. * @param zfar defines the far clip plane
  8664. * @returns a new matrix as a left-handed perspective projection matrix
  8665. */
  8666. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  8667. var matrix = new Matrix();
  8668. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  8669. return matrix;
  8670. };
  8671. /**
  8672. * Stores a left-handed perspective projection into a given matrix
  8673. * @param fov defines the horizontal field of view
  8674. * @param aspect defines the aspect ratio
  8675. * @param znear defines the near clip plane
  8676. * @param zfar defines the far clip plane
  8677. * @param result defines the target matrix
  8678. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  8679. */
  8680. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  8681. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  8682. var n = znear;
  8683. var f = zfar;
  8684. var t = 1.0 / (Math.tan(fov * 0.5));
  8685. var a = isVerticalFovFixed ? (t / aspect) : t;
  8686. var b = isVerticalFovFixed ? t : (t * aspect);
  8687. var c = (f + n) / (f - n);
  8688. var d = -2.0 * f * n / (f - n);
  8689. 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);
  8690. result._updateIdentityStatus(false);
  8691. };
  8692. /**
  8693. * Creates a right-handed perspective projection matrix
  8694. * @param fov defines the horizontal field of view
  8695. * @param aspect defines the aspect ratio
  8696. * @param znear defines the near clip plane
  8697. * @param zfar defines the far clip plane
  8698. * @returns a new matrix as a right-handed perspective projection matrix
  8699. */
  8700. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  8701. var matrix = new Matrix();
  8702. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  8703. return matrix;
  8704. };
  8705. /**
  8706. * Stores a right-handed perspective projection into a given matrix
  8707. * @param fov defines the horizontal field of view
  8708. * @param aspect defines the aspect ratio
  8709. * @param znear defines the near clip plane
  8710. * @param zfar defines the far clip plane
  8711. * @param result defines the target matrix
  8712. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  8713. */
  8714. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  8715. //alternatively this could be expressed as:
  8716. // m = PerspectiveFovLHToRef
  8717. // m[10] *= -1.0;
  8718. // m[11] *= -1.0;
  8719. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  8720. var n = znear;
  8721. var f = zfar;
  8722. var t = 1.0 / (Math.tan(fov * 0.5));
  8723. var a = isVerticalFovFixed ? (t / aspect) : t;
  8724. var b = isVerticalFovFixed ? t : (t * aspect);
  8725. var c = -(f + n) / (f - n);
  8726. var d = -2 * f * n / (f - n);
  8727. 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);
  8728. result._updateIdentityStatus(false);
  8729. };
  8730. /**
  8731. * Stores a perspective projection for WebVR info a given matrix
  8732. * @param fov defines the field of view
  8733. * @param znear defines the near clip plane
  8734. * @param zfar defines the far clip plane
  8735. * @param result defines the target matrix
  8736. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  8737. */
  8738. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  8739. if (rightHanded === void 0) { rightHanded = false; }
  8740. var rightHandedFactor = rightHanded ? -1 : 1;
  8741. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  8742. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  8743. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  8744. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  8745. var xScale = 2.0 / (leftTan + rightTan);
  8746. var yScale = 2.0 / (upTan + downTan);
  8747. var m = result._m;
  8748. m[0] = xScale;
  8749. m[1] = m[2] = m[3] = m[4] = 0.0;
  8750. m[5] = yScale;
  8751. m[6] = m[7] = 0.0;
  8752. m[8] = ((leftTan - rightTan) * xScale * 0.5);
  8753. m[9] = -((upTan - downTan) * yScale * 0.5);
  8754. m[10] = -zfar / (znear - zfar);
  8755. m[11] = 1.0 * rightHandedFactor;
  8756. m[12] = m[13] = m[15] = 0.0;
  8757. m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  8758. result._markAsUpdated();
  8759. };
  8760. /**
  8761. * Computes a complete transformation matrix
  8762. * @param viewport defines the viewport to use
  8763. * @param world defines the world matrix
  8764. * @param view defines the view matrix
  8765. * @param projection defines the projection matrix
  8766. * @param zmin defines the near clip plane
  8767. * @param zmax defines the far clip plane
  8768. * @returns the transformation matrix
  8769. */
  8770. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  8771. var cw = viewport.width;
  8772. var ch = viewport.height;
  8773. var cx = viewport.x;
  8774. var cy = viewport.y;
  8775. 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);
  8776. var matrix = MathTmp.Matrix[0];
  8777. world.multiplyToRef(view, matrix);
  8778. matrix.multiplyToRef(projection, matrix);
  8779. return matrix.multiply(viewportMatrix);
  8780. };
  8781. /**
  8782. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  8783. * @param matrix defines the matrix to use
  8784. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  8785. */
  8786. Matrix.GetAsMatrix2x2 = function (matrix) {
  8787. return new Float32Array([
  8788. matrix._m[0], matrix._m[1],
  8789. matrix._m[4], matrix._m[5]
  8790. ]);
  8791. };
  8792. /**
  8793. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  8794. * @param matrix defines the matrix to use
  8795. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  8796. */
  8797. Matrix.GetAsMatrix3x3 = function (matrix) {
  8798. return new Float32Array([
  8799. matrix._m[0], matrix._m[1], matrix._m[2],
  8800. matrix._m[4], matrix._m[5], matrix._m[6],
  8801. matrix._m[8], matrix._m[9], matrix._m[10]
  8802. ]);
  8803. };
  8804. /**
  8805. * Compute the transpose of a given matrix
  8806. * @param matrix defines the matrix to transpose
  8807. * @returns the new matrix
  8808. */
  8809. Matrix.Transpose = function (matrix) {
  8810. var result = new Matrix();
  8811. Matrix.TransposeToRef(matrix, result);
  8812. return result;
  8813. };
  8814. /**
  8815. * Compute the transpose of a matrix and store it in a target matrix
  8816. * @param matrix defines the matrix to transpose
  8817. * @param result defines the target matrix
  8818. */
  8819. Matrix.TransposeToRef = function (matrix, result) {
  8820. var rm = result._m;
  8821. var mm = matrix._m;
  8822. rm[0] = mm[0];
  8823. rm[1] = mm[4];
  8824. rm[2] = mm[8];
  8825. rm[3] = mm[12];
  8826. rm[4] = mm[1];
  8827. rm[5] = mm[5];
  8828. rm[6] = mm[9];
  8829. rm[7] = mm[13];
  8830. rm[8] = mm[2];
  8831. rm[9] = mm[6];
  8832. rm[10] = mm[10];
  8833. rm[11] = mm[14];
  8834. rm[12] = mm[3];
  8835. rm[13] = mm[7];
  8836. rm[14] = mm[11];
  8837. rm[15] = mm[15];
  8838. // identity-ness does not change when transposing
  8839. result._updateIdentityStatus(matrix._isIdentity, matrix._isIdentityDirty);
  8840. };
  8841. /**
  8842. * Computes a reflection matrix from a plane
  8843. * @param plane defines the reflection plane
  8844. * @returns a new matrix
  8845. */
  8846. Matrix.Reflection = function (plane) {
  8847. var matrix = new Matrix();
  8848. Matrix.ReflectionToRef(plane, matrix);
  8849. return matrix;
  8850. };
  8851. /**
  8852. * Computes a reflection matrix from a plane
  8853. * @param plane defines the reflection plane
  8854. * @param result defines the target matrix
  8855. */
  8856. Matrix.ReflectionToRef = function (plane, result) {
  8857. plane.normalize();
  8858. var x = plane.normal.x;
  8859. var y = plane.normal.y;
  8860. var z = plane.normal.z;
  8861. var temp = -2 * x;
  8862. var temp2 = -2 * y;
  8863. var temp3 = -2 * z;
  8864. 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);
  8865. };
  8866. /**
  8867. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  8868. * @param xaxis defines the value of the 1st axis
  8869. * @param yaxis defines the value of the 2nd axis
  8870. * @param zaxis defines the value of the 3rd axis
  8871. * @param result defines the target matrix
  8872. */
  8873. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  8874. 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);
  8875. };
  8876. /**
  8877. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  8878. * @param quat defines the quaternion to use
  8879. * @param result defines the target matrix
  8880. */
  8881. Matrix.FromQuaternionToRef = function (quat, result) {
  8882. var xx = quat.x * quat.x;
  8883. var yy = quat.y * quat.y;
  8884. var zz = quat.z * quat.z;
  8885. var xy = quat.x * quat.y;
  8886. var zw = quat.z * quat.w;
  8887. var zx = quat.z * quat.x;
  8888. var yw = quat.y * quat.w;
  8889. var yz = quat.y * quat.z;
  8890. var xw = quat.x * quat.w;
  8891. result._m[0] = 1.0 - (2.0 * (yy + zz));
  8892. result._m[1] = 2.0 * (xy + zw);
  8893. result._m[2] = 2.0 * (zx - yw);
  8894. result._m[3] = 0.0;
  8895. result._m[4] = 2.0 * (xy - zw);
  8896. result._m[5] = 1.0 - (2.0 * (zz + xx));
  8897. result._m[6] = 2.0 * (yz + xw);
  8898. result._m[7] = 0.0;
  8899. result._m[8] = 2.0 * (zx + yw);
  8900. result._m[9] = 2.0 * (yz - xw);
  8901. result._m[10] = 1.0 - (2.0 * (yy + xx));
  8902. result._m[11] = 0.0;
  8903. result._m[12] = 0.0;
  8904. result._m[13] = 0.0;
  8905. result._m[14] = 0.0;
  8906. result._m[15] = 1.0;
  8907. result._markAsUpdated();
  8908. };
  8909. Matrix._updateFlagSeed = 0;
  8910. Matrix._identityReadOnly = Matrix.Identity();
  8911. return Matrix;
  8912. }());
  8913. BABYLON.Matrix = Matrix;
  8914. /**
  8915. * Represens a plane by the equation ax + by + cz + d = 0
  8916. */
  8917. var Plane = /** @class */ (function () {
  8918. /**
  8919. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  8920. * @param a a component of the plane
  8921. * @param b b component of the plane
  8922. * @param c c component of the plane
  8923. * @param d d component of the plane
  8924. */
  8925. function Plane(a, b, c, d) {
  8926. this.normal = new Vector3(a, b, c);
  8927. this.d = d;
  8928. }
  8929. /**
  8930. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  8931. */
  8932. Plane.prototype.asArray = function () {
  8933. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  8934. };
  8935. // Methods
  8936. /**
  8937. * @returns a new plane copied from the current Plane.
  8938. */
  8939. Plane.prototype.clone = function () {
  8940. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  8941. };
  8942. /**
  8943. * @returns the string "Plane".
  8944. */
  8945. Plane.prototype.getClassName = function () {
  8946. return "Plane";
  8947. };
  8948. /**
  8949. * @returns the Plane hash code.
  8950. */
  8951. Plane.prototype.getHashCode = function () {
  8952. var hash = this.normal.getHashCode();
  8953. hash = (hash * 397) ^ (this.d || 0);
  8954. return hash;
  8955. };
  8956. /**
  8957. * Normalize the current Plane in place.
  8958. * @returns the updated Plane.
  8959. */
  8960. Plane.prototype.normalize = function () {
  8961. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  8962. var magnitude = 0.0;
  8963. if (norm !== 0) {
  8964. magnitude = 1.0 / norm;
  8965. }
  8966. this.normal.x *= magnitude;
  8967. this.normal.y *= magnitude;
  8968. this.normal.z *= magnitude;
  8969. this.d *= magnitude;
  8970. return this;
  8971. };
  8972. /**
  8973. * Applies a transformation the plane and returns the result
  8974. * @param transformation the transformation matrix to be applied to the plane
  8975. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  8976. */
  8977. Plane.prototype.transform = function (transformation) {
  8978. var transposedMatrix = MathTmp.Matrix[0];
  8979. Matrix.TransposeToRef(transformation, transposedMatrix);
  8980. var m = transposedMatrix.m;
  8981. var x = this.normal.x;
  8982. var y = this.normal.y;
  8983. var z = this.normal.z;
  8984. var d = this.d;
  8985. var normalX = x * m[0] + y * m[1] + z * m[2] + d * m[3];
  8986. var normalY = x * m[4] + y * m[5] + z * m[6] + d * m[7];
  8987. var normalZ = x * m[8] + y * m[9] + z * m[10] + d * m[11];
  8988. var finalD = x * m[12] + y * m[13] + z * m[14] + d * m[15];
  8989. return new Plane(normalX, normalY, normalZ, finalD);
  8990. };
  8991. /**
  8992. * Calcualtte the dot product between the point and the plane normal
  8993. * @param point point to calculate the dot product with
  8994. * @returns the dot product (float) of the point coordinates and the plane normal.
  8995. */
  8996. Plane.prototype.dotCoordinate = function (point) {
  8997. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  8998. };
  8999. /**
  9000. * Updates the current Plane from the plane defined by the three given points.
  9001. * @param point1 one of the points used to contruct the plane
  9002. * @param point2 one of the points used to contruct the plane
  9003. * @param point3 one of the points used to contruct the plane
  9004. * @returns the updated Plane.
  9005. */
  9006. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  9007. var x1 = point2.x - point1.x;
  9008. var y1 = point2.y - point1.y;
  9009. var z1 = point2.z - point1.z;
  9010. var x2 = point3.x - point1.x;
  9011. var y2 = point3.y - point1.y;
  9012. var z2 = point3.z - point1.z;
  9013. var yz = (y1 * z2) - (z1 * y2);
  9014. var xz = (z1 * x2) - (x1 * z2);
  9015. var xy = (x1 * y2) - (y1 * x2);
  9016. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  9017. var invPyth;
  9018. if (pyth !== 0) {
  9019. invPyth = 1.0 / pyth;
  9020. }
  9021. else {
  9022. invPyth = 0.0;
  9023. }
  9024. this.normal.x = yz * invPyth;
  9025. this.normal.y = xz * invPyth;
  9026. this.normal.z = xy * invPyth;
  9027. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  9028. return this;
  9029. };
  9030. /**
  9031. * Checks if the plane is facing a given direction
  9032. * @param direction the direction to check if the plane is facing
  9033. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  9034. * @returns True is the vector "direction" is the same side than the plane normal.
  9035. */
  9036. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  9037. var dot = Vector3.Dot(this.normal, direction);
  9038. return (dot <= epsilon);
  9039. };
  9040. /**
  9041. * Calculates the distance to a point
  9042. * @param point point to calculate distance to
  9043. * @returns the signed distance (float) from the given point to the Plane.
  9044. */
  9045. Plane.prototype.signedDistanceTo = function (point) {
  9046. return Vector3.Dot(point, this.normal) + this.d;
  9047. };
  9048. // Statics
  9049. /**
  9050. * Creates a plane from an array
  9051. * @param array the array to create a plane from
  9052. * @returns a new Plane from the given array.
  9053. */
  9054. Plane.FromArray = function (array) {
  9055. return new Plane(array[0], array[1], array[2], array[3]);
  9056. };
  9057. /**
  9058. * Creates a plane from three points
  9059. * @param point1 point used to create the plane
  9060. * @param point2 point used to create the plane
  9061. * @param point3 point used to create the plane
  9062. * @returns a new Plane defined by the three given points.
  9063. */
  9064. Plane.FromPoints = function (point1, point2, point3) {
  9065. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  9066. result.copyFromPoints(point1, point2, point3);
  9067. return result;
  9068. };
  9069. /**
  9070. * Creates a plane from an origin point and a normal
  9071. * @param origin origin of the plane to be constructed
  9072. * @param normal normal of the plane to be constructed
  9073. * @returns a new Plane the normal vector to this plane at the given origin point.
  9074. * Note : the vector "normal" is updated because normalized.
  9075. */
  9076. Plane.FromPositionAndNormal = function (origin, normal) {
  9077. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  9078. normal.normalize();
  9079. result.normal = normal;
  9080. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  9081. return result;
  9082. };
  9083. /**
  9084. * Calculates the distance from a plane and a point
  9085. * @param origin origin of the plane to be constructed
  9086. * @param normal normal of the plane to be constructed
  9087. * @param point point to calculate distance to
  9088. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  9089. */
  9090. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  9091. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  9092. return Vector3.Dot(point, normal) + d;
  9093. };
  9094. return Plane;
  9095. }());
  9096. BABYLON.Plane = Plane;
  9097. /**
  9098. * Class used to represent a viewport on screen
  9099. */
  9100. var Viewport = /** @class */ (function () {
  9101. /**
  9102. * Creates a Viewport object located at (x, y) and sized (width, height)
  9103. * @param x defines viewport left coordinate
  9104. * @param y defines viewport top coordinate
  9105. * @param width defines the viewport width
  9106. * @param height defines the viewport height
  9107. */
  9108. function Viewport(
  9109. /** viewport left coordinate */
  9110. x,
  9111. /** viewport top coordinate */
  9112. y,
  9113. /**viewport width */
  9114. width,
  9115. /** viewport height */
  9116. height) {
  9117. this.x = x;
  9118. this.y = y;
  9119. this.width = width;
  9120. this.height = height;
  9121. }
  9122. /**
  9123. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  9124. * @param renderWidthOrEngine defines either an engine or the rendering width
  9125. * @param renderHeight defines the rendering height
  9126. * @returns a new Viewport
  9127. */
  9128. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  9129. if (renderWidthOrEngine.getRenderWidth) {
  9130. var engine = renderWidthOrEngine;
  9131. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  9132. }
  9133. var renderWidth = renderWidthOrEngine;
  9134. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  9135. };
  9136. /**
  9137. * Returns a new Viewport copied from the current one
  9138. * @returns a new Viewport
  9139. */
  9140. Viewport.prototype.clone = function () {
  9141. return new Viewport(this.x, this.y, this.width, this.height);
  9142. };
  9143. return Viewport;
  9144. }());
  9145. BABYLON.Viewport = Viewport;
  9146. /**
  9147. * Reprasents a camera frustum
  9148. */
  9149. var Frustum = /** @class */ (function () {
  9150. function Frustum() {
  9151. }
  9152. /**
  9153. * Gets the planes representing the frustum
  9154. * @param transform matrix to be applied to the returned planes
  9155. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  9156. */
  9157. Frustum.GetPlanes = function (transform) {
  9158. var frustumPlanes = [];
  9159. for (var index = 0; index < 6; index++) {
  9160. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  9161. }
  9162. Frustum.GetPlanesToRef(transform, frustumPlanes);
  9163. return frustumPlanes;
  9164. };
  9165. /**
  9166. * Gets the near frustum plane transformed by the transform matrix
  9167. * @param transform transformation matrix to be applied to the resulting frustum plane
  9168. * @param frustumPlane the resuling frustum plane
  9169. */
  9170. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  9171. var m = transform.m;
  9172. frustumPlane.normal.x = m[3] + m[2];
  9173. frustumPlane.normal.y = m[7] + m[6];
  9174. frustumPlane.normal.z = m[11] + m[10];
  9175. frustumPlane.d = m[15] + m[14];
  9176. frustumPlane.normalize();
  9177. };
  9178. /**
  9179. * Gets the far frustum plane transformed by the transform matrix
  9180. * @param transform transformation matrix to be applied to the resulting frustum plane
  9181. * @param frustumPlane the resuling frustum plane
  9182. */
  9183. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  9184. var m = transform.m;
  9185. frustumPlane.normal.x = m[3] - m[2];
  9186. frustumPlane.normal.y = m[7] - m[6];
  9187. frustumPlane.normal.z = m[11] - m[10];
  9188. frustumPlane.d = m[15] - m[14];
  9189. frustumPlane.normalize();
  9190. };
  9191. /**
  9192. * Gets the left frustum plane transformed by the transform matrix
  9193. * @param transform transformation matrix to be applied to the resulting frustum plane
  9194. * @param frustumPlane the resuling frustum plane
  9195. */
  9196. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  9197. var m = transform.m;
  9198. frustumPlane.normal.x = m[3] + m[0];
  9199. frustumPlane.normal.y = m[7] + m[4];
  9200. frustumPlane.normal.z = m[11] + m[8];
  9201. frustumPlane.d = m[15] + m[12];
  9202. frustumPlane.normalize();
  9203. };
  9204. /**
  9205. * Gets the right frustum plane transformed by the transform matrix
  9206. * @param transform transformation matrix to be applied to the resulting frustum plane
  9207. * @param frustumPlane the resuling frustum plane
  9208. */
  9209. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  9210. var m = transform.m;
  9211. frustumPlane.normal.x = m[3] - m[0];
  9212. frustumPlane.normal.y = m[7] - m[4];
  9213. frustumPlane.normal.z = m[11] - m[8];
  9214. frustumPlane.d = m[15] - m[12];
  9215. frustumPlane.normalize();
  9216. };
  9217. /**
  9218. * Gets the top frustum plane transformed by the transform matrix
  9219. * @param transform transformation matrix to be applied to the resulting frustum plane
  9220. * @param frustumPlane the resuling frustum plane
  9221. */
  9222. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  9223. var m = transform.m;
  9224. frustumPlane.normal.x = m[3] - m[1];
  9225. frustumPlane.normal.y = m[7] - m[5];
  9226. frustumPlane.normal.z = m[11] - m[9];
  9227. frustumPlane.d = m[15] - m[13];
  9228. frustumPlane.normalize();
  9229. };
  9230. /**
  9231. * Gets the bottom frustum plane transformed by the transform matrix
  9232. * @param transform transformation matrix to be applied to the resulting frustum plane
  9233. * @param frustumPlane the resuling frustum plane
  9234. */
  9235. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  9236. var m = transform.m;
  9237. frustumPlane.normal.x = m[3] + m[1];
  9238. frustumPlane.normal.y = m[7] + m[5];
  9239. frustumPlane.normal.z = m[11] + m[9];
  9240. frustumPlane.d = m[15] + m[13];
  9241. frustumPlane.normalize();
  9242. };
  9243. /**
  9244. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  9245. * @param transform transformation matrix to be applied to the resulting frustum planes
  9246. * @param frustumPlanes the resuling frustum planes
  9247. */
  9248. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  9249. // Near
  9250. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  9251. // Far
  9252. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  9253. // Left
  9254. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  9255. // Right
  9256. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  9257. // Top
  9258. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  9259. // Bottom
  9260. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  9261. };
  9262. return Frustum;
  9263. }());
  9264. BABYLON.Frustum = Frustum;
  9265. /** Defines supported spaces */
  9266. var Space;
  9267. (function (Space) {
  9268. /** Local (object) space */
  9269. Space[Space["LOCAL"] = 0] = "LOCAL";
  9270. /** World space */
  9271. Space[Space["WORLD"] = 1] = "WORLD";
  9272. /** Bone space */
  9273. Space[Space["BONE"] = 2] = "BONE";
  9274. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  9275. /** Defines the 3 main axes */
  9276. var Axis = /** @class */ (function () {
  9277. function Axis() {
  9278. }
  9279. /** X axis */
  9280. Axis.X = new Vector3(1.0, 0.0, 0.0);
  9281. /** Y axis */
  9282. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  9283. /** Z axis */
  9284. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  9285. return Axis;
  9286. }());
  9287. BABYLON.Axis = Axis;
  9288. /** Class used to represent a Bezier curve */
  9289. var BezierCurve = /** @class */ (function () {
  9290. function BezierCurve() {
  9291. }
  9292. /**
  9293. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  9294. * @param t defines the time
  9295. * @param x1 defines the left coordinate on X axis
  9296. * @param y1 defines the left coordinate on Y axis
  9297. * @param x2 defines the right coordinate on X axis
  9298. * @param y2 defines the right coordinate on Y axis
  9299. * @returns the interpolated value
  9300. */
  9301. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  9302. // Extract X (which is equal to time here)
  9303. var f0 = 1 - 3 * x2 + 3 * x1;
  9304. var f1 = 3 * x2 - 6 * x1;
  9305. var f2 = 3 * x1;
  9306. var refinedT = t;
  9307. for (var i = 0; i < 5; i++) {
  9308. var refinedT2 = refinedT * refinedT;
  9309. var refinedT3 = refinedT2 * refinedT;
  9310. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  9311. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  9312. refinedT -= (x - t) * slope;
  9313. refinedT = Math.min(1, Math.max(0, refinedT));
  9314. }
  9315. // Resolve cubic bezier for the given x
  9316. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  9317. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  9318. Math.pow(refinedT, 3);
  9319. };
  9320. return BezierCurve;
  9321. }());
  9322. BABYLON.BezierCurve = BezierCurve;
  9323. /**
  9324. * Defines potential orientation for back face culling
  9325. */
  9326. var Orientation;
  9327. (function (Orientation) {
  9328. /**
  9329. * Clockwise
  9330. */
  9331. Orientation[Orientation["CW"] = 0] = "CW";
  9332. /** Counter clockwise */
  9333. Orientation[Orientation["CCW"] = 1] = "CCW";
  9334. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  9335. /**
  9336. * Defines angle representation
  9337. */
  9338. var Angle = /** @class */ (function () {
  9339. /**
  9340. * Creates an Angle object of "radians" radians (float).
  9341. */
  9342. function Angle(radians) {
  9343. this._radians = radians;
  9344. if (this._radians < 0.0) {
  9345. this._radians += (2.0 * Math.PI);
  9346. }
  9347. }
  9348. /**
  9349. * Get value in degrees
  9350. * @returns the Angle value in degrees (float)
  9351. */
  9352. Angle.prototype.degrees = function () {
  9353. return this._radians * 180.0 / Math.PI;
  9354. };
  9355. /**
  9356. * Get value in radians
  9357. * @returns the Angle value in radians (float)
  9358. */
  9359. Angle.prototype.radians = function () {
  9360. return this._radians;
  9361. };
  9362. /**
  9363. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  9364. * @param a defines first vector
  9365. * @param b defines second vector
  9366. * @returns a new Angle
  9367. */
  9368. Angle.BetweenTwoPoints = function (a, b) {
  9369. var delta = b.subtract(a);
  9370. var theta = Math.atan2(delta.y, delta.x);
  9371. return new Angle(theta);
  9372. };
  9373. /**
  9374. * Gets a new Angle object from the given float in radians
  9375. * @param radians defines the angle value in radians
  9376. * @returns a new Angle
  9377. */
  9378. Angle.FromRadians = function (radians) {
  9379. return new Angle(radians);
  9380. };
  9381. /**
  9382. * Gets a new Angle object from the given float in degrees
  9383. * @param degrees defines the angle value in degrees
  9384. * @returns a new Angle
  9385. */
  9386. Angle.FromDegrees = function (degrees) {
  9387. return new Angle(degrees * Math.PI / 180.0);
  9388. };
  9389. return Angle;
  9390. }());
  9391. BABYLON.Angle = Angle;
  9392. /**
  9393. * This represents an arc in a 2d space.
  9394. */
  9395. var Arc2 = /** @class */ (function () {
  9396. /**
  9397. * Creates an Arc object from the three given points : start, middle and end.
  9398. * @param startPoint Defines the start point of the arc
  9399. * @param midPoint Defines the midlle point of the arc
  9400. * @param endPoint Defines the end point of the arc
  9401. */
  9402. function Arc2(
  9403. /** Defines the start point of the arc */
  9404. startPoint,
  9405. /** Defines the mid point of the arc */
  9406. midPoint,
  9407. /** Defines the end point of the arc */
  9408. endPoint) {
  9409. this.startPoint = startPoint;
  9410. this.midPoint = midPoint;
  9411. this.endPoint = endPoint;
  9412. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  9413. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  9414. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  9415. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  9416. 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);
  9417. this.radius = this.centerPoint.subtract(this.startPoint).length();
  9418. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  9419. var a1 = this.startAngle.degrees();
  9420. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  9421. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  9422. // angles correction
  9423. if (a2 - a1 > +180.0) {
  9424. a2 -= 360.0;
  9425. }
  9426. if (a2 - a1 < -180.0) {
  9427. a2 += 360.0;
  9428. }
  9429. if (a3 - a2 > +180.0) {
  9430. a3 -= 360.0;
  9431. }
  9432. if (a3 - a2 < -180.0) {
  9433. a3 += 360.0;
  9434. }
  9435. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  9436. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  9437. }
  9438. return Arc2;
  9439. }());
  9440. BABYLON.Arc2 = Arc2;
  9441. /**
  9442. * Represents a 2D path made up of multiple 2D points
  9443. */
  9444. var Path2 = /** @class */ (function () {
  9445. /**
  9446. * Creates a Path2 object from the starting 2D coordinates x and y.
  9447. * @param x the starting points x value
  9448. * @param y the starting points y value
  9449. */
  9450. function Path2(x, y) {
  9451. this._points = new Array();
  9452. this._length = 0.0;
  9453. /**
  9454. * If the path start and end point are the same
  9455. */
  9456. this.closed = false;
  9457. this._points.push(new Vector2(x, y));
  9458. }
  9459. /**
  9460. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  9461. * @param x the added points x value
  9462. * @param y the added points y value
  9463. * @returns the updated Path2.
  9464. */
  9465. Path2.prototype.addLineTo = function (x, y) {
  9466. if (this.closed) {
  9467. return this;
  9468. }
  9469. var newPoint = new Vector2(x, y);
  9470. var previousPoint = this._points[this._points.length - 1];
  9471. this._points.push(newPoint);
  9472. this._length += newPoint.subtract(previousPoint).length();
  9473. return this;
  9474. };
  9475. /**
  9476. * 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.
  9477. * @param midX middle point x value
  9478. * @param midY middle point y value
  9479. * @param endX end point x value
  9480. * @param endY end point y value
  9481. * @param numberOfSegments (default: 36)
  9482. * @returns the updated Path2.
  9483. */
  9484. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  9485. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  9486. if (this.closed) {
  9487. return this;
  9488. }
  9489. var startPoint = this._points[this._points.length - 1];
  9490. var midPoint = new Vector2(midX, midY);
  9491. var endPoint = new Vector2(endX, endY);
  9492. var arc = new Arc2(startPoint, midPoint, endPoint);
  9493. var increment = arc.angle.radians() / numberOfSegments;
  9494. if (arc.orientation === Orientation.CW) {
  9495. increment *= -1;
  9496. }
  9497. var currentAngle = arc.startAngle.radians() + increment;
  9498. for (var i = 0; i < numberOfSegments; i++) {
  9499. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  9500. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  9501. this.addLineTo(x, y);
  9502. currentAngle += increment;
  9503. }
  9504. return this;
  9505. };
  9506. /**
  9507. * Closes the Path2.
  9508. * @returns the Path2.
  9509. */
  9510. Path2.prototype.close = function () {
  9511. this.closed = true;
  9512. return this;
  9513. };
  9514. /**
  9515. * Gets the sum of the distance between each sequential point in the path
  9516. * @returns the Path2 total length (float).
  9517. */
  9518. Path2.prototype.length = function () {
  9519. var result = this._length;
  9520. if (!this.closed) {
  9521. var lastPoint = this._points[this._points.length - 1];
  9522. var firstPoint = this._points[0];
  9523. result += (firstPoint.subtract(lastPoint).length());
  9524. }
  9525. return result;
  9526. };
  9527. /**
  9528. * Gets the points which construct the path
  9529. * @returns the Path2 internal array of points.
  9530. */
  9531. Path2.prototype.getPoints = function () {
  9532. return this._points;
  9533. };
  9534. /**
  9535. * Retreives the point at the distance aways from the starting point
  9536. * @param normalizedLengthPosition the length along the path to retreive the point from
  9537. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  9538. */
  9539. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  9540. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  9541. return Vector2.Zero();
  9542. }
  9543. var lengthPosition = normalizedLengthPosition * this.length();
  9544. var previousOffset = 0;
  9545. for (var i = 0; i < this._points.length; i++) {
  9546. var j = (i + 1) % this._points.length;
  9547. var a = this._points[i];
  9548. var b = this._points[j];
  9549. var bToA = b.subtract(a);
  9550. var nextOffset = (bToA.length() + previousOffset);
  9551. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  9552. var dir = bToA.normalize();
  9553. var localOffset = lengthPosition - previousOffset;
  9554. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  9555. }
  9556. previousOffset = nextOffset;
  9557. }
  9558. return Vector2.Zero();
  9559. };
  9560. /**
  9561. * Creates a new path starting from an x and y position
  9562. * @param x starting x value
  9563. * @param y starting y value
  9564. * @returns a new Path2 starting at the coordinates (x, y).
  9565. */
  9566. Path2.StartingAt = function (x, y) {
  9567. return new Path2(x, y);
  9568. };
  9569. return Path2;
  9570. }());
  9571. BABYLON.Path2 = Path2;
  9572. /**
  9573. * Represents a 3D path made up of multiple 3D points
  9574. */
  9575. var Path3D = /** @class */ (function () {
  9576. /**
  9577. * new Path3D(path, normal, raw)
  9578. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  9579. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  9580. * @param path an array of Vector3, the curve axis of the Path3D
  9581. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  9582. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  9583. */
  9584. function Path3D(
  9585. /**
  9586. * an array of Vector3, the curve axis of the Path3D
  9587. */
  9588. path, firstNormal, raw) {
  9589. if (firstNormal === void 0) { firstNormal = null; }
  9590. this.path = path;
  9591. this._curve = new Array();
  9592. this._distances = new Array();
  9593. this._tangents = new Array();
  9594. this._normals = new Array();
  9595. this._binormals = new Array();
  9596. for (var p = 0; p < path.length; p++) {
  9597. this._curve[p] = path[p].clone(); // hard copy
  9598. }
  9599. this._raw = raw || false;
  9600. this._compute(firstNormal);
  9601. }
  9602. /**
  9603. * Returns the Path3D array of successive Vector3 designing its curve.
  9604. * @returns the Path3D array of successive Vector3 designing its curve.
  9605. */
  9606. Path3D.prototype.getCurve = function () {
  9607. return this._curve;
  9608. };
  9609. /**
  9610. * Returns an array populated with tangent vectors on each Path3D curve point.
  9611. * @returns an array populated with tangent vectors on each Path3D curve point.
  9612. */
  9613. Path3D.prototype.getTangents = function () {
  9614. return this._tangents;
  9615. };
  9616. /**
  9617. * Returns an array populated with normal vectors on each Path3D curve point.
  9618. * @returns an array populated with normal vectors on each Path3D curve point.
  9619. */
  9620. Path3D.prototype.getNormals = function () {
  9621. return this._normals;
  9622. };
  9623. /**
  9624. * Returns an array populated with binormal vectors on each Path3D curve point.
  9625. * @returns an array populated with binormal vectors on each Path3D curve point.
  9626. */
  9627. Path3D.prototype.getBinormals = function () {
  9628. return this._binormals;
  9629. };
  9630. /**
  9631. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  9632. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  9633. */
  9634. Path3D.prototype.getDistances = function () {
  9635. return this._distances;
  9636. };
  9637. /**
  9638. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  9639. * @param path path which all values are copied into the curves points
  9640. * @param firstNormal which should be projected onto the curve
  9641. * @returns the same object updated.
  9642. */
  9643. Path3D.prototype.update = function (path, firstNormal) {
  9644. if (firstNormal === void 0) { firstNormal = null; }
  9645. for (var p = 0; p < path.length; p++) {
  9646. this._curve[p].x = path[p].x;
  9647. this._curve[p].y = path[p].y;
  9648. this._curve[p].z = path[p].z;
  9649. }
  9650. this._compute(firstNormal);
  9651. return this;
  9652. };
  9653. // private function compute() : computes tangents, normals and binormals
  9654. Path3D.prototype._compute = function (firstNormal) {
  9655. var l = this._curve.length;
  9656. // first and last tangents
  9657. this._tangents[0] = this._getFirstNonNullVector(0);
  9658. if (!this._raw) {
  9659. this._tangents[0].normalize();
  9660. }
  9661. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  9662. if (!this._raw) {
  9663. this._tangents[l - 1].normalize();
  9664. }
  9665. // normals and binormals at first point : arbitrary vector with _normalVector()
  9666. var tg0 = this._tangents[0];
  9667. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  9668. this._normals[0] = pp0;
  9669. if (!this._raw) {
  9670. this._normals[0].normalize();
  9671. }
  9672. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  9673. if (!this._raw) {
  9674. this._binormals[0].normalize();
  9675. }
  9676. this._distances[0] = 0.0;
  9677. // normals and binormals : next points
  9678. var prev; // previous vector (segment)
  9679. var cur; // current vector (segment)
  9680. var curTang; // current tangent
  9681. // previous normal
  9682. var prevBinor; // previous binormal
  9683. for (var i = 1; i < l; i++) {
  9684. // tangents
  9685. prev = this._getLastNonNullVector(i);
  9686. if (i < l - 1) {
  9687. cur = this._getFirstNonNullVector(i);
  9688. this._tangents[i] = prev.add(cur);
  9689. this._tangents[i].normalize();
  9690. }
  9691. this._distances[i] = this._distances[i - 1] + prev.length();
  9692. // normals and binormals
  9693. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  9694. curTang = this._tangents[i];
  9695. prevBinor = this._binormals[i - 1];
  9696. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  9697. if (!this._raw) {
  9698. this._normals[i].normalize();
  9699. }
  9700. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  9701. if (!this._raw) {
  9702. this._binormals[i].normalize();
  9703. }
  9704. }
  9705. };
  9706. // private function getFirstNonNullVector(index)
  9707. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  9708. Path3D.prototype._getFirstNonNullVector = function (index) {
  9709. var i = 1;
  9710. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  9711. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  9712. i++;
  9713. nNVector = this._curve[index + i].subtract(this._curve[index]);
  9714. }
  9715. return nNVector;
  9716. };
  9717. // private function getLastNonNullVector(index)
  9718. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  9719. Path3D.prototype._getLastNonNullVector = function (index) {
  9720. var i = 1;
  9721. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  9722. while (nLVector.length() === 0 && index > i + 1) {
  9723. i++;
  9724. nLVector = this._curve[index].subtract(this._curve[index - i]);
  9725. }
  9726. return nLVector;
  9727. };
  9728. // private function normalVector(v0, vt, va) :
  9729. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  9730. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  9731. Path3D.prototype._normalVector = function (v0, vt, va) {
  9732. var normal0;
  9733. var tgl = vt.length();
  9734. if (tgl === 0.0) {
  9735. tgl = 1.0;
  9736. }
  9737. if (va === undefined || va === null) {
  9738. var point;
  9739. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  9740. point = new Vector3(0.0, -1.0, 0.0);
  9741. }
  9742. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  9743. point = new Vector3(1.0, 0.0, 0.0);
  9744. }
  9745. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  9746. point = new Vector3(0.0, 0.0, 1.0);
  9747. }
  9748. else {
  9749. point = Vector3.Zero();
  9750. }
  9751. normal0 = Vector3.Cross(vt, point);
  9752. }
  9753. else {
  9754. normal0 = Vector3.Cross(vt, va);
  9755. Vector3.CrossToRef(normal0, vt, normal0);
  9756. }
  9757. normal0.normalize();
  9758. return normal0;
  9759. };
  9760. return Path3D;
  9761. }());
  9762. BABYLON.Path3D = Path3D;
  9763. /**
  9764. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  9765. * A Curve3 is designed from a series of successive Vector3.
  9766. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  9767. */
  9768. var Curve3 = /** @class */ (function () {
  9769. /**
  9770. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  9771. * A Curve3 is designed from a series of successive Vector3.
  9772. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  9773. * @param points points which make up the curve
  9774. */
  9775. function Curve3(points) {
  9776. this._length = 0.0;
  9777. this._points = points;
  9778. this._length = this._computeLength(points);
  9779. }
  9780. /**
  9781. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  9782. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  9783. * @param v1 (Vector3) the control point
  9784. * @param v2 (Vector3) the end point of the Quadratic Bezier
  9785. * @param nbPoints (integer) the wanted number of points in the curve
  9786. * @returns the created Curve3
  9787. */
  9788. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  9789. nbPoints = nbPoints > 2 ? nbPoints : 3;
  9790. var bez = new Array();
  9791. var equation = function (t, val0, val1, val2) {
  9792. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  9793. return res;
  9794. };
  9795. for (var i = 0; i <= nbPoints; i++) {
  9796. 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)));
  9797. }
  9798. return new Curve3(bez);
  9799. };
  9800. /**
  9801. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  9802. * @param v0 (Vector3) the origin point of the Cubic Bezier
  9803. * @param v1 (Vector3) the first control point
  9804. * @param v2 (Vector3) the second control point
  9805. * @param v3 (Vector3) the end point of the Cubic Bezier
  9806. * @param nbPoints (integer) the wanted number of points in the curve
  9807. * @returns the created Curve3
  9808. */
  9809. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  9810. nbPoints = nbPoints > 3 ? nbPoints : 4;
  9811. var bez = new Array();
  9812. var equation = function (t, val0, val1, val2, val3) {
  9813. 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;
  9814. return res;
  9815. };
  9816. for (var i = 0; i <= nbPoints; i++) {
  9817. 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)));
  9818. }
  9819. return new Curve3(bez);
  9820. };
  9821. /**
  9822. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  9823. * @param p1 (Vector3) the origin point of the Hermite Spline
  9824. * @param t1 (Vector3) the tangent vector at the origin point
  9825. * @param p2 (Vector3) the end point of the Hermite Spline
  9826. * @param t2 (Vector3) the tangent vector at the end point
  9827. * @param nbPoints (integer) the wanted number of points in the curve
  9828. * @returns the created Curve3
  9829. */
  9830. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  9831. var hermite = new Array();
  9832. var step = 1.0 / nbPoints;
  9833. for (var i = 0; i <= nbPoints; i++) {
  9834. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  9835. }
  9836. return new Curve3(hermite);
  9837. };
  9838. /**
  9839. * Returns a Curve3 object along a CatmullRom Spline curve :
  9840. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  9841. * @param nbPoints (integer) the wanted number of points between each curve control points
  9842. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  9843. * @returns the created Curve3
  9844. */
  9845. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  9846. var catmullRom = new Array();
  9847. var step = 1.0 / nbPoints;
  9848. var amount = 0.0;
  9849. if (closed) {
  9850. var pointsCount = points.length;
  9851. for (var i = 0; i < pointsCount; i++) {
  9852. amount = 0;
  9853. for (var c = 0; c < nbPoints; c++) {
  9854. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  9855. amount += step;
  9856. }
  9857. }
  9858. catmullRom.push(catmullRom[0]);
  9859. }
  9860. else {
  9861. var totalPoints = new Array();
  9862. totalPoints.push(points[0].clone());
  9863. Array.prototype.push.apply(totalPoints, points);
  9864. totalPoints.push(points[points.length - 1].clone());
  9865. for (var i = 0; i < totalPoints.length - 3; i++) {
  9866. amount = 0;
  9867. for (var c = 0; c < nbPoints; c++) {
  9868. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  9869. amount += step;
  9870. }
  9871. }
  9872. i--;
  9873. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  9874. }
  9875. return new Curve3(catmullRom);
  9876. };
  9877. /**
  9878. * @returns the Curve3 stored array of successive Vector3
  9879. */
  9880. Curve3.prototype.getPoints = function () {
  9881. return this._points;
  9882. };
  9883. /**
  9884. * @returns the computed length (float) of the curve.
  9885. */
  9886. Curve3.prototype.length = function () {
  9887. return this._length;
  9888. };
  9889. /**
  9890. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  9891. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  9892. * curveA and curveB keep unchanged.
  9893. * @param curve the curve to continue from this curve
  9894. * @returns the newly constructed curve
  9895. */
  9896. Curve3.prototype.continue = function (curve) {
  9897. var lastPoint = this._points[this._points.length - 1];
  9898. var continuedPoints = this._points.slice();
  9899. var curvePoints = curve.getPoints();
  9900. for (var i = 1; i < curvePoints.length; i++) {
  9901. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  9902. }
  9903. var continuedCurve = new Curve3(continuedPoints);
  9904. return continuedCurve;
  9905. };
  9906. Curve3.prototype._computeLength = function (path) {
  9907. var l = 0;
  9908. for (var i = 1; i < path.length; i++) {
  9909. l += (path[i].subtract(path[i - 1])).length();
  9910. }
  9911. return l;
  9912. };
  9913. return Curve3;
  9914. }());
  9915. BABYLON.Curve3 = Curve3;
  9916. // Vertex formats
  9917. /**
  9918. * Contains position and normal vectors for a vertex
  9919. */
  9920. var PositionNormalVertex = /** @class */ (function () {
  9921. /**
  9922. * Creates a PositionNormalVertex
  9923. * @param position the position of the vertex (defaut: 0,0,0)
  9924. * @param normal the normal of the vertex (defaut: 0,1,0)
  9925. */
  9926. function PositionNormalVertex(
  9927. /** the position of the vertex (defaut: 0,0,0) */
  9928. position,
  9929. /** the normal of the vertex (defaut: 0,1,0) */
  9930. normal) {
  9931. if (position === void 0) { position = Vector3.Zero(); }
  9932. if (normal === void 0) { normal = Vector3.Up(); }
  9933. this.position = position;
  9934. this.normal = normal;
  9935. }
  9936. /**
  9937. * Clones the PositionNormalVertex
  9938. * @returns the cloned PositionNormalVertex
  9939. */
  9940. PositionNormalVertex.prototype.clone = function () {
  9941. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  9942. };
  9943. return PositionNormalVertex;
  9944. }());
  9945. BABYLON.PositionNormalVertex = PositionNormalVertex;
  9946. /**
  9947. * Contains position, normal and uv vectors for a vertex
  9948. */
  9949. var PositionNormalTextureVertex = /** @class */ (function () {
  9950. /**
  9951. * Creates a PositionNormalTextureVertex
  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. * @param uv the uv of the vertex (default: 0,0)
  9955. */
  9956. function PositionNormalTextureVertex(
  9957. /** the position of the vertex (defaut: 0,0,0) */
  9958. position,
  9959. /** the normal of the vertex (defaut: 0,1,0) */
  9960. normal,
  9961. /** the uv of the vertex (default: 0,0) */
  9962. uv) {
  9963. if (position === void 0) { position = Vector3.Zero(); }
  9964. if (normal === void 0) { normal = Vector3.Up(); }
  9965. if (uv === void 0) { uv = Vector2.Zero(); }
  9966. this.position = position;
  9967. this.normal = normal;
  9968. this.uv = uv;
  9969. }
  9970. /**
  9971. * Clones the PositionNormalTextureVertex
  9972. * @returns the cloned PositionNormalTextureVertex
  9973. */
  9974. PositionNormalTextureVertex.prototype.clone = function () {
  9975. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  9976. };
  9977. return PositionNormalTextureVertex;
  9978. }());
  9979. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  9980. // Temporary pre-allocated objects for engine internal use
  9981. // usage in any internal function :
  9982. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  9983. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  9984. /**
  9985. * @hidden
  9986. */
  9987. var Tmp = /** @class */ (function () {
  9988. function Tmp() {
  9989. }
  9990. Tmp.Color3 = BABYLON.Tools.BuildArray(3, Color3.Black);
  9991. Tmp.Color4 = BABYLON.Tools.BuildArray(3, function () { return new Color4(0, 0, 0, 0); });
  9992. Tmp.Vector2 = BABYLON.Tools.BuildArray(3, Vector2.Zero); // 3 temp Vector2 at once should be enough
  9993. Tmp.Vector3 = BABYLON.Tools.BuildArray(13, Vector3.Zero); // 13 temp Vector3 at once should be enough
  9994. Tmp.Vector4 = BABYLON.Tools.BuildArray(3, Vector4.Zero); // 3 temp Vector4 at once should be enough
  9995. Tmp.Quaternion = BABYLON.Tools.BuildArray(2, Quaternion.Zero); // 2 temp Quaternion at once should be enough
  9996. Tmp.Matrix = BABYLON.Tools.BuildArray(8, Matrix.Identity); // 8 temp Matrices at once should be enough
  9997. return Tmp;
  9998. }());
  9999. BABYLON.Tmp = Tmp;
  10000. /**
  10001. * @hidden
  10002. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  10003. */
  10004. var MathTmp = /** @class */ (function () {
  10005. function MathTmp() {
  10006. }
  10007. MathTmp.Vector3 = BABYLON.Tools.BuildArray(6, Vector3.Zero);
  10008. MathTmp.Matrix = BABYLON.Tools.BuildArray(2, Matrix.Identity);
  10009. MathTmp.Quaternion = BABYLON.Tools.BuildArray(3, Quaternion.Zero);
  10010. return MathTmp;
  10011. }());
  10012. })(BABYLON || (BABYLON = {}));
  10013. //# sourceMappingURL=babylon.math.js.map
  10014. var BABYLON;
  10015. (function (BABYLON) {
  10016. /**
  10017. * Scalar computation library
  10018. */
  10019. var Scalar = /** @class */ (function () {
  10020. function Scalar() {
  10021. }
  10022. /**
  10023. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  10024. * @param a number
  10025. * @param b number
  10026. * @param epsilon (default = 1.401298E-45)
  10027. * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  10028. */
  10029. Scalar.WithinEpsilon = function (a, b, epsilon) {
  10030. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  10031. var num = a - b;
  10032. return -epsilon <= num && num <= epsilon;
  10033. };
  10034. /**
  10035. * Returns a string : the upper case translation of the number i to hexadecimal.
  10036. * @param i number
  10037. * @returns the upper case translation of the number i to hexadecimal.
  10038. */
  10039. Scalar.ToHex = function (i) {
  10040. var str = i.toString(16);
  10041. if (i <= 15) {
  10042. return ("0" + str).toUpperCase();
  10043. }
  10044. return str.toUpperCase();
  10045. };
  10046. /**
  10047. * Returns -1 if value is negative and +1 is value is positive.
  10048. * @param value the value
  10049. * @returns the value itself if it's equal to zero.
  10050. */
  10051. Scalar.Sign = function (value) {
  10052. value = +value; // convert to a number
  10053. if (value === 0 || isNaN(value)) {
  10054. return value;
  10055. }
  10056. return value > 0 ? 1 : -1;
  10057. };
  10058. /**
  10059. * Returns the value itself if it's between min and max.
  10060. * Returns min if the value is lower than min.
  10061. * Returns max if the value is greater than max.
  10062. * @param value the value to clmap
  10063. * @param min the min value to clamp to (default: 0)
  10064. * @param max the max value to clamp to (default: 1)
  10065. * @returns the clamped value
  10066. */
  10067. Scalar.Clamp = function (value, min, max) {
  10068. if (min === void 0) { min = 0; }
  10069. if (max === void 0) { max = 1; }
  10070. return Math.min(max, Math.max(min, value));
  10071. };
  10072. /**
  10073. * the log2 of value.
  10074. * @param value the value to compute log2 of
  10075. * @returns the log2 of value.
  10076. */
  10077. Scalar.Log2 = function (value) {
  10078. return Math.log(value) * Math.LOG2E;
  10079. };
  10080. /**
  10081. * Loops the value, so that it is never larger than length and never smaller than 0.
  10082. *
  10083. * This is similar to the modulo operator but it works with floating point numbers.
  10084. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  10085. * With t = 5 and length = 2.5, the result would be 0.0.
  10086. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  10087. * @param value the value
  10088. * @param length the length
  10089. * @returns the looped value
  10090. */
  10091. Scalar.Repeat = function (value, length) {
  10092. return value - Math.floor(value / length) * length;
  10093. };
  10094. /**
  10095. * Normalize the value between 0.0 and 1.0 using min and max values
  10096. * @param value value to normalize
  10097. * @param min max to normalize between
  10098. * @param max min to normalize between
  10099. * @returns the normalized value
  10100. */
  10101. Scalar.Normalize = function (value, min, max) {
  10102. return (value - min) / (max - min);
  10103. };
  10104. /**
  10105. * Denormalize the value from 0.0 and 1.0 using min and max values
  10106. * @param normalized value to denormalize
  10107. * @param min max to denormalize between
  10108. * @param max min to denormalize between
  10109. * @returns the denormalized value
  10110. */
  10111. Scalar.Denormalize = function (normalized, min, max) {
  10112. return (normalized * (max - min) + min);
  10113. };
  10114. /**
  10115. * Calculates the shortest difference between two given angles given in degrees.
  10116. * @param current current angle in degrees
  10117. * @param target target angle in degrees
  10118. * @returns the delta
  10119. */
  10120. Scalar.DeltaAngle = function (current, target) {
  10121. var num = Scalar.Repeat(target - current, 360.0);
  10122. if (num > 180.0) {
  10123. num -= 360.0;
  10124. }
  10125. return num;
  10126. };
  10127. /**
  10128. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  10129. * @param tx value
  10130. * @param length length
  10131. * @returns The returned value will move back and forth between 0 and length
  10132. */
  10133. Scalar.PingPong = function (tx, length) {
  10134. var t = Scalar.Repeat(tx, length * 2.0);
  10135. return length - Math.abs(t - length);
  10136. };
  10137. /**
  10138. * Interpolates between min and max with smoothing at the limits.
  10139. *
  10140. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  10141. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  10142. * @param from from
  10143. * @param to to
  10144. * @param tx value
  10145. * @returns the smooth stepped value
  10146. */
  10147. Scalar.SmoothStep = function (from, to, tx) {
  10148. var t = Scalar.Clamp(tx);
  10149. t = -2.0 * t * t * t + 3.0 * t * t;
  10150. return to * t + from * (1.0 - t);
  10151. };
  10152. /**
  10153. * Moves a value current towards target.
  10154. *
  10155. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  10156. * Negative values of maxDelta pushes the value away from target.
  10157. * @param current current value
  10158. * @param target target value
  10159. * @param maxDelta max distance to move
  10160. * @returns resulting value
  10161. */
  10162. Scalar.MoveTowards = function (current, target, maxDelta) {
  10163. var result = 0;
  10164. if (Math.abs(target - current) <= maxDelta) {
  10165. result = target;
  10166. }
  10167. else {
  10168. result = current + Scalar.Sign(target - current) * maxDelta;
  10169. }
  10170. return result;
  10171. };
  10172. /**
  10173. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  10174. *
  10175. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  10176. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  10177. * @param current current value
  10178. * @param target target value
  10179. * @param maxDelta max distance to move
  10180. * @returns resulting angle
  10181. */
  10182. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  10183. var num = Scalar.DeltaAngle(current, target);
  10184. var result = 0;
  10185. if (-maxDelta < num && num < maxDelta) {
  10186. result = target;
  10187. }
  10188. else {
  10189. target = current + num;
  10190. result = Scalar.MoveTowards(current, target, maxDelta);
  10191. }
  10192. return result;
  10193. };
  10194. /**
  10195. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  10196. * @param start start value
  10197. * @param end target value
  10198. * @param amount amount to lerp between
  10199. * @returns the lerped value
  10200. */
  10201. Scalar.Lerp = function (start, end, amount) {
  10202. return start + ((end - start) * amount);
  10203. };
  10204. /**
  10205. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  10206. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  10207. * @param start start value
  10208. * @param end target value
  10209. * @param amount amount to lerp between
  10210. * @returns the lerped value
  10211. */
  10212. Scalar.LerpAngle = function (start, end, amount) {
  10213. var num = Scalar.Repeat(end - start, 360.0);
  10214. if (num > 180.0) {
  10215. num -= 360.0;
  10216. }
  10217. return start + num * Scalar.Clamp(amount);
  10218. };
  10219. /**
  10220. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  10221. * @param a start value
  10222. * @param b target value
  10223. * @param value value between a and b
  10224. * @returns the inverseLerp value
  10225. */
  10226. Scalar.InverseLerp = function (a, b, value) {
  10227. var result = 0;
  10228. if (a != b) {
  10229. result = Scalar.Clamp((value - a) / (b - a));
  10230. }
  10231. else {
  10232. result = 0.0;
  10233. }
  10234. return result;
  10235. };
  10236. /**
  10237. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  10238. * @see http://mathworld.wolfram.com/HermitePolynomial.html
  10239. * @param value1 spline value
  10240. * @param tangent1 spline value
  10241. * @param value2 spline value
  10242. * @param tangent2 spline value
  10243. * @param amount input value
  10244. * @returns hermite result
  10245. */
  10246. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  10247. var squared = amount * amount;
  10248. var cubed = amount * squared;
  10249. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  10250. var part2 = (-2.0 * cubed) + (3.0 * squared);
  10251. var part3 = (cubed - (2.0 * squared)) + amount;
  10252. var part4 = cubed - squared;
  10253. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  10254. };
  10255. /**
  10256. * Returns a random float number between and min and max values
  10257. * @param min min value of random
  10258. * @param max max value of random
  10259. * @returns random value
  10260. */
  10261. Scalar.RandomRange = function (min, max) {
  10262. if (min === max) {
  10263. return min;
  10264. }
  10265. return ((Math.random() * (max - min)) + min);
  10266. };
  10267. /**
  10268. * This function returns percentage of a number in a given range.
  10269. *
  10270. * RangeToPercent(40,20,60) will return 0.5 (50%)
  10271. * RangeToPercent(34,0,100) will return 0.34 (34%)
  10272. * @param number to convert to percentage
  10273. * @param min min range
  10274. * @param max max range
  10275. * @returns the percentage
  10276. */
  10277. Scalar.RangeToPercent = function (number, min, max) {
  10278. return ((number - min) / (max - min));
  10279. };
  10280. /**
  10281. * This function returns number that corresponds to the percentage in a given range.
  10282. *
  10283. * PercentToRange(0.34,0,100) will return 34.
  10284. * @param percent to convert to number
  10285. * @param min min range
  10286. * @param max max range
  10287. * @returns the number
  10288. */
  10289. Scalar.PercentToRange = function (percent, min, max) {
  10290. return ((max - min) * percent + min);
  10291. };
  10292. /**
  10293. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  10294. * @param angle The angle to normalize in radian.
  10295. * @return The converted angle.
  10296. */
  10297. Scalar.NormalizeRadians = function (angle) {
  10298. // More precise but slower version kept for reference.
  10299. // angle = angle % Tools.TwoPi;
  10300. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  10301. //if (angle > Math.PI) {
  10302. // angle -= Tools.TwoPi;
  10303. //}
  10304. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  10305. return angle;
  10306. };
  10307. /**
  10308. * Two pi constants convenient for computation.
  10309. */
  10310. Scalar.TwoPi = Math.PI * 2;
  10311. return Scalar;
  10312. }());
  10313. BABYLON.Scalar = Scalar;
  10314. })(BABYLON || (BABYLON = {}));
  10315. //# sourceMappingURL=babylon.math.scalar.js.map
  10316. //# sourceMappingURL=babylon.mixins.js.map
  10317. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  10318. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  10319. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  10320. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  10321. //# sourceMappingURL=babylon.webgl2.js.map
  10322. var BABYLON;
  10323. (function (BABYLON) {
  10324. var __decoratorInitialStore = {};
  10325. var __mergedStore = {};
  10326. var _copySource = function (creationFunction, source, instanciate) {
  10327. var destination = creationFunction();
  10328. // Tags
  10329. if (BABYLON.Tags) {
  10330. BABYLON.Tags.AddTagsTo(destination, source.tags);
  10331. }
  10332. var classStore = getMergedStore(destination);
  10333. // Properties
  10334. for (var property in classStore) {
  10335. var propertyDescriptor = classStore[property];
  10336. var sourceProperty = source[property];
  10337. var propertyType = propertyDescriptor.type;
  10338. if (sourceProperty !== undefined && sourceProperty !== null) {
  10339. switch (propertyType) {
  10340. case 0: // Value
  10341. case 6: // Mesh reference
  10342. case 11: // Camera reference
  10343. destination[property] = sourceProperty;
  10344. break;
  10345. case 1: // Texture
  10346. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  10347. break;
  10348. case 2: // Color3
  10349. case 3: // FresnelParameters
  10350. case 4: // Vector2
  10351. case 5: // Vector3
  10352. case 7: // Color Curves
  10353. case 10: // Quaternion
  10354. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  10355. break;
  10356. }
  10357. }
  10358. }
  10359. return destination;
  10360. };
  10361. function getDirectStore(target) {
  10362. var classKey = target.getClassName();
  10363. if (!__decoratorInitialStore[classKey]) {
  10364. __decoratorInitialStore[classKey] = {};
  10365. }
  10366. return __decoratorInitialStore[classKey];
  10367. }
  10368. /**
  10369. * Return the list of properties flagged as serializable
  10370. * @param target: host object
  10371. */
  10372. function getMergedStore(target) {
  10373. var classKey = target.getClassName();
  10374. if (__mergedStore[classKey]) {
  10375. return __mergedStore[classKey];
  10376. }
  10377. __mergedStore[classKey] = {};
  10378. var store = __mergedStore[classKey];
  10379. var currentTarget = target;
  10380. var currentKey = classKey;
  10381. while (currentKey) {
  10382. var initialStore = __decoratorInitialStore[currentKey];
  10383. for (var property in initialStore) {
  10384. store[property] = initialStore[property];
  10385. }
  10386. var parent_1 = void 0;
  10387. var done = false;
  10388. do {
  10389. parent_1 = Object.getPrototypeOf(currentTarget);
  10390. if (!parent_1.getClassName) {
  10391. done = true;
  10392. break;
  10393. }
  10394. if (parent_1.getClassName() !== currentKey) {
  10395. break;
  10396. }
  10397. currentTarget = parent_1;
  10398. } while (parent_1);
  10399. if (done) {
  10400. break;
  10401. }
  10402. currentKey = parent_1.getClassName();
  10403. currentTarget = parent_1;
  10404. }
  10405. return store;
  10406. }
  10407. function generateSerializableMember(type, sourceName) {
  10408. return function (target, propertyKey) {
  10409. var classStore = getDirectStore(target);
  10410. if (!classStore[propertyKey]) {
  10411. classStore[propertyKey] = { type: type, sourceName: sourceName };
  10412. }
  10413. };
  10414. }
  10415. function generateExpandMember(setCallback, targetKey) {
  10416. if (targetKey === void 0) { targetKey = null; }
  10417. return function (target, propertyKey) {
  10418. var key = targetKey || ("_" + propertyKey);
  10419. Object.defineProperty(target, propertyKey, {
  10420. get: function () {
  10421. return this[key];
  10422. },
  10423. set: function (value) {
  10424. if (this[key] === value) {
  10425. return;
  10426. }
  10427. this[key] = value;
  10428. target[setCallback].apply(this);
  10429. },
  10430. enumerable: true,
  10431. configurable: true
  10432. });
  10433. };
  10434. }
  10435. function expandToProperty(callback, targetKey) {
  10436. if (targetKey === void 0) { targetKey = null; }
  10437. return generateExpandMember(callback, targetKey);
  10438. }
  10439. BABYLON.expandToProperty = expandToProperty;
  10440. function serialize(sourceName) {
  10441. return generateSerializableMember(0, sourceName); // value member
  10442. }
  10443. BABYLON.serialize = serialize;
  10444. function serializeAsTexture(sourceName) {
  10445. return generateSerializableMember(1, sourceName); // texture member
  10446. }
  10447. BABYLON.serializeAsTexture = serializeAsTexture;
  10448. function serializeAsColor3(sourceName) {
  10449. return generateSerializableMember(2, sourceName); // color3 member
  10450. }
  10451. BABYLON.serializeAsColor3 = serializeAsColor3;
  10452. function serializeAsFresnelParameters(sourceName) {
  10453. return generateSerializableMember(3, sourceName); // fresnel parameters member
  10454. }
  10455. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  10456. function serializeAsVector2(sourceName) {
  10457. return generateSerializableMember(4, sourceName); // vector2 member
  10458. }
  10459. BABYLON.serializeAsVector2 = serializeAsVector2;
  10460. function serializeAsVector3(sourceName) {
  10461. return generateSerializableMember(5, sourceName); // vector3 member
  10462. }
  10463. BABYLON.serializeAsVector3 = serializeAsVector3;
  10464. function serializeAsMeshReference(sourceName) {
  10465. return generateSerializableMember(6, sourceName); // mesh reference member
  10466. }
  10467. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  10468. function serializeAsColorCurves(sourceName) {
  10469. return generateSerializableMember(7, sourceName); // color curves
  10470. }
  10471. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  10472. function serializeAsColor4(sourceName) {
  10473. return generateSerializableMember(8, sourceName); // color 4
  10474. }
  10475. BABYLON.serializeAsColor4 = serializeAsColor4;
  10476. function serializeAsImageProcessingConfiguration(sourceName) {
  10477. return generateSerializableMember(9, sourceName); // image processing
  10478. }
  10479. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  10480. function serializeAsQuaternion(sourceName) {
  10481. return generateSerializableMember(10, sourceName); // quaternion member
  10482. }
  10483. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  10484. /**
  10485. * Decorator used to define property that can be serialized as reference to a camera
  10486. * @param sourceName defines the name of the property to decorate
  10487. */
  10488. function serializeAsCameraReference(sourceName) {
  10489. return generateSerializableMember(11, sourceName); // camera reference member
  10490. }
  10491. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  10492. /**
  10493. * Class used to help serialization objects
  10494. */
  10495. var SerializationHelper = /** @class */ (function () {
  10496. function SerializationHelper() {
  10497. }
  10498. /**
  10499. * Static function used to serialized a specific entity
  10500. * @param entity defines the entity to serialize
  10501. * @param serializationObject defines the optional target obecjt where serialization data will be stored
  10502. * @returns a JSON compatible object representing the serialization of the entity
  10503. */
  10504. SerializationHelper.Serialize = function (entity, serializationObject) {
  10505. if (!serializationObject) {
  10506. serializationObject = {};
  10507. }
  10508. // Tags
  10509. if (BABYLON.Tags) {
  10510. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  10511. }
  10512. var serializedProperties = getMergedStore(entity);
  10513. // Properties
  10514. for (var property in serializedProperties) {
  10515. var propertyDescriptor = serializedProperties[property];
  10516. var targetPropertyName = propertyDescriptor.sourceName || property;
  10517. var propertyType = propertyDescriptor.type;
  10518. var sourceProperty = entity[property];
  10519. if (sourceProperty !== undefined && sourceProperty !== null) {
  10520. switch (propertyType) {
  10521. case 0: // Value
  10522. serializationObject[targetPropertyName] = sourceProperty;
  10523. break;
  10524. case 1: // Texture
  10525. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10526. break;
  10527. case 2: // Color3
  10528. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10529. break;
  10530. case 3: // FresnelParameters
  10531. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10532. break;
  10533. case 4: // Vector2
  10534. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10535. break;
  10536. case 5: // Vector3
  10537. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10538. break;
  10539. case 6: // Mesh reference
  10540. serializationObject[targetPropertyName] = sourceProperty.id;
  10541. break;
  10542. case 7: // Color Curves
  10543. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10544. break;
  10545. case 8: // Color 4
  10546. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10547. break;
  10548. case 9: // Image Processing
  10549. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10550. break;
  10551. case 10: // Quaternion
  10552. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10553. break;
  10554. case 11: // Camera reference
  10555. serializationObject[targetPropertyName] = sourceProperty.id;
  10556. break;
  10557. }
  10558. }
  10559. }
  10560. return serializationObject;
  10561. };
  10562. /**
  10563. * Creates a new entity from a serialization data object
  10564. * @param creationFunction defines a function used to instanciated the new entity
  10565. * @param source defines the source serialization data
  10566. * @param scene defines the hosting scene
  10567. * @param rootUrl defines the root url for resources
  10568. * @returns a new entity
  10569. */
  10570. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  10571. if (rootUrl === void 0) { rootUrl = null; }
  10572. var destination = creationFunction();
  10573. if (!rootUrl) {
  10574. rootUrl = "";
  10575. }
  10576. // Tags
  10577. if (BABYLON.Tags) {
  10578. BABYLON.Tags.AddTagsTo(destination, source.tags);
  10579. }
  10580. var classStore = getMergedStore(destination);
  10581. // Properties
  10582. for (var property in classStore) {
  10583. var propertyDescriptor = classStore[property];
  10584. var sourceProperty = source[propertyDescriptor.sourceName || property];
  10585. var propertyType = propertyDescriptor.type;
  10586. if (sourceProperty !== undefined && sourceProperty !== null) {
  10587. var dest = destination;
  10588. switch (propertyType) {
  10589. case 0: // Value
  10590. dest[property] = sourceProperty;
  10591. break;
  10592. case 1: // Texture
  10593. if (scene) {
  10594. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  10595. }
  10596. break;
  10597. case 2: // Color3
  10598. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  10599. break;
  10600. case 3: // FresnelParameters
  10601. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  10602. break;
  10603. case 4: // Vector2
  10604. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  10605. break;
  10606. case 5: // Vector3
  10607. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  10608. break;
  10609. case 6: // Mesh reference
  10610. if (scene) {
  10611. dest[property] = scene.getLastMeshByID(sourceProperty);
  10612. }
  10613. break;
  10614. case 7: // Color Curves
  10615. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  10616. break;
  10617. case 8: // Color 4
  10618. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  10619. break;
  10620. case 9: // Image Processing
  10621. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  10622. break;
  10623. case 10: // Quaternion
  10624. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  10625. break;
  10626. case 11: // Camera reference
  10627. if (scene) {
  10628. dest[property] = scene.getCameraByID(sourceProperty);
  10629. }
  10630. break;
  10631. }
  10632. }
  10633. }
  10634. return destination;
  10635. };
  10636. /**
  10637. * Clones an object
  10638. * @param creationFunction defines the function used to instanciate the new object
  10639. * @param source defines the source object
  10640. * @returns the cloned object
  10641. */
  10642. SerializationHelper.Clone = function (creationFunction, source) {
  10643. return _copySource(creationFunction, source, false);
  10644. };
  10645. /**
  10646. * Instanciates a new object based on a source one (some data will be shared between both object)
  10647. * @param creationFunction defines the function used to instanciate the new object
  10648. * @param source defines the source object
  10649. * @returns the new object
  10650. */
  10651. SerializationHelper.Instanciate = function (creationFunction, source) {
  10652. return _copySource(creationFunction, source, true);
  10653. };
  10654. return SerializationHelper;
  10655. }());
  10656. BABYLON.SerializationHelper = SerializationHelper;
  10657. })(BABYLON || (BABYLON = {}));
  10658. //# sourceMappingURL=babylon.decorators.js.map
  10659. var BABYLON;
  10660. (function (BABYLON) {
  10661. /**
  10662. * Wrapper class for promise with external resolve and reject.
  10663. */
  10664. var Deferred = /** @class */ (function () {
  10665. /**
  10666. * Constructor for this deferred object.
  10667. */
  10668. function Deferred() {
  10669. var _this = this;
  10670. this.promise = new Promise(function (resolve, reject) {
  10671. _this._resolve = resolve;
  10672. _this._reject = reject;
  10673. });
  10674. }
  10675. Object.defineProperty(Deferred.prototype, "resolve", {
  10676. /**
  10677. * The resolve method of the promise associated with this deferred object.
  10678. */
  10679. get: function () {
  10680. return this._resolve;
  10681. },
  10682. enumerable: true,
  10683. configurable: true
  10684. });
  10685. Object.defineProperty(Deferred.prototype, "reject", {
  10686. /**
  10687. * The reject method of the promise associated with this deferred object.
  10688. */
  10689. get: function () {
  10690. return this._reject;
  10691. },
  10692. enumerable: true,
  10693. configurable: true
  10694. });
  10695. return Deferred;
  10696. }());
  10697. BABYLON.Deferred = Deferred;
  10698. })(BABYLON || (BABYLON = {}));
  10699. //# sourceMappingURL=babylon.deferred.js.map
  10700. var BABYLON;
  10701. (function (BABYLON) {
  10702. /**
  10703. * A class serves as a medium between the observable and its observers
  10704. */
  10705. var EventState = /** @class */ (function () {
  10706. /**
  10707. * Create a new EventState
  10708. * @param mask defines the mask associated with this state
  10709. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  10710. * @param target defines the original target of the state
  10711. * @param currentTarget defines the current target of the state
  10712. */
  10713. function EventState(mask, skipNextObservers, target, currentTarget) {
  10714. if (skipNextObservers === void 0) { skipNextObservers = false; }
  10715. this.initalize(mask, skipNextObservers, target, currentTarget);
  10716. }
  10717. /**
  10718. * Initialize the current event state
  10719. * @param mask defines the mask associated with this state
  10720. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  10721. * @param target defines the original target of the state
  10722. * @param currentTarget defines the current target of the state
  10723. * @returns the current event state
  10724. */
  10725. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  10726. if (skipNextObservers === void 0) { skipNextObservers = false; }
  10727. this.mask = mask;
  10728. this.skipNextObservers = skipNextObservers;
  10729. this.target = target;
  10730. this.currentTarget = currentTarget;
  10731. return this;
  10732. };
  10733. return EventState;
  10734. }());
  10735. BABYLON.EventState = EventState;
  10736. /**
  10737. * Represent an Observer registered to a given Observable object.
  10738. */
  10739. var Observer = /** @class */ (function () {
  10740. /**
  10741. * Creates a new observer
  10742. * @param callback defines the callback to call when the observer is notified
  10743. * @param mask defines the mask of the observer (used to filter notifications)
  10744. * @param scope defines the current scope used to restore the JS context
  10745. */
  10746. function Observer(
  10747. /**
  10748. * Defines the callback to call when the observer is notified
  10749. */
  10750. callback,
  10751. /**
  10752. * Defines the mask of the observer (used to filter notifications)
  10753. */
  10754. mask,
  10755. /**
  10756. * Defines the current scope used to restore the JS context
  10757. */
  10758. scope) {
  10759. if (scope === void 0) { scope = null; }
  10760. this.callback = callback;
  10761. this.mask = mask;
  10762. this.scope = scope;
  10763. /** @hidden */
  10764. this._willBeUnregistered = false;
  10765. /**
  10766. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  10767. */
  10768. this.unregisterOnNextCall = false;
  10769. }
  10770. return Observer;
  10771. }());
  10772. BABYLON.Observer = Observer;
  10773. /**
  10774. * Represent a list of observers registered to multiple Observables object.
  10775. */
  10776. var MultiObserver = /** @class */ (function () {
  10777. function MultiObserver() {
  10778. }
  10779. /**
  10780. * Release associated resources
  10781. */
  10782. MultiObserver.prototype.dispose = function () {
  10783. if (this._observers && this._observables) {
  10784. for (var index = 0; index < this._observers.length; index++) {
  10785. this._observables[index].remove(this._observers[index]);
  10786. }
  10787. }
  10788. this._observers = null;
  10789. this._observables = null;
  10790. };
  10791. /**
  10792. * Raise a callback when one of the observable will notify
  10793. * @param observables defines a list of observables to watch
  10794. * @param callback defines the callback to call on notification
  10795. * @param mask defines the mask used to filter notifications
  10796. * @param scope defines the current scope used to restore the JS context
  10797. * @returns the new MultiObserver
  10798. */
  10799. MultiObserver.Watch = function (observables, callback, mask, scope) {
  10800. if (mask === void 0) { mask = -1; }
  10801. if (scope === void 0) { scope = null; }
  10802. var result = new MultiObserver();
  10803. result._observers = new Array();
  10804. result._observables = observables;
  10805. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  10806. var observable = observables_1[_i];
  10807. var observer = observable.add(callback, mask, false, scope);
  10808. if (observer) {
  10809. result._observers.push(observer);
  10810. }
  10811. }
  10812. return result;
  10813. };
  10814. return MultiObserver;
  10815. }());
  10816. BABYLON.MultiObserver = MultiObserver;
  10817. /**
  10818. * The Observable class is a simple implementation of the Observable pattern.
  10819. *
  10820. * 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.
  10821. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  10822. * 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).
  10823. * 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.
  10824. */
  10825. var Observable = /** @class */ (function () {
  10826. /**
  10827. * Creates a new observable
  10828. * @param onObserverAdded defines a callback to call when a new observer is added
  10829. */
  10830. function Observable(onObserverAdded) {
  10831. this._observers = new Array();
  10832. this._eventState = new EventState(0);
  10833. if (onObserverAdded) {
  10834. this._onObserverAdded = onObserverAdded;
  10835. }
  10836. }
  10837. /**
  10838. * Create a new Observer with the specified callback
  10839. * @param callback the callback that will be executed for that Observer
  10840. * @param mask the mask used to filter observers
  10841. * @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.
  10842. * @param scope optional scope for the callback to be called from
  10843. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  10844. * @returns the new observer created for the callback
  10845. */
  10846. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  10847. if (mask === void 0) { mask = -1; }
  10848. if (insertFirst === void 0) { insertFirst = false; }
  10849. if (scope === void 0) { scope = null; }
  10850. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  10851. if (!callback) {
  10852. return null;
  10853. }
  10854. var observer = new Observer(callback, mask, scope);
  10855. observer.unregisterOnNextCall = unregisterOnFirstCall;
  10856. if (insertFirst) {
  10857. this._observers.unshift(observer);
  10858. }
  10859. else {
  10860. this._observers.push(observer);
  10861. }
  10862. if (this._onObserverAdded) {
  10863. this._onObserverAdded(observer);
  10864. }
  10865. return observer;
  10866. };
  10867. /**
  10868. * Create a new Observer with the specified callback and unregisters after the next notification
  10869. * @param callback the callback that will be executed for that Observer
  10870. * @returns the new observer created for the callback
  10871. */
  10872. Observable.prototype.addOnce = function (callback) {
  10873. return this.add(callback, undefined, undefined, undefined, true);
  10874. };
  10875. /**
  10876. * Remove an Observer from the Observable object
  10877. * @param observer the instance of the Observer to remove
  10878. * @returns false if it doesn't belong to this Observable
  10879. */
  10880. Observable.prototype.remove = function (observer) {
  10881. if (!observer) {
  10882. return false;
  10883. }
  10884. var index = this._observers.indexOf(observer);
  10885. if (index !== -1) {
  10886. this._deferUnregister(observer);
  10887. return true;
  10888. }
  10889. return false;
  10890. };
  10891. /**
  10892. * Remove a callback from the Observable object
  10893. * @param callback the callback to remove
  10894. * @param scope optional scope. If used only the callbacks with this scope will be removed
  10895. * @returns false if it doesn't belong to this Observable
  10896. */
  10897. Observable.prototype.removeCallback = function (callback, scope) {
  10898. for (var index = 0; index < this._observers.length; index++) {
  10899. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  10900. this._deferUnregister(this._observers[index]);
  10901. return true;
  10902. }
  10903. }
  10904. return false;
  10905. };
  10906. Observable.prototype._deferUnregister = function (observer) {
  10907. var _this = this;
  10908. observer.unregisterOnNextCall = false;
  10909. observer._willBeUnregistered = true;
  10910. BABYLON.Tools.SetImmediate(function () {
  10911. _this._remove(observer);
  10912. });
  10913. };
  10914. // This should only be called when not iterating over _observers to avoid callback skipping.
  10915. // Removes an observer from the _observer Array.
  10916. Observable.prototype._remove = function (observer) {
  10917. if (!observer) {
  10918. return false;
  10919. }
  10920. var index = this._observers.indexOf(observer);
  10921. if (index !== -1) {
  10922. this._observers.splice(index, 1);
  10923. return true;
  10924. }
  10925. return false;
  10926. };
  10927. /**
  10928. * Notify all Observers by calling their respective callback with the given data
  10929. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  10930. * @param eventData defines the data to send to all observers
  10931. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  10932. * @param target defines the original target of the state
  10933. * @param currentTarget defines the current target of the state
  10934. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  10935. */
  10936. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  10937. if (mask === void 0) { mask = -1; }
  10938. if (!this._observers.length) {
  10939. return true;
  10940. }
  10941. var state = this._eventState;
  10942. state.mask = mask;
  10943. state.target = target;
  10944. state.currentTarget = currentTarget;
  10945. state.skipNextObservers = false;
  10946. state.lastReturnValue = eventData;
  10947. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  10948. var obs = _a[_i];
  10949. if (obs._willBeUnregistered) {
  10950. continue;
  10951. }
  10952. if (obs.mask & mask) {
  10953. if (obs.scope) {
  10954. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  10955. }
  10956. else {
  10957. state.lastReturnValue = obs.callback(eventData, state);
  10958. }
  10959. if (obs.unregisterOnNextCall) {
  10960. this._deferUnregister(obs);
  10961. }
  10962. }
  10963. if (state.skipNextObservers) {
  10964. return false;
  10965. }
  10966. }
  10967. return true;
  10968. };
  10969. /**
  10970. * Calling this will execute each callback, expecting it to be a promise or return a value.
  10971. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  10972. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  10973. * and it is crucial that all callbacks will be executed.
  10974. * The order of the callbacks is kept, callbacks are not executed parallel.
  10975. *
  10976. * @param eventData The data to be sent to each callback
  10977. * @param mask is used to filter observers defaults to -1
  10978. * @param target defines the callback target (see EventState)
  10979. * @param currentTarget defines he current object in the bubbling phase
  10980. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  10981. */
  10982. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  10983. var _this = this;
  10984. if (mask === void 0) { mask = -1; }
  10985. // create an empty promise
  10986. var p = Promise.resolve(eventData);
  10987. // no observers? return this promise.
  10988. if (!this._observers.length) {
  10989. return p;
  10990. }
  10991. var state = this._eventState;
  10992. state.mask = mask;
  10993. state.target = target;
  10994. state.currentTarget = currentTarget;
  10995. state.skipNextObservers = false;
  10996. // execute one callback after another (not using Promise.all, the order is important)
  10997. this._observers.forEach(function (obs) {
  10998. if (state.skipNextObservers) {
  10999. return;
  11000. }
  11001. if (obs._willBeUnregistered) {
  11002. return;
  11003. }
  11004. if (obs.mask & mask) {
  11005. if (obs.scope) {
  11006. p = p.then(function (lastReturnedValue) {
  11007. state.lastReturnValue = lastReturnedValue;
  11008. return obs.callback.apply(obs.scope, [eventData, state]);
  11009. });
  11010. }
  11011. else {
  11012. p = p.then(function (lastReturnedValue) {
  11013. state.lastReturnValue = lastReturnedValue;
  11014. return obs.callback(eventData, state);
  11015. });
  11016. }
  11017. if (obs.unregisterOnNextCall) {
  11018. _this._deferUnregister(obs);
  11019. }
  11020. }
  11021. });
  11022. // return the eventData
  11023. return p.then(function () { return eventData; });
  11024. };
  11025. /**
  11026. * Notify a specific observer
  11027. * @param observer defines the observer to notify
  11028. * @param eventData defines the data to be sent to each callback
  11029. * @param mask is used to filter observers defaults to -1
  11030. */
  11031. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  11032. if (mask === void 0) { mask = -1; }
  11033. var state = this._eventState;
  11034. state.mask = mask;
  11035. state.skipNextObservers = false;
  11036. observer.callback(eventData, state);
  11037. };
  11038. /**
  11039. * Gets a boolean indicating if the observable has at least one observer
  11040. * @returns true is the Observable has at least one Observer registered
  11041. */
  11042. Observable.prototype.hasObservers = function () {
  11043. return this._observers.length > 0;
  11044. };
  11045. /**
  11046. * Clear the list of observers
  11047. */
  11048. Observable.prototype.clear = function () {
  11049. this._observers = new Array();
  11050. this._onObserverAdded = null;
  11051. };
  11052. /**
  11053. * Clone the current observable
  11054. * @returns a new observable
  11055. */
  11056. Observable.prototype.clone = function () {
  11057. var result = new Observable();
  11058. result._observers = this._observers.slice(0);
  11059. return result;
  11060. };
  11061. /**
  11062. * Does this observable handles observer registered with a given mask
  11063. * @param mask defines the mask to be tested
  11064. * @return whether or not one observer registered with the given mask is handeled
  11065. **/
  11066. Observable.prototype.hasSpecificMask = function (mask) {
  11067. if (mask === void 0) { mask = -1; }
  11068. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  11069. var obs = _a[_i];
  11070. if (obs.mask & mask || obs.mask === mask) {
  11071. return true;
  11072. }
  11073. }
  11074. return false;
  11075. };
  11076. return Observable;
  11077. }());
  11078. BABYLON.Observable = Observable;
  11079. })(BABYLON || (BABYLON = {}));
  11080. //# sourceMappingURL=babylon.observable.js.map
  11081. var BABYLON;
  11082. (function (BABYLON) {
  11083. /**
  11084. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  11085. */
  11086. var SmartArray = /** @class */ (function () {
  11087. /**
  11088. * Instantiates a Smart Array.
  11089. * @param capacity defines the default capacity of the array.
  11090. */
  11091. function SmartArray(capacity) {
  11092. /**
  11093. * The active length of the array.
  11094. */
  11095. this.length = 0;
  11096. this.data = new Array(capacity);
  11097. this._id = SmartArray._GlobalId++;
  11098. }
  11099. /**
  11100. * Pushes a value at the end of the active data.
  11101. * @param value defines the object to push in the array.
  11102. */
  11103. SmartArray.prototype.push = function (value) {
  11104. this.data[this.length++] = value;
  11105. if (this.length > this.data.length) {
  11106. this.data.length *= 2;
  11107. }
  11108. };
  11109. /**
  11110. * Iterates over the active data and apply the lambda to them.
  11111. * @param func defines the action to apply on each value.
  11112. */
  11113. SmartArray.prototype.forEach = function (func) {
  11114. for (var index = 0; index < this.length; index++) {
  11115. func(this.data[index]);
  11116. }
  11117. };
  11118. /**
  11119. * Sorts the full sets of data.
  11120. * @param compareFn defines the comparison function to apply.
  11121. */
  11122. SmartArray.prototype.sort = function (compareFn) {
  11123. this.data.sort(compareFn);
  11124. };
  11125. /**
  11126. * Resets the active data to an empty array.
  11127. */
  11128. SmartArray.prototype.reset = function () {
  11129. this.length = 0;
  11130. };
  11131. /**
  11132. * Releases all the data from the array as well as the array.
  11133. */
  11134. SmartArray.prototype.dispose = function () {
  11135. this.reset();
  11136. if (this.data) {
  11137. this.data.length = 0;
  11138. this.data = [];
  11139. }
  11140. };
  11141. /**
  11142. * Concats the active data with a given array.
  11143. * @param array defines the data to concatenate with.
  11144. */
  11145. SmartArray.prototype.concat = function (array) {
  11146. if (array.length === 0) {
  11147. return;
  11148. }
  11149. if (this.length + array.length > this.data.length) {
  11150. this.data.length = (this.length + array.length) * 2;
  11151. }
  11152. for (var index = 0; index < array.length; index++) {
  11153. this.data[this.length++] = (array.data || array)[index];
  11154. }
  11155. };
  11156. /**
  11157. * Returns the position of a value in the active data.
  11158. * @param value defines the value to find the index for
  11159. * @returns the index if found in the active data otherwise -1
  11160. */
  11161. SmartArray.prototype.indexOf = function (value) {
  11162. var position = this.data.indexOf(value);
  11163. if (position >= this.length) {
  11164. return -1;
  11165. }
  11166. return position;
  11167. };
  11168. /**
  11169. * Returns whether an element is part of the active data.
  11170. * @param value defines the value to look for
  11171. * @returns true if found in the active data otherwise false
  11172. */
  11173. SmartArray.prototype.contains = function (value) {
  11174. return this.indexOf(value) !== -1;
  11175. };
  11176. // Statics
  11177. SmartArray._GlobalId = 0;
  11178. return SmartArray;
  11179. }());
  11180. BABYLON.SmartArray = SmartArray;
  11181. /**
  11182. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  11183. * The data in this array can only be present once
  11184. */
  11185. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  11186. __extends(SmartArrayNoDuplicate, _super);
  11187. function SmartArrayNoDuplicate() {
  11188. var _this = _super !== null && _super.apply(this, arguments) || this;
  11189. _this._duplicateId = 0;
  11190. return _this;
  11191. }
  11192. /**
  11193. * Pushes a value at the end of the active data.
  11194. * THIS DOES NOT PREVENT DUPPLICATE DATA
  11195. * @param value defines the object to push in the array.
  11196. */
  11197. SmartArrayNoDuplicate.prototype.push = function (value) {
  11198. _super.prototype.push.call(this, value);
  11199. if (!value.__smartArrayFlags) {
  11200. value.__smartArrayFlags = {};
  11201. }
  11202. value.__smartArrayFlags[this._id] = this._duplicateId;
  11203. };
  11204. /**
  11205. * Pushes a value at the end of the active data.
  11206. * If the data is already present, it won t be added again
  11207. * @param value defines the object to push in the array.
  11208. * @returns true if added false if it was already present
  11209. */
  11210. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  11211. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  11212. return false;
  11213. }
  11214. this.push(value);
  11215. return true;
  11216. };
  11217. /**
  11218. * Resets the active data to an empty array.
  11219. */
  11220. SmartArrayNoDuplicate.prototype.reset = function () {
  11221. _super.prototype.reset.call(this);
  11222. this._duplicateId++;
  11223. };
  11224. /**
  11225. * Concats the active data with a given array.
  11226. * This ensures no dupplicate will be present in the result.
  11227. * @param array defines the data to concatenate with.
  11228. */
  11229. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  11230. if (array.length === 0) {
  11231. return;
  11232. }
  11233. if (this.length + array.length > this.data.length) {
  11234. this.data.length = (this.length + array.length) * 2;
  11235. }
  11236. for (var index = 0; index < array.length; index++) {
  11237. var item = (array.data || array)[index];
  11238. this.pushNoDuplicate(item);
  11239. }
  11240. };
  11241. return SmartArrayNoDuplicate;
  11242. }(SmartArray));
  11243. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  11244. })(BABYLON || (BABYLON = {}));
  11245. //# sourceMappingURL=babylon.smartArray.js.map
  11246. var BABYLON;
  11247. (function (BABYLON) {
  11248. var PromiseStates;
  11249. (function (PromiseStates) {
  11250. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11251. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11252. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11253. })(PromiseStates || (PromiseStates = {}));
  11254. var FulFillmentAgregator = /** @class */ (function () {
  11255. function FulFillmentAgregator() {
  11256. this.count = 0;
  11257. this.target = 0;
  11258. this.results = [];
  11259. }
  11260. return FulFillmentAgregator;
  11261. }());
  11262. var InternalPromise = /** @class */ (function () {
  11263. function InternalPromise(resolver) {
  11264. var _this = this;
  11265. this._state = PromiseStates.Pending;
  11266. this._children = new Array();
  11267. this._rejectWasConsumed = false;
  11268. if (!resolver) {
  11269. return;
  11270. }
  11271. try {
  11272. resolver(function (value) {
  11273. _this._resolve(value);
  11274. }, function (reason) {
  11275. _this._reject(reason);
  11276. });
  11277. }
  11278. catch (e) {
  11279. this._reject(e);
  11280. }
  11281. }
  11282. Object.defineProperty(InternalPromise.prototype, "_result", {
  11283. get: function () {
  11284. return this._resultValue;
  11285. },
  11286. set: function (value) {
  11287. this._resultValue = value;
  11288. if (this._parent && this._parent._result === undefined) {
  11289. this._parent._result = value;
  11290. }
  11291. },
  11292. enumerable: true,
  11293. configurable: true
  11294. });
  11295. InternalPromise.prototype.catch = function (onRejected) {
  11296. return this.then(undefined, onRejected);
  11297. };
  11298. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11299. var _this = this;
  11300. var newPromise = new InternalPromise();
  11301. newPromise._onFulfilled = onFulfilled;
  11302. newPromise._onRejected = onRejected;
  11303. // Composition
  11304. this._children.push(newPromise);
  11305. newPromise._parent = this;
  11306. if (this._state !== PromiseStates.Pending) {
  11307. BABYLON.Tools.SetImmediate(function () {
  11308. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11309. var returnedValue = newPromise._resolve(_this._result);
  11310. if (returnedValue !== undefined && returnedValue !== null) {
  11311. if (returnedValue._state !== undefined) {
  11312. var returnedPromise = returnedValue;
  11313. newPromise._children.push(returnedPromise);
  11314. returnedPromise._parent = newPromise;
  11315. newPromise = returnedPromise;
  11316. }
  11317. else {
  11318. newPromise._result = returnedValue;
  11319. }
  11320. }
  11321. }
  11322. else {
  11323. newPromise._reject(_this._reason);
  11324. }
  11325. });
  11326. }
  11327. return newPromise;
  11328. };
  11329. InternalPromise.prototype._moveChildren = function (children) {
  11330. var _this = this;
  11331. var _a;
  11332. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11333. this._children.forEach(function (child) {
  11334. child._parent = _this;
  11335. });
  11336. if (this._state === PromiseStates.Fulfilled) {
  11337. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11338. var child = _b[_i];
  11339. child._resolve(this._result);
  11340. }
  11341. }
  11342. else if (this._state === PromiseStates.Rejected) {
  11343. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11344. var child = _d[_c];
  11345. child._reject(this._reason);
  11346. }
  11347. }
  11348. };
  11349. InternalPromise.prototype._resolve = function (value) {
  11350. try {
  11351. this._state = PromiseStates.Fulfilled;
  11352. var returnedValue = null;
  11353. if (this._onFulfilled) {
  11354. returnedValue = this._onFulfilled(value);
  11355. }
  11356. if (returnedValue !== undefined && returnedValue !== null) {
  11357. if (returnedValue._state !== undefined) {
  11358. // Transmit children
  11359. var returnedPromise = returnedValue;
  11360. returnedPromise._parent = this;
  11361. returnedPromise._moveChildren(this._children);
  11362. value = returnedPromise._result;
  11363. }
  11364. else {
  11365. value = returnedValue;
  11366. }
  11367. }
  11368. this._result = value;
  11369. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11370. var child = _a[_i];
  11371. child._resolve(value);
  11372. }
  11373. this._children.length = 0;
  11374. delete this._onFulfilled;
  11375. delete this._onRejected;
  11376. }
  11377. catch (e) {
  11378. this._reject(e, true);
  11379. }
  11380. };
  11381. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11382. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11383. this._state = PromiseStates.Rejected;
  11384. this._reason = reason;
  11385. if (this._onRejected && !onLocalThrow) {
  11386. try {
  11387. this._onRejected(reason);
  11388. this._rejectWasConsumed = true;
  11389. }
  11390. catch (e) {
  11391. reason = e;
  11392. }
  11393. }
  11394. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11395. var child = _a[_i];
  11396. if (this._rejectWasConsumed) {
  11397. child._resolve(null);
  11398. }
  11399. else {
  11400. child._reject(reason);
  11401. }
  11402. }
  11403. this._children.length = 0;
  11404. delete this._onFulfilled;
  11405. delete this._onRejected;
  11406. };
  11407. InternalPromise.resolve = function (value) {
  11408. var newPromise = new InternalPromise();
  11409. newPromise._resolve(value);
  11410. return newPromise;
  11411. };
  11412. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11413. promise.then(function (value) {
  11414. agregator.results[index] = value;
  11415. agregator.count++;
  11416. if (agregator.count === agregator.target) {
  11417. agregator.rootPromise._resolve(agregator.results);
  11418. }
  11419. return null;
  11420. }, function (reason) {
  11421. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11422. agregator.rootPromise._reject(reason);
  11423. }
  11424. });
  11425. };
  11426. InternalPromise.all = function (promises) {
  11427. var newPromise = new InternalPromise();
  11428. var agregator = new FulFillmentAgregator();
  11429. agregator.target = promises.length;
  11430. agregator.rootPromise = newPromise;
  11431. if (promises.length) {
  11432. for (var index = 0; index < promises.length; index++) {
  11433. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11434. }
  11435. }
  11436. else {
  11437. newPromise._resolve([]);
  11438. }
  11439. return newPromise;
  11440. };
  11441. InternalPromise.race = function (promises) {
  11442. var newPromise = new InternalPromise();
  11443. if (promises.length) {
  11444. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11445. var promise = promises_1[_i];
  11446. promise.then(function (value) {
  11447. if (newPromise) {
  11448. newPromise._resolve(value);
  11449. newPromise = null;
  11450. }
  11451. return null;
  11452. }, function (reason) {
  11453. if (newPromise) {
  11454. newPromise._reject(reason);
  11455. newPromise = null;
  11456. }
  11457. });
  11458. }
  11459. }
  11460. return newPromise;
  11461. };
  11462. return InternalPromise;
  11463. }());
  11464. /**
  11465. * Helper class that provides a small promise polyfill
  11466. */
  11467. var PromisePolyfill = /** @class */ (function () {
  11468. function PromisePolyfill() {
  11469. }
  11470. /**
  11471. * Static function used to check if the polyfill is required
  11472. * If this is the case then the function will inject the polyfill to window.Promise
  11473. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11474. */
  11475. PromisePolyfill.Apply = function (force) {
  11476. if (force === void 0) { force = false; }
  11477. if (force || typeof Promise === 'undefined') {
  11478. var root = window;
  11479. root.Promise = InternalPromise;
  11480. }
  11481. };
  11482. return PromisePolyfill;
  11483. }());
  11484. BABYLON.PromisePolyfill = PromisePolyfill;
  11485. })(BABYLON || (BABYLON = {}));
  11486. //# sourceMappingURL=babylon.promise.js.map
  11487. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11488. var BABYLON;
  11489. (function (BABYLON) {
  11490. /**
  11491. * Helper class to push actions to a pool of workers.
  11492. */
  11493. var WorkerPool = /** @class */ (function () {
  11494. /**
  11495. * Constructor
  11496. * @param workers Array of workers to use for actions
  11497. */
  11498. function WorkerPool(workers) {
  11499. this._pendingActions = new Array();
  11500. this._workerInfos = workers.map(function (worker) { return ({
  11501. worker: worker,
  11502. active: false
  11503. }); });
  11504. }
  11505. /**
  11506. * Terminates all workers and clears any pending actions.
  11507. */
  11508. WorkerPool.prototype.dispose = function () {
  11509. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11510. var workerInfo = _a[_i];
  11511. workerInfo.worker.terminate();
  11512. }
  11513. delete this._workerInfos;
  11514. delete this._pendingActions;
  11515. };
  11516. /**
  11517. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11518. * pended until a worker has completed its action.
  11519. * @param action The action to perform. Call onComplete when the action is complete.
  11520. */
  11521. WorkerPool.prototype.push = function (action) {
  11522. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11523. var workerInfo = _a[_i];
  11524. if (!workerInfo.active) {
  11525. this._execute(workerInfo, action);
  11526. return;
  11527. }
  11528. }
  11529. this._pendingActions.push(action);
  11530. };
  11531. WorkerPool.prototype._execute = function (workerInfo, action) {
  11532. var _this = this;
  11533. workerInfo.active = true;
  11534. action(workerInfo.worker, function () {
  11535. workerInfo.active = false;
  11536. var nextAction = _this._pendingActions.shift();
  11537. if (nextAction) {
  11538. _this._execute(workerInfo, nextAction);
  11539. }
  11540. });
  11541. };
  11542. return WorkerPool;
  11543. }());
  11544. BABYLON.WorkerPool = WorkerPool;
  11545. })(BABYLON || (BABYLON = {}));
  11546. //# sourceMappingURL=babylon.workerPool.js.map
  11547. var BABYLON;
  11548. (function (BABYLON) {
  11549. /**
  11550. * @hidden
  11551. **/
  11552. var _AlphaState = /** @class */ (function () {
  11553. /**
  11554. * Initializes the state.
  11555. */
  11556. function _AlphaState() {
  11557. this._isAlphaBlendDirty = false;
  11558. this._isBlendFunctionParametersDirty = false;
  11559. this._isBlendEquationParametersDirty = false;
  11560. this._isBlendConstantsDirty = false;
  11561. this._alphaBlend = false;
  11562. this._blendFunctionParameters = new Array(4);
  11563. this._blendEquationParameters = new Array(2);
  11564. this._blendConstants = new Array(4);
  11565. this.reset();
  11566. }
  11567. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11568. get: function () {
  11569. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11570. },
  11571. enumerable: true,
  11572. configurable: true
  11573. });
  11574. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11575. get: function () {
  11576. return this._alphaBlend;
  11577. },
  11578. set: function (value) {
  11579. if (this._alphaBlend === value) {
  11580. return;
  11581. }
  11582. this._alphaBlend = value;
  11583. this._isAlphaBlendDirty = true;
  11584. },
  11585. enumerable: true,
  11586. configurable: true
  11587. });
  11588. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11589. if (this._blendConstants[0] === r &&
  11590. this._blendConstants[1] === g &&
  11591. this._blendConstants[2] === b &&
  11592. this._blendConstants[3] === a) {
  11593. return;
  11594. }
  11595. this._blendConstants[0] = r;
  11596. this._blendConstants[1] = g;
  11597. this._blendConstants[2] = b;
  11598. this._blendConstants[3] = a;
  11599. this._isBlendConstantsDirty = true;
  11600. };
  11601. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11602. if (this._blendFunctionParameters[0] === value0 &&
  11603. this._blendFunctionParameters[1] === value1 &&
  11604. this._blendFunctionParameters[2] === value2 &&
  11605. this._blendFunctionParameters[3] === value3) {
  11606. return;
  11607. }
  11608. this._blendFunctionParameters[0] = value0;
  11609. this._blendFunctionParameters[1] = value1;
  11610. this._blendFunctionParameters[2] = value2;
  11611. this._blendFunctionParameters[3] = value3;
  11612. this._isBlendFunctionParametersDirty = true;
  11613. };
  11614. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11615. if (this._blendEquationParameters[0] === rgb &&
  11616. this._blendEquationParameters[1] === alpha) {
  11617. return;
  11618. }
  11619. this._blendEquationParameters[0] = rgb;
  11620. this._blendEquationParameters[1] = alpha;
  11621. this._isBlendEquationParametersDirty = true;
  11622. };
  11623. _AlphaState.prototype.reset = function () {
  11624. this._alphaBlend = false;
  11625. this._blendFunctionParameters[0] = null;
  11626. this._blendFunctionParameters[1] = null;
  11627. this._blendFunctionParameters[2] = null;
  11628. this._blendFunctionParameters[3] = null;
  11629. this._blendEquationParameters[0] = null;
  11630. this._blendEquationParameters[1] = null;
  11631. this._blendConstants[0] = null;
  11632. this._blendConstants[1] = null;
  11633. this._blendConstants[2] = null;
  11634. this._blendConstants[3] = null;
  11635. this._isAlphaBlendDirty = true;
  11636. this._isBlendFunctionParametersDirty = false;
  11637. this._isBlendEquationParametersDirty = false;
  11638. this._isBlendConstantsDirty = false;
  11639. };
  11640. _AlphaState.prototype.apply = function (gl) {
  11641. if (!this.isDirty) {
  11642. return;
  11643. }
  11644. // Alpha blend
  11645. if (this._isAlphaBlendDirty) {
  11646. if (this._alphaBlend) {
  11647. gl.enable(gl.BLEND);
  11648. }
  11649. else {
  11650. gl.disable(gl.BLEND);
  11651. }
  11652. this._isAlphaBlendDirty = false;
  11653. }
  11654. // Alpha function
  11655. if (this._isBlendFunctionParametersDirty) {
  11656. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11657. this._isBlendFunctionParametersDirty = false;
  11658. }
  11659. // Alpha equation
  11660. if (this._isBlendEquationParametersDirty) {
  11661. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11662. this._isBlendEquationParametersDirty = false;
  11663. }
  11664. // Constants
  11665. if (this._isBlendConstantsDirty) {
  11666. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11667. this._isBlendConstantsDirty = false;
  11668. }
  11669. };
  11670. return _AlphaState;
  11671. }());
  11672. BABYLON._AlphaState = _AlphaState;
  11673. })(BABYLON || (BABYLON = {}));
  11674. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11675. var BABYLON;
  11676. (function (BABYLON) {
  11677. /**
  11678. * @hidden
  11679. **/
  11680. var _DepthCullingState = /** @class */ (function () {
  11681. /**
  11682. * Initializes the state.
  11683. */
  11684. function _DepthCullingState() {
  11685. this._isDepthTestDirty = false;
  11686. this._isDepthMaskDirty = false;
  11687. this._isDepthFuncDirty = false;
  11688. this._isCullFaceDirty = false;
  11689. this._isCullDirty = false;
  11690. this._isZOffsetDirty = false;
  11691. this._isFrontFaceDirty = false;
  11692. this.reset();
  11693. }
  11694. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11695. get: function () {
  11696. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11697. },
  11698. enumerable: true,
  11699. configurable: true
  11700. });
  11701. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11702. get: function () {
  11703. return this._zOffset;
  11704. },
  11705. set: function (value) {
  11706. if (this._zOffset === value) {
  11707. return;
  11708. }
  11709. this._zOffset = value;
  11710. this._isZOffsetDirty = true;
  11711. },
  11712. enumerable: true,
  11713. configurable: true
  11714. });
  11715. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11716. get: function () {
  11717. return this._cullFace;
  11718. },
  11719. set: function (value) {
  11720. if (this._cullFace === value) {
  11721. return;
  11722. }
  11723. this._cullFace = value;
  11724. this._isCullFaceDirty = true;
  11725. },
  11726. enumerable: true,
  11727. configurable: true
  11728. });
  11729. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11730. get: function () {
  11731. return this._cull;
  11732. },
  11733. set: function (value) {
  11734. if (this._cull === value) {
  11735. return;
  11736. }
  11737. this._cull = value;
  11738. this._isCullDirty = true;
  11739. },
  11740. enumerable: true,
  11741. configurable: true
  11742. });
  11743. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11744. get: function () {
  11745. return this._depthFunc;
  11746. },
  11747. set: function (value) {
  11748. if (this._depthFunc === value) {
  11749. return;
  11750. }
  11751. this._depthFunc = value;
  11752. this._isDepthFuncDirty = true;
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11758. get: function () {
  11759. return this._depthMask;
  11760. },
  11761. set: function (value) {
  11762. if (this._depthMask === value) {
  11763. return;
  11764. }
  11765. this._depthMask = value;
  11766. this._isDepthMaskDirty = true;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11772. get: function () {
  11773. return this._depthTest;
  11774. },
  11775. set: function (value) {
  11776. if (this._depthTest === value) {
  11777. return;
  11778. }
  11779. this._depthTest = value;
  11780. this._isDepthTestDirty = true;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11786. get: function () {
  11787. return this._frontFace;
  11788. },
  11789. set: function (value) {
  11790. if (this._frontFace === value) {
  11791. return;
  11792. }
  11793. this._frontFace = value;
  11794. this._isFrontFaceDirty = true;
  11795. },
  11796. enumerable: true,
  11797. configurable: true
  11798. });
  11799. _DepthCullingState.prototype.reset = function () {
  11800. this._depthMask = true;
  11801. this._depthTest = true;
  11802. this._depthFunc = null;
  11803. this._cullFace = null;
  11804. this._cull = null;
  11805. this._zOffset = 0;
  11806. this._frontFace = null;
  11807. this._isDepthTestDirty = true;
  11808. this._isDepthMaskDirty = true;
  11809. this._isDepthFuncDirty = false;
  11810. this._isCullFaceDirty = false;
  11811. this._isCullDirty = false;
  11812. this._isZOffsetDirty = false;
  11813. this._isFrontFaceDirty = false;
  11814. };
  11815. _DepthCullingState.prototype.apply = function (gl) {
  11816. if (!this.isDirty) {
  11817. return;
  11818. }
  11819. // Cull
  11820. if (this._isCullDirty) {
  11821. if (this.cull) {
  11822. gl.enable(gl.CULL_FACE);
  11823. }
  11824. else {
  11825. gl.disable(gl.CULL_FACE);
  11826. }
  11827. this._isCullDirty = false;
  11828. }
  11829. // Cull face
  11830. if (this._isCullFaceDirty) {
  11831. gl.cullFace(this.cullFace);
  11832. this._isCullFaceDirty = false;
  11833. }
  11834. // Depth mask
  11835. if (this._isDepthMaskDirty) {
  11836. gl.depthMask(this.depthMask);
  11837. this._isDepthMaskDirty = false;
  11838. }
  11839. // Depth test
  11840. if (this._isDepthTestDirty) {
  11841. if (this.depthTest) {
  11842. gl.enable(gl.DEPTH_TEST);
  11843. }
  11844. else {
  11845. gl.disable(gl.DEPTH_TEST);
  11846. }
  11847. this._isDepthTestDirty = false;
  11848. }
  11849. // Depth func
  11850. if (this._isDepthFuncDirty) {
  11851. gl.depthFunc(this.depthFunc);
  11852. this._isDepthFuncDirty = false;
  11853. }
  11854. // zOffset
  11855. if (this._isZOffsetDirty) {
  11856. if (this.zOffset) {
  11857. gl.enable(gl.POLYGON_OFFSET_FILL);
  11858. gl.polygonOffset(this.zOffset, 0);
  11859. }
  11860. else {
  11861. gl.disable(gl.POLYGON_OFFSET_FILL);
  11862. }
  11863. this._isZOffsetDirty = false;
  11864. }
  11865. // Front face
  11866. if (this._isFrontFaceDirty) {
  11867. gl.frontFace(this.frontFace);
  11868. this._isFrontFaceDirty = false;
  11869. }
  11870. };
  11871. return _DepthCullingState;
  11872. }());
  11873. BABYLON._DepthCullingState = _DepthCullingState;
  11874. })(BABYLON || (BABYLON = {}));
  11875. //# sourceMappingURL=babylon.depthCullingState.js.map
  11876. var BABYLON;
  11877. (function (BABYLON) {
  11878. /**
  11879. * @hidden
  11880. **/
  11881. var _StencilState = /** @class */ (function () {
  11882. function _StencilState() {
  11883. this._isStencilTestDirty = false;
  11884. this._isStencilMaskDirty = false;
  11885. this._isStencilFuncDirty = false;
  11886. this._isStencilOpDirty = false;
  11887. this.reset();
  11888. }
  11889. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11890. get: function () {
  11891. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11892. },
  11893. enumerable: true,
  11894. configurable: true
  11895. });
  11896. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11897. get: function () {
  11898. return this._stencilFunc;
  11899. },
  11900. set: function (value) {
  11901. if (this._stencilFunc === value) {
  11902. return;
  11903. }
  11904. this._stencilFunc = value;
  11905. this._isStencilFuncDirty = true;
  11906. },
  11907. enumerable: true,
  11908. configurable: true
  11909. });
  11910. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11911. get: function () {
  11912. return this._stencilFuncRef;
  11913. },
  11914. set: function (value) {
  11915. if (this._stencilFuncRef === value) {
  11916. return;
  11917. }
  11918. this._stencilFuncRef = value;
  11919. this._isStencilFuncDirty = true;
  11920. },
  11921. enumerable: true,
  11922. configurable: true
  11923. });
  11924. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11925. get: function () {
  11926. return this._stencilFuncMask;
  11927. },
  11928. set: function (value) {
  11929. if (this._stencilFuncMask === value) {
  11930. return;
  11931. }
  11932. this._stencilFuncMask = value;
  11933. this._isStencilFuncDirty = true;
  11934. },
  11935. enumerable: true,
  11936. configurable: true
  11937. });
  11938. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11939. get: function () {
  11940. return this._stencilOpStencilFail;
  11941. },
  11942. set: function (value) {
  11943. if (this._stencilOpStencilFail === value) {
  11944. return;
  11945. }
  11946. this._stencilOpStencilFail = value;
  11947. this._isStencilOpDirty = true;
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11953. get: function () {
  11954. return this._stencilOpDepthFail;
  11955. },
  11956. set: function (value) {
  11957. if (this._stencilOpDepthFail === value) {
  11958. return;
  11959. }
  11960. this._stencilOpDepthFail = value;
  11961. this._isStencilOpDirty = true;
  11962. },
  11963. enumerable: true,
  11964. configurable: true
  11965. });
  11966. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11967. get: function () {
  11968. return this._stencilOpStencilDepthPass;
  11969. },
  11970. set: function (value) {
  11971. if (this._stencilOpStencilDepthPass === value) {
  11972. return;
  11973. }
  11974. this._stencilOpStencilDepthPass = value;
  11975. this._isStencilOpDirty = true;
  11976. },
  11977. enumerable: true,
  11978. configurable: true
  11979. });
  11980. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11981. get: function () {
  11982. return this._stencilMask;
  11983. },
  11984. set: function (value) {
  11985. if (this._stencilMask === value) {
  11986. return;
  11987. }
  11988. this._stencilMask = value;
  11989. this._isStencilMaskDirty = true;
  11990. },
  11991. enumerable: true,
  11992. configurable: true
  11993. });
  11994. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11995. get: function () {
  11996. return this._stencilTest;
  11997. },
  11998. set: function (value) {
  11999. if (this._stencilTest === value) {
  12000. return;
  12001. }
  12002. this._stencilTest = value;
  12003. this._isStencilTestDirty = true;
  12004. },
  12005. enumerable: true,
  12006. configurable: true
  12007. });
  12008. _StencilState.prototype.reset = function () {
  12009. this._stencilTest = false;
  12010. this._stencilMask = 0xFF;
  12011. this._stencilFunc = BABYLON.Engine.ALWAYS;
  12012. this._stencilFuncRef = 1;
  12013. this._stencilFuncMask = 0xFF;
  12014. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  12015. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  12016. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  12017. this._isStencilTestDirty = true;
  12018. this._isStencilMaskDirty = true;
  12019. this._isStencilFuncDirty = true;
  12020. this._isStencilOpDirty = true;
  12021. };
  12022. _StencilState.prototype.apply = function (gl) {
  12023. if (!this.isDirty) {
  12024. return;
  12025. }
  12026. // Stencil test
  12027. if (this._isStencilTestDirty) {
  12028. if (this.stencilTest) {
  12029. gl.enable(gl.STENCIL_TEST);
  12030. }
  12031. else {
  12032. gl.disable(gl.STENCIL_TEST);
  12033. }
  12034. this._isStencilTestDirty = false;
  12035. }
  12036. // Stencil mask
  12037. if (this._isStencilMaskDirty) {
  12038. gl.stencilMask(this.stencilMask);
  12039. this._isStencilMaskDirty = false;
  12040. }
  12041. // Stencil func
  12042. if (this._isStencilFuncDirty) {
  12043. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  12044. this._isStencilFuncDirty = false;
  12045. }
  12046. // Stencil op
  12047. if (this._isStencilOpDirty) {
  12048. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  12049. this._isStencilOpDirty = false;
  12050. }
  12051. };
  12052. return _StencilState;
  12053. }());
  12054. BABYLON._StencilState = _StencilState;
  12055. })(BABYLON || (BABYLON = {}));
  12056. //# sourceMappingURL=babylon.stencilState.js.map
  12057. var __assign = (this && this.__assign) || function () {
  12058. __assign = Object.assign || function(t) {
  12059. for (var s, i = 1, n = arguments.length; i < n; i++) {
  12060. s = arguments[i];
  12061. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  12062. t[p] = s[p];
  12063. }
  12064. return t;
  12065. };
  12066. return __assign.apply(this, arguments);
  12067. };
  12068. var BABYLON;
  12069. (function (BABYLON) {
  12070. /**
  12071. * Keeps track of all the buffer info used in engine.
  12072. */
  12073. var BufferPointer = /** @class */ (function () {
  12074. function BufferPointer() {
  12075. }
  12076. return BufferPointer;
  12077. }());
  12078. /**
  12079. * Interface for attribute information associated with buffer instanciation
  12080. */
  12081. var InstancingAttributeInfo = /** @class */ (function () {
  12082. function InstancingAttributeInfo() {
  12083. }
  12084. return InstancingAttributeInfo;
  12085. }());
  12086. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  12087. /**
  12088. * Define options used to create a render target texture
  12089. */
  12090. var RenderTargetCreationOptions = /** @class */ (function () {
  12091. function RenderTargetCreationOptions() {
  12092. }
  12093. return RenderTargetCreationOptions;
  12094. }());
  12095. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  12096. /**
  12097. * Define options used to create a depth texture
  12098. */
  12099. var DepthTextureCreationOptions = /** @class */ (function () {
  12100. function DepthTextureCreationOptions() {
  12101. }
  12102. return DepthTextureCreationOptions;
  12103. }());
  12104. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  12105. /**
  12106. * Class used to describe the capabilities of the engine relatively to the current browser
  12107. */
  12108. var EngineCapabilities = /** @class */ (function () {
  12109. function EngineCapabilities() {
  12110. }
  12111. return EngineCapabilities;
  12112. }());
  12113. BABYLON.EngineCapabilities = EngineCapabilities;
  12114. /**
  12115. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  12116. */
  12117. var Engine = /** @class */ (function () {
  12118. /**
  12119. * Creates a new engine
  12120. * @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
  12121. * @param antialias defines enable antialiasing (default: false)
  12122. * @param options defines further options to be sent to the getContext() function
  12123. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  12124. */
  12125. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  12126. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  12127. var _this = this;
  12128. // Public members
  12129. /**
  12130. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  12131. */
  12132. this.forcePOTTextures = false;
  12133. /**
  12134. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  12135. */
  12136. this.isFullscreen = false;
  12137. /**
  12138. * Gets a boolean indicating if the pointer is currently locked
  12139. */
  12140. this.isPointerLock = false;
  12141. /**
  12142. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12143. */
  12144. this.cullBackFaces = true;
  12145. /**
  12146. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12147. */
  12148. this.renderEvenInBackground = true;
  12149. /**
  12150. * Gets or sets a boolean indicating that cache can be kept between frames
  12151. */
  12152. this.preventCacheWipeBetweenFrames = false;
  12153. /**
  12154. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12155. **/
  12156. this.enableOfflineSupport = false;
  12157. /**
  12158. * 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)
  12159. **/
  12160. this.disableManifestCheck = false;
  12161. /**
  12162. * Gets the list of created scenes
  12163. */
  12164. this.scenes = new Array();
  12165. /**
  12166. * Gets the list of created postprocesses
  12167. */
  12168. this.postProcesses = new Array();
  12169. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12170. this.validateShaderPrograms = false;
  12171. // Observables
  12172. /**
  12173. * Observable event triggered each time the rendering canvas is resized
  12174. */
  12175. this.onResizeObservable = new BABYLON.Observable();
  12176. /**
  12177. * Observable event triggered each time the canvas loses focus
  12178. */
  12179. this.onCanvasBlurObservable = new BABYLON.Observable();
  12180. /**
  12181. * Observable event triggered each time the canvas gains focus
  12182. */
  12183. this.onCanvasFocusObservable = new BABYLON.Observable();
  12184. /**
  12185. * Observable event triggered each time the canvas receives pointerout event
  12186. */
  12187. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12188. /**
  12189. * Observable event triggered before each texture is initialized
  12190. */
  12191. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12192. //WebVR
  12193. this._vrDisplay = undefined;
  12194. this._vrSupported = false;
  12195. this._vrExclusivePointerMode = false;
  12196. // Uniform buffers list
  12197. /**
  12198. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12199. */
  12200. this.disableUniformBuffers = false;
  12201. /** @hidden */
  12202. this._uniformBuffers = new Array();
  12203. // Observables
  12204. /**
  12205. * Observable raised when the engine begins a new frame
  12206. */
  12207. this.onBeginFrameObservable = new BABYLON.Observable();
  12208. /**
  12209. * If set, will be used to request the next animation frame for the render loop
  12210. */
  12211. this.customAnimationFrameRequester = null;
  12212. /**
  12213. * Observable raised when the engine ends the current frame
  12214. */
  12215. this.onEndFrameObservable = new BABYLON.Observable();
  12216. /**
  12217. * Observable raised when the engine is about to compile a shader
  12218. */
  12219. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12220. /**
  12221. * Observable raised when the engine has jsut compiled a shader
  12222. */
  12223. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12224. this._windowIsBackground = false;
  12225. this._webGLVersion = 1.0;
  12226. /** @hidden */
  12227. this._badOS = false;
  12228. /** @hidden */
  12229. this._badDesktopOS = false;
  12230. /**
  12231. * Gets or sets a value indicating if we want to disable texture binding optimization.
  12232. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12233. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12234. */
  12235. this.disableTextureBindingOptimization = false;
  12236. /**
  12237. * Observable signaled when VR display mode changes
  12238. */
  12239. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12240. /**
  12241. * Observable signaled when VR request present is complete
  12242. */
  12243. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12244. /**
  12245. * Observable signaled when VR request present starts
  12246. */
  12247. this.onVRRequestPresentStart = new BABYLON.Observable();
  12248. this._colorWrite = true;
  12249. /** @hidden */
  12250. this._drawCalls = new BABYLON.PerfCounter();
  12251. /** @hidden */
  12252. this._textureCollisions = new BABYLON.PerfCounter();
  12253. this._renderingQueueLaunched = false;
  12254. this._activeRenderLoops = new Array();
  12255. // Deterministic lockstepMaxSteps
  12256. this._deterministicLockstep = false;
  12257. this._lockstepMaxSteps = 4;
  12258. // Lost context
  12259. /**
  12260. * Observable signaled when a context lost event is raised
  12261. */
  12262. this.onContextLostObservable = new BABYLON.Observable();
  12263. /**
  12264. * Observable signaled when a context restored event is raised
  12265. */
  12266. this.onContextRestoredObservable = new BABYLON.Observable();
  12267. this._contextWasLost = false;
  12268. this._doNotHandleContextLost = false;
  12269. // FPS
  12270. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12271. this._fps = 60;
  12272. this._deltaTime = 0;
  12273. /**
  12274. * Turn this value on if you want to pause FPS computation when in background
  12275. */
  12276. this.disablePerformanceMonitorInBackground = false;
  12277. // States
  12278. /** @hidden */
  12279. this._depthCullingState = new BABYLON._DepthCullingState();
  12280. /** @hidden */
  12281. this._stencilState = new BABYLON._StencilState();
  12282. /** @hidden */
  12283. this._alphaState = new BABYLON._AlphaState();
  12284. /** @hidden */
  12285. this._alphaMode = Engine.ALPHA_DISABLE;
  12286. // Cache
  12287. this._internalTexturesCache = new Array();
  12288. /** @hidden */
  12289. this._activeChannel = 0;
  12290. this._currentTextureChannel = -1;
  12291. /** @hidden */
  12292. this._boundTexturesCache = {};
  12293. this._compiledEffects = {};
  12294. this._vertexAttribArraysEnabled = [];
  12295. this._uintIndicesCurrentlySet = false;
  12296. this._currentBoundBuffer = new Array();
  12297. /** @hidden */
  12298. this._currentFramebuffer = null;
  12299. this._currentBufferPointers = new Array();
  12300. this._currentInstanceLocations = new Array();
  12301. this._currentInstanceBuffers = new Array();
  12302. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12303. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12304. this._vaoRecordInProgress = false;
  12305. this._mustWipeVertexAttributes = false;
  12306. this._nextFreeTextureSlots = new Array();
  12307. this._maxSimultaneousTextures = 0;
  12308. this._activeRequests = new Array();
  12309. // Hardware supported Compressed Textures
  12310. this._texturesSupported = new Array();
  12311. /**
  12312. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12313. */
  12314. this.premultipliedAlpha = true;
  12315. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12316. this._onVRFullScreenTriggered = function () {
  12317. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12318. //get the old size before we change
  12319. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12320. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12321. //get the width and height, change the render size
  12322. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12323. _this.setHardwareScalingLevel(1);
  12324. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12325. }
  12326. else {
  12327. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12328. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12329. }
  12330. };
  12331. this._unpackFlipYCached = null;
  12332. /**
  12333. * In case you are sharing the context with other applications, it might
  12334. * be interested to not cache the unpack flip y state to ensure a consistent
  12335. * value would be set.
  12336. */
  12337. this.enableUnpackFlipYCached = true;
  12338. this._boundUniforms = {};
  12339. // Register promises
  12340. BABYLON.PromisePolyfill.Apply();
  12341. var canvas = null;
  12342. Engine.Instances.push(this);
  12343. if (!canvasOrContext) {
  12344. return;
  12345. }
  12346. options = options || {};
  12347. if (canvasOrContext.getContext) {
  12348. canvas = canvasOrContext;
  12349. this._renderingCanvas = canvas;
  12350. if (antialias != null) {
  12351. options.antialias = antialias;
  12352. }
  12353. if (options.deterministicLockstep === undefined) {
  12354. options.deterministicLockstep = false;
  12355. }
  12356. if (options.lockstepMaxSteps === undefined) {
  12357. options.lockstepMaxSteps = 4;
  12358. }
  12359. if (options.preserveDrawingBuffer === undefined) {
  12360. options.preserveDrawingBuffer = false;
  12361. }
  12362. if (options.audioEngine === undefined) {
  12363. options.audioEngine = true;
  12364. }
  12365. if (options.stencil === undefined) {
  12366. options.stencil = true;
  12367. }
  12368. if (options.premultipliedAlpha === false) {
  12369. this.premultipliedAlpha = false;
  12370. }
  12371. this._deterministicLockstep = options.deterministicLockstep;
  12372. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12373. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12374. // Exceptions
  12375. if (navigator && navigator.userAgent) {
  12376. var ua = navigator.userAgent;
  12377. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12378. var exception = _a[_i];
  12379. var key = exception.key;
  12380. var targets = exception.targets;
  12381. if (ua.indexOf(key) > -1) {
  12382. if (exception.capture && exception.captureConstraint) {
  12383. var capture = exception.capture;
  12384. var constraint = exception.captureConstraint;
  12385. var regex = new RegExp(capture);
  12386. var matches = regex.exec(ua);
  12387. if (matches && matches.length > 0) {
  12388. var capturedValue = parseInt(matches[matches.length - 1]);
  12389. if (capturedValue >= constraint) {
  12390. continue;
  12391. }
  12392. }
  12393. }
  12394. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12395. var target = targets_1[_b];
  12396. switch (target) {
  12397. case "uniformBuffer":
  12398. this.disableUniformBuffers = true;
  12399. break;
  12400. case "textureBindingOptimization":
  12401. this.disableTextureBindingOptimization = true;
  12402. break;
  12403. }
  12404. }
  12405. }
  12406. }
  12407. }
  12408. // GL
  12409. if (!options.disableWebGL2Support) {
  12410. try {
  12411. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12412. if (this._gl) {
  12413. this._webGLVersion = 2.0;
  12414. // Prevent weird browsers to lie :-)
  12415. if (!this._gl.deleteQuery) {
  12416. this._webGLVersion = 1.0;
  12417. }
  12418. }
  12419. }
  12420. catch (e) {
  12421. // Do nothing
  12422. }
  12423. }
  12424. if (!this._gl) {
  12425. if (!canvas) {
  12426. throw new Error("The provided canvas is null or undefined.");
  12427. }
  12428. try {
  12429. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12430. }
  12431. catch (e) {
  12432. throw new Error("WebGL not supported");
  12433. }
  12434. }
  12435. if (!this._gl) {
  12436. throw new Error("WebGL not supported");
  12437. }
  12438. this._onCanvasFocus = function () {
  12439. _this.onCanvasFocusObservable.notifyObservers(_this);
  12440. };
  12441. this._onCanvasBlur = function () {
  12442. _this.onCanvasBlurObservable.notifyObservers(_this);
  12443. };
  12444. canvas.addEventListener("focus", this._onCanvasFocus);
  12445. canvas.addEventListener("blur", this._onCanvasBlur);
  12446. this._onBlur = function () {
  12447. if (_this.disablePerformanceMonitorInBackground) {
  12448. _this._performanceMonitor.disable();
  12449. }
  12450. _this._windowIsBackground = true;
  12451. };
  12452. this._onFocus = function () {
  12453. if (_this.disablePerformanceMonitorInBackground) {
  12454. _this._performanceMonitor.enable();
  12455. }
  12456. _this._windowIsBackground = false;
  12457. };
  12458. this._onCanvasPointerOut = function (ev) {
  12459. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12460. };
  12461. window.addEventListener("blur", this._onBlur);
  12462. window.addEventListener("focus", this._onFocus);
  12463. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12464. // Context lost
  12465. if (!this._doNotHandleContextLost) {
  12466. this._onContextLost = function (evt) {
  12467. evt.preventDefault();
  12468. _this._contextWasLost = true;
  12469. BABYLON.Tools.Warn("WebGL context lost.");
  12470. _this.onContextLostObservable.notifyObservers(_this);
  12471. };
  12472. this._onContextRestored = function (evt) {
  12473. // Adding a timeout to avoid race condition at browser level
  12474. setTimeout(function () {
  12475. // Rebuild gl context
  12476. _this._initGLContext();
  12477. // Rebuild effects
  12478. _this._rebuildEffects();
  12479. // Rebuild textures
  12480. _this._rebuildInternalTextures();
  12481. // Rebuild buffers
  12482. _this._rebuildBuffers();
  12483. // Cache
  12484. _this.wipeCaches(true);
  12485. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12486. _this.onContextRestoredObservable.notifyObservers(_this);
  12487. _this._contextWasLost = false;
  12488. }, 0);
  12489. };
  12490. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12491. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12492. }
  12493. }
  12494. else {
  12495. this._gl = canvasOrContext;
  12496. this._renderingCanvas = this._gl.canvas;
  12497. if (this._gl.renderbufferStorageMultisample) {
  12498. this._webGLVersion = 2.0;
  12499. }
  12500. var attributes = this._gl.getContextAttributes();
  12501. if (attributes) {
  12502. options.stencil = attributes.stencil;
  12503. }
  12504. }
  12505. // Viewport
  12506. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12507. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12508. this.resize();
  12509. this._isStencilEnable = options.stencil ? true : false;
  12510. this._initGLContext();
  12511. if (canvas) {
  12512. // Fullscreen
  12513. this._onFullscreenChange = function () {
  12514. if (document.fullscreen !== undefined) {
  12515. _this.isFullscreen = document.fullscreen;
  12516. }
  12517. else if (document.mozFullScreen !== undefined) {
  12518. _this.isFullscreen = document.mozFullScreen;
  12519. }
  12520. else if (document.webkitIsFullScreen !== undefined) {
  12521. _this.isFullscreen = document.webkitIsFullScreen;
  12522. }
  12523. else if (document.msIsFullScreen !== undefined) {
  12524. _this.isFullscreen = document.msIsFullScreen;
  12525. }
  12526. // Pointer lock
  12527. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12528. canvas.requestPointerLock = canvas.requestPointerLock ||
  12529. canvas.msRequestPointerLock ||
  12530. canvas.mozRequestPointerLock ||
  12531. canvas.webkitRequestPointerLock;
  12532. if (canvas.requestPointerLock) {
  12533. canvas.requestPointerLock();
  12534. }
  12535. }
  12536. };
  12537. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12538. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12539. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12540. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12541. // Pointer lock
  12542. this._onPointerLockChange = function () {
  12543. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12544. document.webkitPointerLockElement === canvas ||
  12545. document.msPointerLockElement === canvas ||
  12546. document.pointerLockElement === canvas);
  12547. };
  12548. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12549. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12550. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12551. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12552. this._onVRDisplayPointerRestricted = function () {
  12553. if (canvas) {
  12554. canvas.requestPointerLock();
  12555. }
  12556. };
  12557. this._onVRDisplayPointerUnrestricted = function () {
  12558. document.exitPointerLock();
  12559. };
  12560. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12561. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12562. }
  12563. // Create Audio Engine if needed.
  12564. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12565. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  12566. }
  12567. // Prepare buffer pointers
  12568. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12569. this._currentBufferPointers[i] = new BufferPointer();
  12570. }
  12571. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12572. // Load WebVR Devices
  12573. if (options.autoEnableWebVR) {
  12574. this.initWebVR();
  12575. }
  12576. // Detect if we are running on a faulty buggy OS.
  12577. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12578. // Detect if we are running on a faulty buggy desktop OS.
  12579. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12580. console.log("Babylon.js v" + Engine.Version + " - " + this.description);
  12581. this.enableOfflineSupport = Engine.OfflineProviderFactory !== undefined;
  12582. }
  12583. Object.defineProperty(Engine, "LastCreatedEngine", {
  12584. /**
  12585. * Gets the latest created engine
  12586. */
  12587. get: function () {
  12588. if (Engine.Instances.length === 0) {
  12589. return null;
  12590. }
  12591. return Engine.Instances[Engine.Instances.length - 1];
  12592. },
  12593. enumerable: true,
  12594. configurable: true
  12595. });
  12596. Object.defineProperty(Engine, "LastCreatedScene", {
  12597. /**
  12598. * Gets the latest created scene
  12599. */
  12600. get: function () {
  12601. var lastCreatedEngine = Engine.LastCreatedEngine;
  12602. if (!lastCreatedEngine) {
  12603. return null;
  12604. }
  12605. if (lastCreatedEngine.scenes.length === 0) {
  12606. return null;
  12607. }
  12608. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12609. },
  12610. enumerable: true,
  12611. configurable: true
  12612. });
  12613. /**
  12614. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12615. * @param flag defines which part of the materials must be marked as dirty
  12616. * @param predicate defines a predicate used to filter which materials should be affected
  12617. */
  12618. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12619. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12620. var engine = Engine.Instances[engineIndex];
  12621. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12622. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12623. }
  12624. }
  12625. };
  12626. Object.defineProperty(Engine, "Version", {
  12627. /**
  12628. * Returns the current version of the framework
  12629. */
  12630. get: function () {
  12631. return "4.0.0-alpha.4";
  12632. },
  12633. enumerable: true,
  12634. configurable: true
  12635. });
  12636. Object.defineProperty(Engine.prototype, "description", {
  12637. /**
  12638. * Returns a string describing the current engine
  12639. */
  12640. get: function () {
  12641. var description = "WebGL" + this.webGLVersion;
  12642. if (this._caps.parallelShaderCompile) {
  12643. description += " - Parallel shader compilation";
  12644. }
  12645. return description;
  12646. },
  12647. enumerable: true,
  12648. configurable: true
  12649. });
  12650. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12651. /**
  12652. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12653. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12654. */
  12655. get: function () {
  12656. return this._vrExclusivePointerMode;
  12657. },
  12658. enumerable: true,
  12659. configurable: true
  12660. });
  12661. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12662. /**
  12663. * Gets a boolean indicating that the engine supports uniform buffers
  12664. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12665. */
  12666. get: function () {
  12667. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12668. },
  12669. enumerable: true,
  12670. configurable: true
  12671. });
  12672. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12673. /**
  12674. * Gets a boolean indicating that only power of 2 textures are supported
  12675. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12676. */
  12677. get: function () {
  12678. return this._webGLVersion < 2 || this.forcePOTTextures;
  12679. },
  12680. enumerable: true,
  12681. configurable: true
  12682. });
  12683. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12684. /**
  12685. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12686. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12687. */
  12688. get: function () {
  12689. return this._doNotHandleContextLost;
  12690. },
  12691. set: function (value) {
  12692. this._doNotHandleContextLost = value;
  12693. },
  12694. enumerable: true,
  12695. configurable: true
  12696. });
  12697. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12698. /**
  12699. * Gets the performance monitor attached to this engine
  12700. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12701. */
  12702. get: function () {
  12703. return this._performanceMonitor;
  12704. },
  12705. enumerable: true,
  12706. configurable: true
  12707. });
  12708. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12709. /**
  12710. * Gets the list of texture formats supported
  12711. */
  12712. get: function () {
  12713. return this._texturesSupported;
  12714. },
  12715. enumerable: true,
  12716. configurable: true
  12717. });
  12718. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12719. /**
  12720. * Gets the list of texture formats in use
  12721. */
  12722. get: function () {
  12723. return this._textureFormatInUse;
  12724. },
  12725. enumerable: true,
  12726. configurable: true
  12727. });
  12728. Object.defineProperty(Engine.prototype, "currentViewport", {
  12729. /**
  12730. * Gets the current viewport
  12731. */
  12732. get: function () {
  12733. return this._cachedViewport;
  12734. },
  12735. enumerable: true,
  12736. configurable: true
  12737. });
  12738. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12739. /**
  12740. * Gets the default empty texture
  12741. */
  12742. get: function () {
  12743. if (!this._emptyTexture) {
  12744. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12745. }
  12746. return this._emptyTexture;
  12747. },
  12748. enumerable: true,
  12749. configurable: true
  12750. });
  12751. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12752. /**
  12753. * Gets the default empty 3D texture
  12754. */
  12755. get: function () {
  12756. if (!this._emptyTexture3D) {
  12757. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12758. }
  12759. return this._emptyTexture3D;
  12760. },
  12761. enumerable: true,
  12762. configurable: true
  12763. });
  12764. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12765. /**
  12766. * Gets the default empty cube texture
  12767. */
  12768. get: function () {
  12769. if (!this._emptyCubeTexture) {
  12770. var faceData = new Uint8Array(4);
  12771. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12772. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12773. }
  12774. return this._emptyCubeTexture;
  12775. },
  12776. enumerable: true,
  12777. configurable: true
  12778. });
  12779. Engine.prototype._rebuildInternalTextures = function () {
  12780. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12781. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12782. var internalTexture = currentState_1[_i];
  12783. internalTexture._rebuild();
  12784. }
  12785. };
  12786. Engine.prototype._rebuildEffects = function () {
  12787. for (var key in this._compiledEffects) {
  12788. var effect = this._compiledEffects[key];
  12789. effect._prepareEffect();
  12790. }
  12791. BABYLON.Effect.ResetCache();
  12792. };
  12793. /**
  12794. * Gets a boolean indicating if all created effects are ready
  12795. * @returns true if all effects are ready
  12796. */
  12797. Engine.prototype.areAllEffectsReady = function () {
  12798. for (var key in this._compiledEffects) {
  12799. var effect = this._compiledEffects[key];
  12800. if (!effect.isReady()) {
  12801. return false;
  12802. }
  12803. }
  12804. return true;
  12805. };
  12806. Engine.prototype._rebuildBuffers = function () {
  12807. // Index / Vertex
  12808. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12809. var scene = _a[_i];
  12810. scene.resetCachedMaterial();
  12811. scene._rebuildGeometries();
  12812. scene._rebuildTextures();
  12813. }
  12814. // Uniforms
  12815. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12816. var uniformBuffer = _c[_b];
  12817. uniformBuffer._rebuild();
  12818. }
  12819. };
  12820. Engine.prototype._initGLContext = function () {
  12821. // Caps
  12822. this._caps = new EngineCapabilities();
  12823. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12824. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12825. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12826. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12827. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12828. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12829. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12830. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12831. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12832. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12833. // Infos
  12834. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12835. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12836. if (rendererInfo != null) {
  12837. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12838. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12839. }
  12840. if (!this._glVendor) {
  12841. this._glVendor = "Unknown vendor";
  12842. }
  12843. if (!this._glRenderer) {
  12844. this._glRenderer = "Unknown renderer";
  12845. }
  12846. // Constants
  12847. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12848. if (this._gl.RGBA16F !== 0x881A) {
  12849. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12850. }
  12851. if (this._gl.RGBA32F !== 0x8814) {
  12852. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12853. }
  12854. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12855. this._gl.DEPTH24_STENCIL8 = 35056;
  12856. }
  12857. // Extensions
  12858. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12859. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12860. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12861. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12862. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12863. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12864. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12865. 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');
  12866. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12867. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12868. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12869. this._caps.highPrecisionShaderSupported = false;
  12870. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12871. if (this._caps.timerQuery) {
  12872. if (this._webGLVersion === 1) {
  12873. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12874. }
  12875. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12876. }
  12877. // Checks if some of the format renders first to allow the use of webgl inspector.
  12878. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12879. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12880. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12881. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12882. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12883. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12884. if (this._webGLVersion > 1) {
  12885. this._gl.HALF_FLOAT_OES = 0x140B;
  12886. }
  12887. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12888. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12889. // Draw buffers
  12890. if (this._webGLVersion > 1) {
  12891. this._caps.drawBuffersExtension = true;
  12892. }
  12893. else {
  12894. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12895. if (drawBuffersExtension !== null) {
  12896. this._caps.drawBuffersExtension = true;
  12897. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12898. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12899. for (var i = 0; i < 16; i++) {
  12900. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12901. }
  12902. }
  12903. else {
  12904. this._caps.drawBuffersExtension = false;
  12905. }
  12906. }
  12907. // Shader compiler threads
  12908. this._caps.parallelShaderCompile = this._gl.getExtension('KHR_parallel_shader_compile');
  12909. if (this._caps.parallelShaderCompile) {
  12910. var threads = this._gl.getParameter(this._caps.parallelShaderCompile.MAX_SHADER_COMPILER_THREADS_KHR);
  12911. this._caps.parallelShaderCompile.maxShaderCompilerThreadsKHR(threads);
  12912. }
  12913. // Depth Texture
  12914. if (this._webGLVersion > 1) {
  12915. this._caps.depthTextureExtension = true;
  12916. }
  12917. else {
  12918. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12919. if (depthTextureExtension != null) {
  12920. this._caps.depthTextureExtension = true;
  12921. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12922. }
  12923. }
  12924. // Vertex array object
  12925. if (this._webGLVersion > 1) {
  12926. this._caps.vertexArrayObject = true;
  12927. }
  12928. else {
  12929. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12930. if (vertexArrayObjectExtension != null) {
  12931. this._caps.vertexArrayObject = true;
  12932. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12933. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12934. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12935. }
  12936. else {
  12937. this._caps.vertexArrayObject = false;
  12938. }
  12939. }
  12940. // Instances count
  12941. if (this._webGLVersion > 1) {
  12942. this._caps.instancedArrays = true;
  12943. }
  12944. else {
  12945. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12946. if (instanceExtension != null) {
  12947. this._caps.instancedArrays = true;
  12948. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12949. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12950. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12951. }
  12952. else {
  12953. this._caps.instancedArrays = false;
  12954. }
  12955. }
  12956. // Intelligently add supported compressed formats in order to check for.
  12957. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12958. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12959. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12960. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12961. if (this._caps.astc) {
  12962. this.texturesSupported.push('-astc.ktx');
  12963. }
  12964. if (this._caps.s3tc) {
  12965. this.texturesSupported.push('-dxt.ktx');
  12966. }
  12967. if (this._caps.pvrtc) {
  12968. this.texturesSupported.push('-pvrtc.ktx');
  12969. }
  12970. if (this._caps.etc2) {
  12971. this.texturesSupported.push('-etc2.ktx');
  12972. }
  12973. if (this._caps.etc1) {
  12974. this.texturesSupported.push('-etc1.ktx');
  12975. }
  12976. if (this._gl.getShaderPrecisionFormat) {
  12977. var vertex_highp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT);
  12978. var fragment_highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12979. if (vertex_highp && fragment_highp) {
  12980. this._caps.highPrecisionShaderSupported = vertex_highp.precision !== 0 && fragment_highp.precision !== 0;
  12981. }
  12982. }
  12983. // Depth buffer
  12984. this.setDepthBuffer(true);
  12985. this.setDepthFunctionToLessOrEqual();
  12986. this.setDepthWrite(true);
  12987. // Texture maps
  12988. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12989. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12990. this._nextFreeTextureSlots.push(slot);
  12991. }
  12992. };
  12993. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12994. /**
  12995. * Gets version of the current webGL context
  12996. */
  12997. get: function () {
  12998. return this._webGLVersion;
  12999. },
  13000. enumerable: true,
  13001. configurable: true
  13002. });
  13003. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  13004. /**
  13005. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  13006. */
  13007. get: function () {
  13008. return this._isStencilEnable;
  13009. },
  13010. enumerable: true,
  13011. configurable: true
  13012. });
  13013. Engine.prototype._prepareWorkingCanvas = function () {
  13014. if (this._workingCanvas) {
  13015. return;
  13016. }
  13017. this._workingCanvas = document.createElement("canvas");
  13018. var context = this._workingCanvas.getContext("2d");
  13019. if (context) {
  13020. this._workingContext = context;
  13021. }
  13022. };
  13023. /**
  13024. * Reset the texture cache to empty state
  13025. */
  13026. Engine.prototype.resetTextureCache = function () {
  13027. for (var key in this._boundTexturesCache) {
  13028. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  13029. continue;
  13030. }
  13031. var boundTexture = this._boundTexturesCache[key];
  13032. if (boundTexture) {
  13033. this._removeDesignatedSlot(boundTexture);
  13034. }
  13035. this._boundTexturesCache[key] = null;
  13036. }
  13037. if (!this.disableTextureBindingOptimization) {
  13038. this._nextFreeTextureSlots = [];
  13039. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  13040. this._nextFreeTextureSlots.push(slot);
  13041. }
  13042. }
  13043. this._currentTextureChannel = -1;
  13044. };
  13045. /**
  13046. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  13047. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13048. * @returns true if engine is in deterministic lock step mode
  13049. */
  13050. Engine.prototype.isDeterministicLockStep = function () {
  13051. return this._deterministicLockstep;
  13052. };
  13053. /**
  13054. * Gets the max steps when engine is running in deterministic lock step
  13055. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13056. * @returns the max steps
  13057. */
  13058. Engine.prototype.getLockstepMaxSteps = function () {
  13059. return this._lockstepMaxSteps;
  13060. };
  13061. /**
  13062. * Gets an object containing information about the current webGL context
  13063. * @returns an object containing the vender, the renderer and the version of the current webGL context
  13064. */
  13065. Engine.prototype.getGlInfo = function () {
  13066. return {
  13067. vendor: this._glVendor,
  13068. renderer: this._glRenderer,
  13069. version: this._glVersion
  13070. };
  13071. };
  13072. /**
  13073. * Gets current aspect ratio
  13074. * @param camera defines the camera to use to get the aspect ratio
  13075. * @param useScreen defines if screen size must be used (or the current render target if any)
  13076. * @returns a number defining the aspect ratio
  13077. */
  13078. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  13079. if (useScreen === void 0) { useScreen = false; }
  13080. var viewport = camera.viewport;
  13081. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  13082. };
  13083. /**
  13084. * Gets current screen aspect ratio
  13085. * @returns a number defining the aspect ratio
  13086. */
  13087. Engine.prototype.getScreenAspectRatio = function () {
  13088. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  13089. };
  13090. /**
  13091. * Gets the current render width
  13092. * @param useScreen defines if screen size must be used (or the current render target if any)
  13093. * @returns a number defining the current render width
  13094. */
  13095. Engine.prototype.getRenderWidth = function (useScreen) {
  13096. if (useScreen === void 0) { useScreen = false; }
  13097. if (!useScreen && this._currentRenderTarget) {
  13098. return this._currentRenderTarget.width;
  13099. }
  13100. return this._gl.drawingBufferWidth;
  13101. };
  13102. /**
  13103. * Gets the current render height
  13104. * @param useScreen defines if screen size must be used (or the current render target if any)
  13105. * @returns a number defining the current render height
  13106. */
  13107. Engine.prototype.getRenderHeight = function (useScreen) {
  13108. if (useScreen === void 0) { useScreen = false; }
  13109. if (!useScreen && this._currentRenderTarget) {
  13110. return this._currentRenderTarget.height;
  13111. }
  13112. return this._gl.drawingBufferHeight;
  13113. };
  13114. /**
  13115. * Gets the HTML canvas attached with the current webGL context
  13116. * @returns a HTML canvas
  13117. */
  13118. Engine.prototype.getRenderingCanvas = function () {
  13119. return this._renderingCanvas;
  13120. };
  13121. /**
  13122. * Gets the client rect of the HTML canvas attached with the current webGL context
  13123. * @returns a client rectanglee
  13124. */
  13125. Engine.prototype.getRenderingCanvasClientRect = function () {
  13126. if (!this._renderingCanvas) {
  13127. return null;
  13128. }
  13129. return this._renderingCanvas.getBoundingClientRect();
  13130. };
  13131. /**
  13132. * Defines the hardware scaling level.
  13133. * By default the hardware scaling level is computed from the window device ratio.
  13134. * 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.
  13135. * @param level defines the level to use
  13136. */
  13137. Engine.prototype.setHardwareScalingLevel = function (level) {
  13138. this._hardwareScalingLevel = level;
  13139. this.resize();
  13140. };
  13141. /**
  13142. * Gets the current hardware scaling level.
  13143. * By default the hardware scaling level is computed from the window device ratio.
  13144. * 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.
  13145. * @returns a number indicating the current hardware scaling level
  13146. */
  13147. Engine.prototype.getHardwareScalingLevel = function () {
  13148. return this._hardwareScalingLevel;
  13149. };
  13150. /**
  13151. * Gets the list of loaded textures
  13152. * @returns an array containing all loaded textures
  13153. */
  13154. Engine.prototype.getLoadedTexturesCache = function () {
  13155. return this._internalTexturesCache;
  13156. };
  13157. /**
  13158. * Gets the object containing all engine capabilities
  13159. * @returns the EngineCapabilities object
  13160. */
  13161. Engine.prototype.getCaps = function () {
  13162. return this._caps;
  13163. };
  13164. /**
  13165. * Gets the current depth function
  13166. * @returns a number defining the depth function
  13167. */
  13168. Engine.prototype.getDepthFunction = function () {
  13169. return this._depthCullingState.depthFunc;
  13170. };
  13171. /**
  13172. * Sets the current depth function
  13173. * @param depthFunc defines the function to use
  13174. */
  13175. Engine.prototype.setDepthFunction = function (depthFunc) {
  13176. this._depthCullingState.depthFunc = depthFunc;
  13177. };
  13178. /**
  13179. * Sets the current depth function to GREATER
  13180. */
  13181. Engine.prototype.setDepthFunctionToGreater = function () {
  13182. this._depthCullingState.depthFunc = this._gl.GREATER;
  13183. };
  13184. /**
  13185. * Sets the current depth function to GEQUAL
  13186. */
  13187. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13188. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13189. };
  13190. /**
  13191. * Sets the current depth function to LESS
  13192. */
  13193. Engine.prototype.setDepthFunctionToLess = function () {
  13194. this._depthCullingState.depthFunc = this._gl.LESS;
  13195. };
  13196. /**
  13197. * Sets the current depth function to LEQUAL
  13198. */
  13199. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13200. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13201. };
  13202. /**
  13203. * Gets a boolean indicating if stencil buffer is enabled
  13204. * @returns the current stencil buffer state
  13205. */
  13206. Engine.prototype.getStencilBuffer = function () {
  13207. return this._stencilState.stencilTest;
  13208. };
  13209. /**
  13210. * Enable or disable the stencil buffer
  13211. * @param enable defines if the stencil buffer must be enabled or disabled
  13212. */
  13213. Engine.prototype.setStencilBuffer = function (enable) {
  13214. this._stencilState.stencilTest = enable;
  13215. };
  13216. /**
  13217. * Gets the current stencil mask
  13218. * @returns a number defining the new stencil mask to use
  13219. */
  13220. Engine.prototype.getStencilMask = function () {
  13221. return this._stencilState.stencilMask;
  13222. };
  13223. /**
  13224. * Sets the current stencil mask
  13225. * @param mask defines the new stencil mask to use
  13226. */
  13227. Engine.prototype.setStencilMask = function (mask) {
  13228. this._stencilState.stencilMask = mask;
  13229. };
  13230. /**
  13231. * Gets the current stencil function
  13232. * @returns a number defining the stencil function to use
  13233. */
  13234. Engine.prototype.getStencilFunction = function () {
  13235. return this._stencilState.stencilFunc;
  13236. };
  13237. /**
  13238. * Gets the current stencil reference value
  13239. * @returns a number defining the stencil reference value to use
  13240. */
  13241. Engine.prototype.getStencilFunctionReference = function () {
  13242. return this._stencilState.stencilFuncRef;
  13243. };
  13244. /**
  13245. * Gets the current stencil mask
  13246. * @returns a number defining the stencil mask to use
  13247. */
  13248. Engine.prototype.getStencilFunctionMask = function () {
  13249. return this._stencilState.stencilFuncMask;
  13250. };
  13251. /**
  13252. * Sets the current stencil function
  13253. * @param stencilFunc defines the new stencil function to use
  13254. */
  13255. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13256. this._stencilState.stencilFunc = stencilFunc;
  13257. };
  13258. /**
  13259. * Sets the current stencil reference
  13260. * @param reference defines the new stencil reference to use
  13261. */
  13262. Engine.prototype.setStencilFunctionReference = function (reference) {
  13263. this._stencilState.stencilFuncRef = reference;
  13264. };
  13265. /**
  13266. * Sets the current stencil mask
  13267. * @param mask defines the new stencil mask to use
  13268. */
  13269. Engine.prototype.setStencilFunctionMask = function (mask) {
  13270. this._stencilState.stencilFuncMask = mask;
  13271. };
  13272. /**
  13273. * Gets the current stencil operation when stencil fails
  13274. * @returns a number defining stencil operation to use when stencil fails
  13275. */
  13276. Engine.prototype.getStencilOperationFail = function () {
  13277. return this._stencilState.stencilOpStencilFail;
  13278. };
  13279. /**
  13280. * Gets the current stencil operation when depth fails
  13281. * @returns a number defining stencil operation to use when depth fails
  13282. */
  13283. Engine.prototype.getStencilOperationDepthFail = function () {
  13284. return this._stencilState.stencilOpDepthFail;
  13285. };
  13286. /**
  13287. * Gets the current stencil operation when stencil passes
  13288. * @returns a number defining stencil operation to use when stencil passes
  13289. */
  13290. Engine.prototype.getStencilOperationPass = function () {
  13291. return this._stencilState.stencilOpStencilDepthPass;
  13292. };
  13293. /**
  13294. * Sets the stencil operation to use when stencil fails
  13295. * @param operation defines the stencil operation to use when stencil fails
  13296. */
  13297. Engine.prototype.setStencilOperationFail = function (operation) {
  13298. this._stencilState.stencilOpStencilFail = operation;
  13299. };
  13300. /**
  13301. * Sets the stencil operation to use when depth fails
  13302. * @param operation defines the stencil operation to use when depth fails
  13303. */
  13304. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13305. this._stencilState.stencilOpDepthFail = operation;
  13306. };
  13307. /**
  13308. * Sets the stencil operation to use when stencil passes
  13309. * @param operation defines the stencil operation to use when stencil passes
  13310. */
  13311. Engine.prototype.setStencilOperationPass = function (operation) {
  13312. this._stencilState.stencilOpStencilDepthPass = operation;
  13313. };
  13314. /**
  13315. * Sets a boolean indicating if the dithering state is enabled or disabled
  13316. * @param value defines the dithering state
  13317. */
  13318. Engine.prototype.setDitheringState = function (value) {
  13319. if (value) {
  13320. this._gl.enable(this._gl.DITHER);
  13321. }
  13322. else {
  13323. this._gl.disable(this._gl.DITHER);
  13324. }
  13325. };
  13326. /**
  13327. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13328. * @param value defines the rasterizer state
  13329. */
  13330. Engine.prototype.setRasterizerState = function (value) {
  13331. if (value) {
  13332. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13333. }
  13334. else {
  13335. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13336. }
  13337. };
  13338. /**
  13339. * stop executing a render loop function and remove it from the execution array
  13340. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13341. */
  13342. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13343. if (!renderFunction) {
  13344. this._activeRenderLoops = [];
  13345. return;
  13346. }
  13347. var index = this._activeRenderLoops.indexOf(renderFunction);
  13348. if (index >= 0) {
  13349. this._activeRenderLoops.splice(index, 1);
  13350. }
  13351. };
  13352. /** @hidden */
  13353. Engine.prototype._renderLoop = function () {
  13354. if (!this._contextWasLost) {
  13355. var shouldRender = true;
  13356. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13357. shouldRender = false;
  13358. }
  13359. if (shouldRender) {
  13360. // Start new frame
  13361. this.beginFrame();
  13362. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13363. var renderFunction = this._activeRenderLoops[index];
  13364. renderFunction();
  13365. }
  13366. // Present
  13367. this.endFrame();
  13368. }
  13369. }
  13370. if (this._activeRenderLoops.length > 0) {
  13371. // Register new frame
  13372. if (this.customAnimationFrameRequester) {
  13373. this.customAnimationFrameRequester.requestID = BABYLON.Tools.QueueNewFrame(this.customAnimationFrameRequester.renderFunction || this._bindedRenderFunction, this.customAnimationFrameRequester);
  13374. this._frameHandler = this.customAnimationFrameRequester.requestID;
  13375. }
  13376. else if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13377. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplay);
  13378. }
  13379. else {
  13380. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13381. }
  13382. }
  13383. else {
  13384. this._renderingQueueLaunched = false;
  13385. }
  13386. };
  13387. /**
  13388. * Register and execute a render loop. The engine can have more than one render function
  13389. * @param renderFunction defines the function to continuously execute
  13390. */
  13391. Engine.prototype.runRenderLoop = function (renderFunction) {
  13392. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13393. return;
  13394. }
  13395. this._activeRenderLoops.push(renderFunction);
  13396. if (!this._renderingQueueLaunched) {
  13397. this._renderingQueueLaunched = true;
  13398. this._bindedRenderFunction = this._renderLoop.bind(this);
  13399. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13400. }
  13401. };
  13402. /**
  13403. * Toggle full screen mode
  13404. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13405. */
  13406. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13407. if (this.isFullscreen) {
  13408. BABYLON.Tools.ExitFullscreen();
  13409. }
  13410. else {
  13411. this._pointerLockRequested = requestPointerLock;
  13412. if (this._renderingCanvas) {
  13413. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13414. }
  13415. }
  13416. };
  13417. /**
  13418. * Clear the current render buffer or the current render target (if any is set up)
  13419. * @param color defines the color to use
  13420. * @param backBuffer defines if the back buffer must be cleared
  13421. * @param depth defines if the depth buffer must be cleared
  13422. * @param stencil defines if the stencil buffer must be cleared
  13423. */
  13424. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13425. if (stencil === void 0) { stencil = false; }
  13426. this.applyStates();
  13427. var mode = 0;
  13428. if (backBuffer && color) {
  13429. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13430. mode |= this._gl.COLOR_BUFFER_BIT;
  13431. }
  13432. if (depth) {
  13433. this._gl.clearDepth(1.0);
  13434. mode |= this._gl.DEPTH_BUFFER_BIT;
  13435. }
  13436. if (stencil) {
  13437. this._gl.clearStencil(0);
  13438. mode |= this._gl.STENCIL_BUFFER_BIT;
  13439. }
  13440. this._gl.clear(mode);
  13441. };
  13442. /**
  13443. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13444. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13445. * @param y defines the y-coordinate of the corner of the clear rectangle
  13446. * @param width defines the width of the clear rectangle
  13447. * @param height defines the height of the clear rectangle
  13448. * @param clearColor defines the clear color
  13449. */
  13450. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13451. var gl = this._gl;
  13452. // Save state
  13453. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13454. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13455. // Change state
  13456. gl.enable(gl.SCISSOR_TEST);
  13457. gl.scissor(x, y, width, height);
  13458. // Clear
  13459. this.clear(clearColor, true, true, true);
  13460. // Restore state
  13461. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13462. if (curScissor === true) {
  13463. gl.enable(gl.SCISSOR_TEST);
  13464. }
  13465. else {
  13466. gl.disable(gl.SCISSOR_TEST);
  13467. }
  13468. };
  13469. /** @hidden */
  13470. Engine.prototype._viewport = function (x, y, width, height) {
  13471. if (x !== this._viewportCached.x ||
  13472. y !== this._viewportCached.y ||
  13473. width !== this._viewportCached.z ||
  13474. height !== this._viewportCached.w) {
  13475. this._viewportCached.x = x;
  13476. this._viewportCached.y = y;
  13477. this._viewportCached.z = width;
  13478. this._viewportCached.w = height;
  13479. this._gl.viewport(x, y, width, height);
  13480. }
  13481. };
  13482. /**
  13483. * Set the WebGL's viewport
  13484. * @param viewport defines the viewport element to be used
  13485. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13486. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13487. */
  13488. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13489. var width = requiredWidth || this.getRenderWidth();
  13490. var height = requiredHeight || this.getRenderHeight();
  13491. var x = viewport.x || 0;
  13492. var y = viewport.y || 0;
  13493. this._cachedViewport = viewport;
  13494. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13495. };
  13496. /**
  13497. * Directly set the WebGL Viewport
  13498. * @param x defines the x coordinate of the viewport (in screen space)
  13499. * @param y defines the y coordinate of the viewport (in screen space)
  13500. * @param width defines the width of the viewport (in screen space)
  13501. * @param height defines the height of the viewport (in screen space)
  13502. * @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
  13503. */
  13504. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13505. var currentViewport = this._cachedViewport;
  13506. this._cachedViewport = null;
  13507. this._viewport(x, y, width, height);
  13508. return currentViewport;
  13509. };
  13510. /**
  13511. * Begin a new frame
  13512. */
  13513. Engine.prototype.beginFrame = function () {
  13514. this.onBeginFrameObservable.notifyObservers(this);
  13515. this._measureFps();
  13516. };
  13517. /**
  13518. * Enf the current frame
  13519. */
  13520. Engine.prototype.endFrame = function () {
  13521. // Force a flush in case we are using a bad OS.
  13522. if (this._badOS) {
  13523. this.flushFramebuffer();
  13524. }
  13525. // Submit frame to the vr device, if enabled
  13526. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13527. // TODO: We should only submit the frame if we read frameData successfully.
  13528. this._vrDisplay.submitFrame();
  13529. }
  13530. this.onEndFrameObservable.notifyObservers(this);
  13531. };
  13532. /**
  13533. * Resize the view according to the canvas' size
  13534. */
  13535. Engine.prototype.resize = function () {
  13536. // We're not resizing the size of the canvas while in VR mode & presenting
  13537. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13538. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13539. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13540. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13541. }
  13542. };
  13543. /**
  13544. * Force a specific size of the canvas
  13545. * @param width defines the new canvas' width
  13546. * @param height defines the new canvas' height
  13547. */
  13548. Engine.prototype.setSize = function (width, height) {
  13549. if (!this._renderingCanvas) {
  13550. return;
  13551. }
  13552. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13553. return;
  13554. }
  13555. this._renderingCanvas.width = width;
  13556. this._renderingCanvas.height = height;
  13557. for (var index = 0; index < this.scenes.length; index++) {
  13558. var scene = this.scenes[index];
  13559. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13560. var cam = scene.cameras[camIndex];
  13561. cam._currentRenderId = 0;
  13562. }
  13563. }
  13564. if (this.onResizeObservable.hasObservers) {
  13565. this.onResizeObservable.notifyObservers(this);
  13566. }
  13567. };
  13568. // WebVR functions
  13569. /**
  13570. * Gets a boolean indicating if a webVR device was detected
  13571. * @returns true if a webVR device was detected
  13572. */
  13573. Engine.prototype.isVRDevicePresent = function () {
  13574. return !!this._vrDisplay;
  13575. };
  13576. /**
  13577. * Gets the current webVR device
  13578. * @returns the current webVR device (or null)
  13579. */
  13580. Engine.prototype.getVRDevice = function () {
  13581. return this._vrDisplay;
  13582. };
  13583. /**
  13584. * Initializes a webVR display and starts listening to display change events
  13585. * The onVRDisplayChangedObservable will be notified upon these changes
  13586. * @returns The onVRDisplayChangedObservable
  13587. */
  13588. Engine.prototype.initWebVR = function () {
  13589. this.initWebVRAsync();
  13590. return this.onVRDisplayChangedObservable;
  13591. };
  13592. /**
  13593. * Initializes a webVR display and starts listening to display change events
  13594. * The onVRDisplayChangedObservable will be notified upon these changes
  13595. * @returns A promise containing a VRDisplay and if vr is supported
  13596. */
  13597. Engine.prototype.initWebVRAsync = function () {
  13598. var _this = this;
  13599. var notifyObservers = function () {
  13600. var eventArgs = {
  13601. vrDisplay: _this._vrDisplay,
  13602. vrSupported: _this._vrSupported
  13603. };
  13604. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13605. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13606. };
  13607. if (!this._onVrDisplayConnect) {
  13608. this._onVrDisplayConnect = function (event) {
  13609. _this._vrDisplay = event.display;
  13610. notifyObservers();
  13611. };
  13612. this._onVrDisplayDisconnect = function () {
  13613. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13614. _this._vrDisplay = undefined;
  13615. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13616. notifyObservers();
  13617. };
  13618. this._onVrDisplayPresentChange = function () {
  13619. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13620. };
  13621. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13622. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13623. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13624. }
  13625. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13626. this._webVRInitPromise.then(notifyObservers);
  13627. return this._webVRInitPromise;
  13628. };
  13629. /**
  13630. * Call this function to switch to webVR mode
  13631. * Will do nothing if webVR is not supported or if there is no webVR device
  13632. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13633. */
  13634. Engine.prototype.enableVR = function () {
  13635. var _this = this;
  13636. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13637. var onResolved = function () {
  13638. _this.onVRRequestPresentComplete.notifyObservers(true);
  13639. _this._onVRFullScreenTriggered();
  13640. };
  13641. var onRejected = function () {
  13642. _this.onVRRequestPresentComplete.notifyObservers(false);
  13643. };
  13644. this.onVRRequestPresentStart.notifyObservers(this);
  13645. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13646. }
  13647. };
  13648. /**
  13649. * Call this function to leave webVR mode
  13650. * Will do nothing if webVR is not supported or if there is no webVR device
  13651. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13652. */
  13653. Engine.prototype.disableVR = function () {
  13654. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13655. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13656. }
  13657. };
  13658. Engine.prototype._getVRDisplaysAsync = function () {
  13659. var _this = this;
  13660. return new Promise(function (res, rej) {
  13661. if (navigator.getVRDisplays) {
  13662. navigator.getVRDisplays().then(function (devices) {
  13663. _this._vrSupported = true;
  13664. // note that devices may actually be an empty array. This is fine;
  13665. // we expect this._vrDisplay to be undefined in this case.
  13666. _this._vrDisplay = devices[0];
  13667. res({
  13668. vrDisplay: _this._vrDisplay,
  13669. vrSupported: _this._vrSupported
  13670. });
  13671. });
  13672. }
  13673. else {
  13674. _this._vrDisplay = undefined;
  13675. _this._vrSupported = false;
  13676. res({
  13677. vrDisplay: _this._vrDisplay,
  13678. vrSupported: _this._vrSupported
  13679. });
  13680. }
  13681. });
  13682. };
  13683. /**
  13684. * Binds the frame buffer to the specified texture.
  13685. * @param texture The texture to render to or null for the default canvas
  13686. * @param faceIndex The face of the texture to render to in case of cube texture
  13687. * @param requiredWidth The width of the target to render to
  13688. * @param requiredHeight The height of the target to render to
  13689. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13690. * @param depthStencilTexture The depth stencil texture to use to render
  13691. * @param lodLevel defines le lod level to bind to the frame buffer
  13692. */
  13693. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13694. if (lodLevel === void 0) { lodLevel = 0; }
  13695. if (this._currentRenderTarget) {
  13696. this.unBindFramebuffer(this._currentRenderTarget);
  13697. }
  13698. this._currentRenderTarget = texture;
  13699. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13700. var gl = this._gl;
  13701. if (texture.isCube) {
  13702. if (faceIndex === undefined) {
  13703. faceIndex = 0;
  13704. }
  13705. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13706. if (depthStencilTexture) {
  13707. if (depthStencilTexture._generateStencilBuffer) {
  13708. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13709. }
  13710. else {
  13711. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13712. }
  13713. }
  13714. }
  13715. if (this._cachedViewport && !forceFullscreenViewport) {
  13716. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13717. }
  13718. else {
  13719. if (!requiredWidth) {
  13720. requiredWidth = texture.width;
  13721. if (lodLevel) {
  13722. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13723. }
  13724. }
  13725. if (!requiredHeight) {
  13726. requiredHeight = texture.height;
  13727. if (lodLevel) {
  13728. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13729. }
  13730. }
  13731. this._viewport(0, 0, requiredWidth, requiredHeight);
  13732. }
  13733. this.wipeCaches();
  13734. };
  13735. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13736. if (this._currentFramebuffer !== framebuffer) {
  13737. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13738. this._currentFramebuffer = framebuffer;
  13739. }
  13740. };
  13741. /**
  13742. * Unbind the current render target texture from the webGL context
  13743. * @param texture defines the render target texture to unbind
  13744. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13745. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13746. */
  13747. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13748. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13749. this._currentRenderTarget = null;
  13750. // If MSAA, we need to bitblt back to main texture
  13751. var gl = this._gl;
  13752. if (texture._MSAAFramebuffer) {
  13753. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13754. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13755. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13756. }
  13757. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13758. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13759. gl.generateMipmap(gl.TEXTURE_2D);
  13760. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13761. }
  13762. if (onBeforeUnbind) {
  13763. if (texture._MSAAFramebuffer) {
  13764. // Bind the correct framebuffer
  13765. this.bindUnboundFramebuffer(texture._framebuffer);
  13766. }
  13767. onBeforeUnbind();
  13768. }
  13769. this.bindUnboundFramebuffer(null);
  13770. };
  13771. /**
  13772. * Unbind a list of render target textures from the webGL context
  13773. * This is used only when drawBuffer extension or webGL2 are active
  13774. * @param textures defines the render target textures to unbind
  13775. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13776. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13777. */
  13778. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13779. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13780. this._currentRenderTarget = null;
  13781. // If MSAA, we need to bitblt back to main texture
  13782. var gl = this._gl;
  13783. if (textures[0]._MSAAFramebuffer) {
  13784. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13785. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13786. var attachments = textures[0]._attachments;
  13787. if (!attachments) {
  13788. attachments = new Array(textures.length);
  13789. textures[0]._attachments = attachments;
  13790. }
  13791. for (var i = 0; i < textures.length; i++) {
  13792. var texture = textures[i];
  13793. for (var j = 0; j < attachments.length; j++) {
  13794. attachments[j] = gl.NONE;
  13795. }
  13796. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13797. gl.readBuffer(attachments[i]);
  13798. gl.drawBuffers(attachments);
  13799. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13800. }
  13801. for (var i = 0; i < attachments.length; i++) {
  13802. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13803. }
  13804. gl.drawBuffers(attachments);
  13805. }
  13806. for (var i = 0; i < textures.length; i++) {
  13807. var texture = textures[i];
  13808. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13809. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13810. gl.generateMipmap(gl.TEXTURE_2D);
  13811. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13812. }
  13813. }
  13814. if (onBeforeUnbind) {
  13815. if (textures[0]._MSAAFramebuffer) {
  13816. // Bind the correct framebuffer
  13817. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13818. }
  13819. onBeforeUnbind();
  13820. }
  13821. this.bindUnboundFramebuffer(null);
  13822. };
  13823. /**
  13824. * Force the mipmap generation for the given render target texture
  13825. * @param texture defines the render target texture to use
  13826. */
  13827. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13828. if (texture.generateMipMaps) {
  13829. var gl = this._gl;
  13830. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13831. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13832. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13833. }
  13834. };
  13835. /**
  13836. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13837. */
  13838. Engine.prototype.flushFramebuffer = function () {
  13839. this._gl.flush();
  13840. };
  13841. /**
  13842. * Unbind the current render target and bind the default framebuffer
  13843. */
  13844. Engine.prototype.restoreDefaultFramebuffer = function () {
  13845. if (this._currentRenderTarget) {
  13846. this.unBindFramebuffer(this._currentRenderTarget);
  13847. }
  13848. else {
  13849. this.bindUnboundFramebuffer(null);
  13850. }
  13851. if (this._cachedViewport) {
  13852. this.setViewport(this._cachedViewport);
  13853. }
  13854. this.wipeCaches();
  13855. };
  13856. // UBOs
  13857. /**
  13858. * Create an uniform buffer
  13859. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13860. * @param elements defines the content of the uniform buffer
  13861. * @returns the webGL uniform buffer
  13862. */
  13863. Engine.prototype.createUniformBuffer = function (elements) {
  13864. var ubo = this._gl.createBuffer();
  13865. if (!ubo) {
  13866. throw new Error("Unable to create uniform buffer");
  13867. }
  13868. this.bindUniformBuffer(ubo);
  13869. if (elements instanceof Float32Array) {
  13870. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13871. }
  13872. else {
  13873. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13874. }
  13875. this.bindUniformBuffer(null);
  13876. ubo.references = 1;
  13877. return ubo;
  13878. };
  13879. /**
  13880. * Create a dynamic uniform buffer
  13881. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13882. * @param elements defines the content of the uniform buffer
  13883. * @returns the webGL uniform buffer
  13884. */
  13885. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13886. var ubo = this._gl.createBuffer();
  13887. if (!ubo) {
  13888. throw new Error("Unable to create dynamic uniform buffer");
  13889. }
  13890. this.bindUniformBuffer(ubo);
  13891. if (elements instanceof Float32Array) {
  13892. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13893. }
  13894. else {
  13895. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13896. }
  13897. this.bindUniformBuffer(null);
  13898. ubo.references = 1;
  13899. return ubo;
  13900. };
  13901. /**
  13902. * Update an existing uniform buffer
  13903. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13904. * @param uniformBuffer defines the target uniform buffer
  13905. * @param elements defines the content to update
  13906. * @param offset defines the offset in the uniform buffer where update should start
  13907. * @param count defines the size of the data to update
  13908. */
  13909. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13910. this.bindUniformBuffer(uniformBuffer);
  13911. if (offset === undefined) {
  13912. offset = 0;
  13913. }
  13914. if (count === undefined) {
  13915. if (elements instanceof Float32Array) {
  13916. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13917. }
  13918. else {
  13919. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13920. }
  13921. }
  13922. else {
  13923. if (elements instanceof Float32Array) {
  13924. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13925. }
  13926. else {
  13927. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13928. }
  13929. }
  13930. this.bindUniformBuffer(null);
  13931. };
  13932. // VBOs
  13933. Engine.prototype._resetVertexBufferBinding = function () {
  13934. this.bindArrayBuffer(null);
  13935. this._cachedVertexBuffers = null;
  13936. };
  13937. /**
  13938. * Creates a vertex buffer
  13939. * @param data the data for the vertex buffer
  13940. * @returns the new WebGL static buffer
  13941. */
  13942. Engine.prototype.createVertexBuffer = function (data) {
  13943. var vbo = this._gl.createBuffer();
  13944. if (!vbo) {
  13945. throw new Error("Unable to create vertex buffer");
  13946. }
  13947. this.bindArrayBuffer(vbo);
  13948. if (data instanceof Array) {
  13949. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13950. }
  13951. else {
  13952. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13953. }
  13954. this._resetVertexBufferBinding();
  13955. vbo.references = 1;
  13956. return vbo;
  13957. };
  13958. /**
  13959. * Creates a dynamic vertex buffer
  13960. * @param data the data for the dynamic vertex buffer
  13961. * @returns the new WebGL dynamic buffer
  13962. */
  13963. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13964. var vbo = this._gl.createBuffer();
  13965. if (!vbo) {
  13966. throw new Error("Unable to create dynamic vertex buffer");
  13967. }
  13968. this.bindArrayBuffer(vbo);
  13969. if (data instanceof Array) {
  13970. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13971. }
  13972. else {
  13973. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13974. }
  13975. this._resetVertexBufferBinding();
  13976. vbo.references = 1;
  13977. return vbo;
  13978. };
  13979. /**
  13980. * Update a dynamic index buffer
  13981. * @param indexBuffer defines the target index buffer
  13982. * @param indices defines the data to update
  13983. * @param offset defines the offset in the target index buffer where update should start
  13984. */
  13985. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13986. if (offset === void 0) { offset = 0; }
  13987. // Force cache update
  13988. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13989. this.bindIndexBuffer(indexBuffer);
  13990. var arrayBuffer;
  13991. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13992. arrayBuffer = indices;
  13993. }
  13994. else {
  13995. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13996. }
  13997. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13998. this._resetIndexBufferBinding();
  13999. };
  14000. /**
  14001. * Updates a dynamic vertex buffer.
  14002. * @param vertexBuffer the vertex buffer to update
  14003. * @param data the data used to update the vertex buffer
  14004. * @param byteOffset the byte offset of the data
  14005. * @param byteLength the byte length of the data
  14006. */
  14007. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  14008. this.bindArrayBuffer(vertexBuffer);
  14009. if (byteOffset === undefined) {
  14010. byteOffset = 0;
  14011. }
  14012. if (byteLength === undefined) {
  14013. if (data instanceof Array) {
  14014. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  14015. }
  14016. else {
  14017. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  14018. }
  14019. }
  14020. else {
  14021. if (data instanceof Array) {
  14022. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  14023. }
  14024. else {
  14025. if (data instanceof ArrayBuffer) {
  14026. data = new Uint8Array(data, byteOffset, byteLength);
  14027. }
  14028. else {
  14029. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  14030. }
  14031. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14032. }
  14033. }
  14034. this._resetVertexBufferBinding();
  14035. };
  14036. Engine.prototype._resetIndexBufferBinding = function () {
  14037. this.bindIndexBuffer(null);
  14038. this._cachedIndexBuffer = null;
  14039. };
  14040. /**
  14041. * Creates a new index buffer
  14042. * @param indices defines the content of the index buffer
  14043. * @param updatable defines if the index buffer must be updatable
  14044. * @returns a new webGL buffer
  14045. */
  14046. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  14047. var vbo = this._gl.createBuffer();
  14048. if (!vbo) {
  14049. throw new Error("Unable to create index buffer");
  14050. }
  14051. this.bindIndexBuffer(vbo);
  14052. // Check for 32 bits indices
  14053. var arrayBuffer;
  14054. var need32Bits = false;
  14055. if (indices instanceof Uint16Array) {
  14056. arrayBuffer = indices;
  14057. }
  14058. else {
  14059. //check 32 bit support
  14060. if (this._caps.uintIndices) {
  14061. if (indices instanceof Uint32Array) {
  14062. arrayBuffer = indices;
  14063. need32Bits = true;
  14064. }
  14065. else {
  14066. //number[] or Int32Array, check if 32 bit is necessary
  14067. for (var index = 0; index < indices.length; index++) {
  14068. if (indices[index] > 65535) {
  14069. need32Bits = true;
  14070. break;
  14071. }
  14072. }
  14073. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14074. }
  14075. }
  14076. else {
  14077. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  14078. arrayBuffer = new Uint16Array(indices);
  14079. }
  14080. }
  14081. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  14082. this._resetIndexBufferBinding();
  14083. vbo.references = 1;
  14084. vbo.is32Bits = need32Bits;
  14085. return vbo;
  14086. };
  14087. /**
  14088. * Bind a webGL buffer to the webGL context
  14089. * @param buffer defines the buffer to bind
  14090. */
  14091. Engine.prototype.bindArrayBuffer = function (buffer) {
  14092. if (!this._vaoRecordInProgress) {
  14093. this._unbindVertexArrayObject();
  14094. }
  14095. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  14096. };
  14097. /**
  14098. * Bind an uniform buffer to the current webGL context
  14099. * @param buffer defines the buffer to bind
  14100. */
  14101. Engine.prototype.bindUniformBuffer = function (buffer) {
  14102. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  14103. };
  14104. /**
  14105. * Bind a buffer to the current webGL context at a given location
  14106. * @param buffer defines the buffer to bind
  14107. * @param location defines the index where to bind the buffer
  14108. */
  14109. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  14110. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  14111. };
  14112. /**
  14113. * Bind a specific block at a given index in a specific shader program
  14114. * @param shaderProgram defines the shader program
  14115. * @param blockName defines the block name
  14116. * @param index defines the index where to bind the block
  14117. */
  14118. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  14119. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  14120. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  14121. };
  14122. Engine.prototype.bindIndexBuffer = function (buffer) {
  14123. if (!this._vaoRecordInProgress) {
  14124. this._unbindVertexArrayObject();
  14125. }
  14126. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  14127. };
  14128. Engine.prototype.bindBuffer = function (buffer, target) {
  14129. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  14130. this._gl.bindBuffer(target, buffer);
  14131. this._currentBoundBuffer[target] = buffer;
  14132. }
  14133. };
  14134. /**
  14135. * update the bound buffer with the given data
  14136. * @param data defines the data to update
  14137. */
  14138. Engine.prototype.updateArrayBuffer = function (data) {
  14139. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14140. };
  14141. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  14142. var pointer = this._currentBufferPointers[indx];
  14143. var changed = false;
  14144. if (!pointer.active) {
  14145. changed = true;
  14146. pointer.active = true;
  14147. pointer.index = indx;
  14148. pointer.size = size;
  14149. pointer.type = type;
  14150. pointer.normalized = normalized;
  14151. pointer.stride = stride;
  14152. pointer.offset = offset;
  14153. pointer.buffer = buffer;
  14154. }
  14155. else {
  14156. if (pointer.buffer !== buffer) {
  14157. pointer.buffer = buffer;
  14158. changed = true;
  14159. }
  14160. if (pointer.size !== size) {
  14161. pointer.size = size;
  14162. changed = true;
  14163. }
  14164. if (pointer.type !== type) {
  14165. pointer.type = type;
  14166. changed = true;
  14167. }
  14168. if (pointer.normalized !== normalized) {
  14169. pointer.normalized = normalized;
  14170. changed = true;
  14171. }
  14172. if (pointer.stride !== stride) {
  14173. pointer.stride = stride;
  14174. changed = true;
  14175. }
  14176. if (pointer.offset !== offset) {
  14177. pointer.offset = offset;
  14178. changed = true;
  14179. }
  14180. }
  14181. if (changed || this._vaoRecordInProgress) {
  14182. this.bindArrayBuffer(buffer);
  14183. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14184. }
  14185. };
  14186. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14187. if (indexBuffer == null) {
  14188. return;
  14189. }
  14190. if (this._cachedIndexBuffer !== indexBuffer) {
  14191. this._cachedIndexBuffer = indexBuffer;
  14192. this.bindIndexBuffer(indexBuffer);
  14193. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14194. }
  14195. };
  14196. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14197. var attributes = effect.getAttributesNames();
  14198. if (!this._vaoRecordInProgress) {
  14199. this._unbindVertexArrayObject();
  14200. }
  14201. this.unbindAllAttributes();
  14202. for (var index = 0; index < attributes.length; index++) {
  14203. var order = effect.getAttributeLocation(index);
  14204. if (order >= 0) {
  14205. var vertexBuffer = vertexBuffers[attributes[index]];
  14206. if (!vertexBuffer) {
  14207. continue;
  14208. }
  14209. this._gl.enableVertexAttribArray(order);
  14210. if (!this._vaoRecordInProgress) {
  14211. this._vertexAttribArraysEnabled[order] = true;
  14212. }
  14213. var buffer = vertexBuffer.getBuffer();
  14214. if (buffer) {
  14215. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14216. if (vertexBuffer.getIsInstanced()) {
  14217. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14218. if (!this._vaoRecordInProgress) {
  14219. this._currentInstanceLocations.push(order);
  14220. this._currentInstanceBuffers.push(buffer);
  14221. }
  14222. }
  14223. }
  14224. }
  14225. }
  14226. };
  14227. /**
  14228. * Records a vertex array object
  14229. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14230. * @param vertexBuffers defines the list of vertex buffers to store
  14231. * @param indexBuffer defines the index buffer to store
  14232. * @param effect defines the effect to store
  14233. * @returns the new vertex array object
  14234. */
  14235. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14236. var vao = this._gl.createVertexArray();
  14237. this._vaoRecordInProgress = true;
  14238. this._gl.bindVertexArray(vao);
  14239. this._mustWipeVertexAttributes = true;
  14240. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14241. this.bindIndexBuffer(indexBuffer);
  14242. this._vaoRecordInProgress = false;
  14243. this._gl.bindVertexArray(null);
  14244. return vao;
  14245. };
  14246. /**
  14247. * Bind a specific vertex array object
  14248. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14249. * @param vertexArrayObject defines the vertex array object to bind
  14250. * @param indexBuffer defines the index buffer to bind
  14251. */
  14252. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14253. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14254. this._cachedVertexArrayObject = vertexArrayObject;
  14255. this._gl.bindVertexArray(vertexArrayObject);
  14256. this._cachedVertexBuffers = null;
  14257. this._cachedIndexBuffer = null;
  14258. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14259. this._mustWipeVertexAttributes = true;
  14260. }
  14261. };
  14262. /**
  14263. * Bind webGl buffers directly to the webGL context
  14264. * @param vertexBuffer defines the vertex buffer to bind
  14265. * @param indexBuffer defines the index buffer to bind
  14266. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14267. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14268. * @param effect defines the effect associated with the vertex buffer
  14269. */
  14270. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14271. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14272. this._cachedVertexBuffers = vertexBuffer;
  14273. this._cachedEffectForVertexBuffers = effect;
  14274. var attributesCount = effect.getAttributesCount();
  14275. this._unbindVertexArrayObject();
  14276. this.unbindAllAttributes();
  14277. var offset = 0;
  14278. for (var index = 0; index < attributesCount; index++) {
  14279. if (index < vertexDeclaration.length) {
  14280. var order = effect.getAttributeLocation(index);
  14281. if (order >= 0) {
  14282. this._gl.enableVertexAttribArray(order);
  14283. this._vertexAttribArraysEnabled[order] = true;
  14284. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14285. }
  14286. offset += vertexDeclaration[index] * 4;
  14287. }
  14288. }
  14289. }
  14290. this._bindIndexBufferWithCache(indexBuffer);
  14291. };
  14292. Engine.prototype._unbindVertexArrayObject = function () {
  14293. if (!this._cachedVertexArrayObject) {
  14294. return;
  14295. }
  14296. this._cachedVertexArrayObject = null;
  14297. this._gl.bindVertexArray(null);
  14298. };
  14299. /**
  14300. * Bind a list of vertex buffers to the webGL context
  14301. * @param vertexBuffers defines the list of vertex buffers to bind
  14302. * @param indexBuffer defines the index buffer to bind
  14303. * @param effect defines the effect associated with the vertex buffers
  14304. */
  14305. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14306. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14307. this._cachedVertexBuffers = vertexBuffers;
  14308. this._cachedEffectForVertexBuffers = effect;
  14309. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14310. }
  14311. this._bindIndexBufferWithCache(indexBuffer);
  14312. };
  14313. /**
  14314. * Unbind all instance attributes
  14315. */
  14316. Engine.prototype.unbindInstanceAttributes = function () {
  14317. var boundBuffer;
  14318. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14319. var instancesBuffer = this._currentInstanceBuffers[i];
  14320. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14321. boundBuffer = instancesBuffer;
  14322. this.bindArrayBuffer(instancesBuffer);
  14323. }
  14324. var offsetLocation = this._currentInstanceLocations[i];
  14325. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14326. }
  14327. this._currentInstanceBuffers.length = 0;
  14328. this._currentInstanceLocations.length = 0;
  14329. };
  14330. /**
  14331. * Release and free the memory of a vertex array object
  14332. * @param vao defines the vertex array object to delete
  14333. */
  14334. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14335. this._gl.deleteVertexArray(vao);
  14336. };
  14337. /** @hidden */
  14338. Engine.prototype._releaseBuffer = function (buffer) {
  14339. buffer.references--;
  14340. if (buffer.references === 0) {
  14341. this._gl.deleteBuffer(buffer);
  14342. return true;
  14343. }
  14344. return false;
  14345. };
  14346. /**
  14347. * Creates a webGL buffer to use with instanciation
  14348. * @param capacity defines the size of the buffer
  14349. * @returns the webGL buffer
  14350. */
  14351. Engine.prototype.createInstancesBuffer = function (capacity) {
  14352. var buffer = this._gl.createBuffer();
  14353. if (!buffer) {
  14354. throw new Error("Unable to create instance buffer");
  14355. }
  14356. buffer.capacity = capacity;
  14357. this.bindArrayBuffer(buffer);
  14358. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14359. return buffer;
  14360. };
  14361. /**
  14362. * Delete a webGL buffer used with instanciation
  14363. * @param buffer defines the webGL buffer to delete
  14364. */
  14365. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14366. this._gl.deleteBuffer(buffer);
  14367. };
  14368. /**
  14369. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14370. * @param instancesBuffer defines the webGL buffer to update and bind
  14371. * @param data defines the data to store in the buffer
  14372. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14373. */
  14374. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14375. this.bindArrayBuffer(instancesBuffer);
  14376. if (data) {
  14377. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14378. }
  14379. if (offsetLocations[0].index !== undefined) {
  14380. var stride = 0;
  14381. for (var i = 0; i < offsetLocations.length; i++) {
  14382. var ai = offsetLocations[i];
  14383. stride += ai.attributeSize * 4;
  14384. }
  14385. for (var i = 0; i < offsetLocations.length; i++) {
  14386. var ai = offsetLocations[i];
  14387. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14388. this._gl.enableVertexAttribArray(ai.index);
  14389. this._vertexAttribArraysEnabled[ai.index] = true;
  14390. }
  14391. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14392. this._gl.vertexAttribDivisor(ai.index, 1);
  14393. this._currentInstanceLocations.push(ai.index);
  14394. this._currentInstanceBuffers.push(instancesBuffer);
  14395. }
  14396. }
  14397. else {
  14398. for (var index = 0; index < 4; index++) {
  14399. var offsetLocation = offsetLocations[index];
  14400. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14401. this._gl.enableVertexAttribArray(offsetLocation);
  14402. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14403. }
  14404. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14405. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14406. this._currentInstanceLocations.push(offsetLocation);
  14407. this._currentInstanceBuffers.push(instancesBuffer);
  14408. }
  14409. }
  14410. };
  14411. /**
  14412. * Apply all cached states (depth, culling, stencil and alpha)
  14413. */
  14414. Engine.prototype.applyStates = function () {
  14415. this._depthCullingState.apply(this._gl);
  14416. this._stencilState.apply(this._gl);
  14417. this._alphaState.apply(this._gl);
  14418. };
  14419. /**
  14420. * Send a draw order
  14421. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14422. * @param indexStart defines the starting index
  14423. * @param indexCount defines the number of index to draw
  14424. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14425. */
  14426. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14427. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14428. };
  14429. /**
  14430. * Draw a list of points
  14431. * @param verticesStart defines the index of first vertex to draw
  14432. * @param verticesCount defines the count of vertices to draw
  14433. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14434. */
  14435. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14436. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14437. };
  14438. /**
  14439. * Draw a list of unindexed primitives
  14440. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14441. * @param verticesStart defines the index of first vertex to draw
  14442. * @param verticesCount defines the count of vertices to draw
  14443. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14444. */
  14445. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14446. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14447. };
  14448. /**
  14449. * Draw a list of indexed primitives
  14450. * @param fillMode defines the primitive to use
  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.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14456. // Apply states
  14457. this.applyStates();
  14458. this._drawCalls.addCount(1, false);
  14459. // Render
  14460. var drawMode = this._drawMode(fillMode);
  14461. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14462. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14463. if (instancesCount) {
  14464. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14465. }
  14466. else {
  14467. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14468. }
  14469. };
  14470. /**
  14471. * Draw a list of unindexed primitives
  14472. * @param fillMode defines the primitive to use
  14473. * @param verticesStart defines the index of first vertex to draw
  14474. * @param verticesCount defines the count of vertices to draw
  14475. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14476. */
  14477. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14478. // Apply states
  14479. this.applyStates();
  14480. this._drawCalls.addCount(1, false);
  14481. var drawMode = this._drawMode(fillMode);
  14482. if (instancesCount) {
  14483. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14484. }
  14485. else {
  14486. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14487. }
  14488. };
  14489. Engine.prototype._drawMode = function (fillMode) {
  14490. switch (fillMode) {
  14491. // Triangle views
  14492. case BABYLON.Material.TriangleFillMode:
  14493. return this._gl.TRIANGLES;
  14494. case BABYLON.Material.PointFillMode:
  14495. return this._gl.POINTS;
  14496. case BABYLON.Material.WireFrameFillMode:
  14497. return this._gl.LINES;
  14498. // Draw modes
  14499. case BABYLON.Material.PointListDrawMode:
  14500. return this._gl.POINTS;
  14501. case BABYLON.Material.LineListDrawMode:
  14502. return this._gl.LINES;
  14503. case BABYLON.Material.LineLoopDrawMode:
  14504. return this._gl.LINE_LOOP;
  14505. case BABYLON.Material.LineStripDrawMode:
  14506. return this._gl.LINE_STRIP;
  14507. case BABYLON.Material.TriangleStripDrawMode:
  14508. return this._gl.TRIANGLE_STRIP;
  14509. case BABYLON.Material.TriangleFanDrawMode:
  14510. return this._gl.TRIANGLE_FAN;
  14511. default:
  14512. return this._gl.TRIANGLES;
  14513. }
  14514. };
  14515. // Shaders
  14516. /** @hidden */
  14517. Engine.prototype._releaseEffect = function (effect) {
  14518. if (this._compiledEffects[effect._key]) {
  14519. delete this._compiledEffects[effect._key];
  14520. this._deleteProgram(effect.getProgram());
  14521. }
  14522. };
  14523. /** @hidden */
  14524. Engine.prototype._deleteProgram = function (program) {
  14525. if (program) {
  14526. program.__SPECTOR_rebuildProgram = null;
  14527. if (program.transformFeedback) {
  14528. this.deleteTransformFeedback(program.transformFeedback);
  14529. program.transformFeedback = null;
  14530. }
  14531. this._gl.deleteProgram(program);
  14532. }
  14533. };
  14534. /**
  14535. * Create a new effect (used to store vertex/fragment shaders)
  14536. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14537. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14538. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14539. * @param samplers defines an array of string used to represent textures
  14540. * @param defines defines the string containing the defines to use to compile the shaders
  14541. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14542. * @param onCompiled defines a function to call when the effect creation is successful
  14543. * @param onError defines a function to call when the effect creation has failed
  14544. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14545. * @returns the new Effect
  14546. */
  14547. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14548. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14549. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14550. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14551. if (this._compiledEffects[name]) {
  14552. var compiledEffect = this._compiledEffects[name];
  14553. if (onCompiled && compiledEffect.isReady()) {
  14554. onCompiled(compiledEffect);
  14555. }
  14556. return compiledEffect;
  14557. }
  14558. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14559. effect._key = name;
  14560. this._compiledEffects[name] = effect;
  14561. return effect;
  14562. };
  14563. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14564. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14565. };
  14566. Engine.prototype._compileRawShader = function (source, type) {
  14567. var gl = this._gl;
  14568. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14569. if (!shader) {
  14570. throw new Error("Something went wrong while compile the shader.");
  14571. }
  14572. gl.shaderSource(shader, source);
  14573. gl.compileShader(shader);
  14574. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14575. var log = gl.getShaderInfoLog(shader);
  14576. if (log) {
  14577. throw new Error(log);
  14578. }
  14579. }
  14580. return shader;
  14581. };
  14582. /**
  14583. * Directly creates a webGL program
  14584. * @param vertexCode defines the vertex shader code to use
  14585. * @param fragmentCode defines the fragment shader code to use
  14586. * @param context defines the webGL context to use (if not set, the current one will be used)
  14587. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14588. * @returns the new webGL program
  14589. */
  14590. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14591. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14592. context = context || this._gl;
  14593. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14594. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14595. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14596. };
  14597. /**
  14598. * Creates a webGL program
  14599. * @param vertexCode defines the vertex shader code to use
  14600. * @param fragmentCode defines the fragment shader code to use
  14601. * @param defines defines the string containing the defines to use to compile the shaders
  14602. * @param context defines the webGL context to use (if not set, the current one will be used)
  14603. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14604. * @returns the new webGL program
  14605. */
  14606. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14607. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14608. context = context || this._gl;
  14609. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14610. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14611. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14612. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14613. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14614. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14615. return program;
  14616. };
  14617. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14618. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14619. var shaderProgram = context.createProgram();
  14620. if (!shaderProgram) {
  14621. throw new Error("Unable to create program");
  14622. }
  14623. context.attachShader(shaderProgram, vertexShader);
  14624. context.attachShader(shaderProgram, fragmentShader);
  14625. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14626. var transformFeedback = this.createTransformFeedback();
  14627. this.bindTransformFeedback(transformFeedback);
  14628. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14629. shaderProgram.transformFeedback = transformFeedback;
  14630. }
  14631. context.linkProgram(shaderProgram);
  14632. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14633. this.bindTransformFeedback(null);
  14634. }
  14635. shaderProgram.context = context;
  14636. shaderProgram.vertexShader = vertexShader;
  14637. shaderProgram.fragmentShader = fragmentShader;
  14638. if (!this._caps.parallelShaderCompile) {
  14639. this._finalizeProgram(shaderProgram);
  14640. }
  14641. else {
  14642. shaderProgram.isParallelCompiled = true;
  14643. }
  14644. return shaderProgram;
  14645. };
  14646. Engine.prototype._finalizeProgram = function (shaderProgram) {
  14647. var context = shaderProgram.context;
  14648. var vertexShader = shaderProgram.vertexShader;
  14649. var fragmentShader = shaderProgram.fragmentShader;
  14650. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14651. if (!linked) {
  14652. var error = context.getProgramInfoLog(shaderProgram);
  14653. if (error) {
  14654. throw new Error(error);
  14655. }
  14656. }
  14657. if (this.validateShaderPrograms) {
  14658. context.validateProgram(shaderProgram);
  14659. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14660. if (!validated) {
  14661. var error = context.getProgramInfoLog(shaderProgram);
  14662. if (error) {
  14663. throw new Error(error);
  14664. }
  14665. }
  14666. }
  14667. context.deleteShader(vertexShader);
  14668. context.deleteShader(fragmentShader);
  14669. shaderProgram.context = undefined;
  14670. shaderProgram.vertexShader = undefined;
  14671. shaderProgram.fragmentShader = undefined;
  14672. if (shaderProgram.onCompiled) {
  14673. shaderProgram.onCompiled();
  14674. shaderProgram.onCompiled = undefined;
  14675. }
  14676. };
  14677. /** @hidden */
  14678. Engine.prototype._isProgramCompiled = function (shaderProgram) {
  14679. if (!shaderProgram.isParallelCompiled) {
  14680. return true;
  14681. }
  14682. if (this._gl.getProgramParameter(shaderProgram, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)) {
  14683. this._finalizeProgram(shaderProgram);
  14684. return true;
  14685. }
  14686. return false;
  14687. };
  14688. /** @hidden */
  14689. Engine.prototype._executeWhenProgramIsCompiled = function (shaderProgram, action) {
  14690. if (!shaderProgram.isParallelCompiled) {
  14691. action();
  14692. return;
  14693. }
  14694. shaderProgram.onCompiled = action;
  14695. };
  14696. /**
  14697. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14698. * @param shaderProgram defines the webGL program to use
  14699. * @param uniformsNames defines the list of uniform names
  14700. * @returns an array of webGL uniform locations
  14701. */
  14702. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14703. var results = new Array();
  14704. for (var index = 0; index < uniformsNames.length; index++) {
  14705. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14706. }
  14707. return results;
  14708. };
  14709. /**
  14710. * Gets the lsit of active attributes for a given webGL program
  14711. * @param shaderProgram defines the webGL program to use
  14712. * @param attributesNames defines the list of attribute names to get
  14713. * @returns an array of indices indicating the offset of each attribute
  14714. */
  14715. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14716. var results = [];
  14717. for (var index = 0; index < attributesNames.length; index++) {
  14718. try {
  14719. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14720. }
  14721. catch (e) {
  14722. results.push(-1);
  14723. }
  14724. }
  14725. return results;
  14726. };
  14727. /**
  14728. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14729. * @param effect defines the effect to activate
  14730. */
  14731. Engine.prototype.enableEffect = function (effect) {
  14732. if (!effect || effect === this._currentEffect) {
  14733. return;
  14734. }
  14735. // Use program
  14736. this.bindSamplers(effect);
  14737. this._currentEffect = effect;
  14738. if (effect.onBind) {
  14739. effect.onBind(effect);
  14740. }
  14741. if (effect._onBindObservable) {
  14742. effect._onBindObservable.notifyObservers(effect);
  14743. }
  14744. };
  14745. /**
  14746. * Set the value of an uniform to an array of int32
  14747. * @param uniform defines the webGL uniform location where to store the value
  14748. * @param array defines the array of int32 to store
  14749. */
  14750. Engine.prototype.setIntArray = function (uniform, array) {
  14751. if (!uniform) {
  14752. return;
  14753. }
  14754. this._gl.uniform1iv(uniform, array);
  14755. };
  14756. /**
  14757. * Set the value of an uniform to an array of int32 (stored as vec2)
  14758. * @param uniform defines the webGL uniform location where to store the value
  14759. * @param array defines the array of int32 to store
  14760. */
  14761. Engine.prototype.setIntArray2 = function (uniform, array) {
  14762. if (!uniform || array.length % 2 !== 0) {
  14763. return;
  14764. }
  14765. this._gl.uniform2iv(uniform, array);
  14766. };
  14767. /**
  14768. * Set the value of an uniform to an array of int32 (stored as vec3)
  14769. * @param uniform defines the webGL uniform location where to store the value
  14770. * @param array defines the array of int32 to store
  14771. */
  14772. Engine.prototype.setIntArray3 = function (uniform, array) {
  14773. if (!uniform || array.length % 3 !== 0) {
  14774. return;
  14775. }
  14776. this._gl.uniform3iv(uniform, array);
  14777. };
  14778. /**
  14779. * Set the value of an uniform to an array of int32 (stored as vec4)
  14780. * @param uniform defines the webGL uniform location where to store the value
  14781. * @param array defines the array of int32 to store
  14782. */
  14783. Engine.prototype.setIntArray4 = function (uniform, array) {
  14784. if (!uniform || array.length % 4 !== 0) {
  14785. return;
  14786. }
  14787. this._gl.uniform4iv(uniform, array);
  14788. };
  14789. /**
  14790. * Set the value of an uniform to an array of float32
  14791. * @param uniform defines the webGL uniform location where to store the value
  14792. * @param array defines the array of float32 to store
  14793. */
  14794. Engine.prototype.setFloatArray = function (uniform, array) {
  14795. if (!uniform) {
  14796. return;
  14797. }
  14798. this._gl.uniform1fv(uniform, array);
  14799. };
  14800. /**
  14801. * Set the value of an uniform to an array of float32 (stored as vec2)
  14802. * @param uniform defines the webGL uniform location where to store the value
  14803. * @param array defines the array of float32 to store
  14804. */
  14805. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14806. if (!uniform || array.length % 2 !== 0) {
  14807. return;
  14808. }
  14809. this._gl.uniform2fv(uniform, array);
  14810. };
  14811. /**
  14812. * Set the value of an uniform to an array of float32 (stored as vec3)
  14813. * @param uniform defines the webGL uniform location where to store the value
  14814. * @param array defines the array of float32 to store
  14815. */
  14816. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14817. if (!uniform || array.length % 3 !== 0) {
  14818. return;
  14819. }
  14820. this._gl.uniform3fv(uniform, array);
  14821. };
  14822. /**
  14823. * Set the value of an uniform to an array of float32 (stored as vec4)
  14824. * @param uniform defines the webGL uniform location where to store the value
  14825. * @param array defines the array of float32 to store
  14826. */
  14827. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14828. if (!uniform || array.length % 4 !== 0) {
  14829. return;
  14830. }
  14831. this._gl.uniform4fv(uniform, array);
  14832. };
  14833. /**
  14834. * Set the value of an uniform to an array of number
  14835. * @param uniform defines the webGL uniform location where to store the value
  14836. * @param array defines the array of number to store
  14837. */
  14838. Engine.prototype.setArray = function (uniform, array) {
  14839. if (!uniform) {
  14840. return;
  14841. }
  14842. this._gl.uniform1fv(uniform, array);
  14843. };
  14844. /**
  14845. * Set the value of an uniform to an array of number (stored as vec2)
  14846. * @param uniform defines the webGL uniform location where to store the value
  14847. * @param array defines the array of number to store
  14848. */
  14849. Engine.prototype.setArray2 = function (uniform, array) {
  14850. if (!uniform || array.length % 2 !== 0) {
  14851. return;
  14852. }
  14853. this._gl.uniform2fv(uniform, array);
  14854. };
  14855. /**
  14856. * Set the value of an uniform to an array of number (stored as vec3)
  14857. * @param uniform defines the webGL uniform location where to store the value
  14858. * @param array defines the array of number to store
  14859. */
  14860. Engine.prototype.setArray3 = function (uniform, array) {
  14861. if (!uniform || array.length % 3 !== 0) {
  14862. return;
  14863. }
  14864. this._gl.uniform3fv(uniform, array);
  14865. };
  14866. /**
  14867. * Set the value of an uniform to an array of number (stored as vec4)
  14868. * @param uniform defines the webGL uniform location where to store the value
  14869. * @param array defines the array of number to store
  14870. */
  14871. Engine.prototype.setArray4 = function (uniform, array) {
  14872. if (!uniform || array.length % 4 !== 0) {
  14873. return;
  14874. }
  14875. this._gl.uniform4fv(uniform, array);
  14876. };
  14877. /**
  14878. * Set the value of an uniform to an array of float32 (stored as matrices)
  14879. * @param uniform defines the webGL uniform location where to store the value
  14880. * @param matrices defines the array of float32 to store
  14881. */
  14882. Engine.prototype.setMatrices = function (uniform, matrices) {
  14883. if (!uniform) {
  14884. return;
  14885. }
  14886. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14887. };
  14888. /**
  14889. * Set the value of an uniform to a matrix
  14890. * @param uniform defines the webGL uniform location where to store the value
  14891. * @param matrix defines the matrix to store
  14892. */
  14893. Engine.prototype.setMatrix = function (uniform, matrix) {
  14894. if (!uniform) {
  14895. return;
  14896. }
  14897. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14898. };
  14899. /**
  14900. * Set the value of an uniform to a matrix (3x3)
  14901. * @param uniform defines the webGL uniform location where to store the value
  14902. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14903. */
  14904. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14905. if (!uniform) {
  14906. return;
  14907. }
  14908. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14909. };
  14910. /**
  14911. * Set the value of an uniform to a matrix (2x2)
  14912. * @param uniform defines the webGL uniform location where to store the value
  14913. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14914. */
  14915. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14916. if (!uniform) {
  14917. return;
  14918. }
  14919. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14920. };
  14921. /**
  14922. * Set the value of an uniform to a number (int)
  14923. * @param uniform defines the webGL uniform location where to store the value
  14924. * @param value defines the int number to store
  14925. */
  14926. Engine.prototype.setInt = function (uniform, value) {
  14927. if (!uniform) {
  14928. return;
  14929. }
  14930. this._gl.uniform1i(uniform, value);
  14931. };
  14932. /**
  14933. * Set the value of an uniform to a number (float)
  14934. * @param uniform defines the webGL uniform location where to store the value
  14935. * @param value defines the float number to store
  14936. */
  14937. Engine.prototype.setFloat = function (uniform, value) {
  14938. if (!uniform) {
  14939. return;
  14940. }
  14941. this._gl.uniform1f(uniform, value);
  14942. };
  14943. /**
  14944. * Set the value of an uniform to a vec2
  14945. * @param uniform defines the webGL uniform location where to store the value
  14946. * @param x defines the 1st component of the value
  14947. * @param y defines the 2nd component of the value
  14948. */
  14949. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14950. if (!uniform) {
  14951. return;
  14952. }
  14953. this._gl.uniform2f(uniform, x, y);
  14954. };
  14955. /**
  14956. * Set the value of an uniform to a vec3
  14957. * @param uniform defines the webGL uniform location where to store the value
  14958. * @param x defines the 1st component of the value
  14959. * @param y defines the 2nd component of the value
  14960. * @param z defines the 3rd component of the value
  14961. */
  14962. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14963. if (!uniform) {
  14964. return;
  14965. }
  14966. this._gl.uniform3f(uniform, x, y, z);
  14967. };
  14968. /**
  14969. * Set the value of an uniform to a boolean
  14970. * @param uniform defines the webGL uniform location where to store the value
  14971. * @param bool defines the boolean to store
  14972. */
  14973. Engine.prototype.setBool = function (uniform, bool) {
  14974. if (!uniform) {
  14975. return;
  14976. }
  14977. this._gl.uniform1i(uniform, bool);
  14978. };
  14979. /**
  14980. * Set the value of an uniform to a vec4
  14981. * @param uniform defines the webGL uniform location where to store the value
  14982. * @param x defines the 1st component of the value
  14983. * @param y defines the 2nd component of the value
  14984. * @param z defines the 3rd component of the value
  14985. * @param w defines the 4th component of the value
  14986. */
  14987. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14988. if (!uniform) {
  14989. return;
  14990. }
  14991. this._gl.uniform4f(uniform, x, y, z, w);
  14992. };
  14993. /**
  14994. * Set the value of an uniform to a Color3
  14995. * @param uniform defines the webGL uniform location where to store the value
  14996. * @param color3 defines the color to store
  14997. */
  14998. Engine.prototype.setColor3 = function (uniform, color3) {
  14999. if (!uniform) {
  15000. return;
  15001. }
  15002. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  15003. };
  15004. /**
  15005. * Set the value of an uniform to a Color3 and an alpha value
  15006. * @param uniform defines the webGL uniform location where to store the value
  15007. * @param color3 defines the color to store
  15008. * @param alpha defines the alpha component to store
  15009. */
  15010. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  15011. if (!uniform) {
  15012. return;
  15013. }
  15014. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  15015. };
  15016. /**
  15017. * Sets a Color4 on a uniform variable
  15018. * @param uniform defines the uniform location
  15019. * @param color4 defines the value to be set
  15020. */
  15021. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  15022. if (!uniform) {
  15023. return;
  15024. }
  15025. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  15026. };
  15027. // States
  15028. /**
  15029. * Set various states to the webGL context
  15030. * @param culling defines backface culling state
  15031. * @param zOffset defines the value to apply to zOffset (0 by default)
  15032. * @param force defines if states must be applied even if cache is up to date
  15033. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  15034. */
  15035. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  15036. if (zOffset === void 0) { zOffset = 0; }
  15037. if (reverseSide === void 0) { reverseSide = false; }
  15038. // Culling
  15039. if (this._depthCullingState.cull !== culling || force) {
  15040. this._depthCullingState.cull = culling;
  15041. }
  15042. // Cull face
  15043. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  15044. if (this._depthCullingState.cullFace !== cullFace || force) {
  15045. this._depthCullingState.cullFace = cullFace;
  15046. }
  15047. // Z offset
  15048. this.setZOffset(zOffset);
  15049. // Front face
  15050. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  15051. if (this._depthCullingState.frontFace !== frontFace || force) {
  15052. this._depthCullingState.frontFace = frontFace;
  15053. }
  15054. };
  15055. /**
  15056. * Set the z offset to apply to current rendering
  15057. * @param value defines the offset to apply
  15058. */
  15059. Engine.prototype.setZOffset = function (value) {
  15060. this._depthCullingState.zOffset = value;
  15061. };
  15062. /**
  15063. * Gets the current value of the zOffset
  15064. * @returns the current zOffset state
  15065. */
  15066. Engine.prototype.getZOffset = function () {
  15067. return this._depthCullingState.zOffset;
  15068. };
  15069. /**
  15070. * Enable or disable depth buffering
  15071. * @param enable defines the state to set
  15072. */
  15073. Engine.prototype.setDepthBuffer = function (enable) {
  15074. this._depthCullingState.depthTest = enable;
  15075. };
  15076. /**
  15077. * Gets a boolean indicating if depth writing is enabled
  15078. * @returns the current depth writing state
  15079. */
  15080. Engine.prototype.getDepthWrite = function () {
  15081. return this._depthCullingState.depthMask;
  15082. };
  15083. /**
  15084. * Enable or disable depth writing
  15085. * @param enable defines the state to set
  15086. */
  15087. Engine.prototype.setDepthWrite = function (enable) {
  15088. this._depthCullingState.depthMask = enable;
  15089. };
  15090. /**
  15091. * Enable or disable color writing
  15092. * @param enable defines the state to set
  15093. */
  15094. Engine.prototype.setColorWrite = function (enable) {
  15095. this._gl.colorMask(enable, enable, enable, enable);
  15096. this._colorWrite = enable;
  15097. };
  15098. /**
  15099. * Gets a boolean indicating if color writing is enabled
  15100. * @returns the current color writing state
  15101. */
  15102. Engine.prototype.getColorWrite = function () {
  15103. return this._colorWrite;
  15104. };
  15105. /**
  15106. * Sets alpha constants used by some alpha blending modes
  15107. * @param r defines the red component
  15108. * @param g defines the green component
  15109. * @param b defines the blue component
  15110. * @param a defines the alpha component
  15111. */
  15112. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  15113. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  15114. };
  15115. /**
  15116. * Sets the current alpha mode
  15117. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  15118. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  15119. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15120. */
  15121. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  15122. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  15123. if (this._alphaMode === mode) {
  15124. return;
  15125. }
  15126. switch (mode) {
  15127. case Engine.ALPHA_DISABLE:
  15128. this._alphaState.alphaBlend = false;
  15129. break;
  15130. case Engine.ALPHA_PREMULTIPLIED:
  15131. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15132. this._alphaState.alphaBlend = true;
  15133. break;
  15134. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  15135. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15136. this._alphaState.alphaBlend = true;
  15137. break;
  15138. case Engine.ALPHA_COMBINE:
  15139. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15140. this._alphaState.alphaBlend = true;
  15141. break;
  15142. case Engine.ALPHA_ONEONE:
  15143. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15144. this._alphaState.alphaBlend = true;
  15145. break;
  15146. case Engine.ALPHA_ADD:
  15147. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15148. this._alphaState.alphaBlend = true;
  15149. break;
  15150. case Engine.ALPHA_SUBTRACT:
  15151. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15152. this._alphaState.alphaBlend = true;
  15153. break;
  15154. case Engine.ALPHA_MULTIPLY:
  15155. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  15156. this._alphaState.alphaBlend = true;
  15157. break;
  15158. case Engine.ALPHA_MAXIMIZED:
  15159. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15160. this._alphaState.alphaBlend = true;
  15161. break;
  15162. case Engine.ALPHA_INTERPOLATE:
  15163. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  15164. this._alphaState.alphaBlend = true;
  15165. break;
  15166. case Engine.ALPHA_SCREENMODE:
  15167. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15168. this._alphaState.alphaBlend = true;
  15169. break;
  15170. }
  15171. if (!noDepthWriteChange) {
  15172. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  15173. }
  15174. this._alphaMode = mode;
  15175. };
  15176. /**
  15177. * Gets the current alpha mode
  15178. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15179. * @returns the current alpha mode
  15180. */
  15181. Engine.prototype.getAlphaMode = function () {
  15182. return this._alphaMode;
  15183. };
  15184. // Textures
  15185. /**
  15186. * Clears the list of texture accessible through engine.
  15187. * This can help preventing texture load conflict due to name collision.
  15188. */
  15189. Engine.prototype.clearInternalTexturesCache = function () {
  15190. this._internalTexturesCache = [];
  15191. };
  15192. /**
  15193. * Force the entire cache to be cleared
  15194. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  15195. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  15196. */
  15197. Engine.prototype.wipeCaches = function (bruteForce) {
  15198. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  15199. return;
  15200. }
  15201. this._currentEffect = null;
  15202. this._viewportCached.x = 0;
  15203. this._viewportCached.y = 0;
  15204. this._viewportCached.z = 0;
  15205. this._viewportCached.w = 0;
  15206. if (bruteForce) {
  15207. this.resetTextureCache();
  15208. this._currentProgram = null;
  15209. this._stencilState.reset();
  15210. this._depthCullingState.reset();
  15211. this.setDepthFunctionToLessOrEqual();
  15212. this._alphaState.reset();
  15213. this._unpackFlipYCached = null;
  15214. }
  15215. this._resetVertexBufferBinding();
  15216. this._cachedIndexBuffer = null;
  15217. this._cachedEffectForVertexBuffers = null;
  15218. this._unbindVertexArrayObject();
  15219. this.bindIndexBuffer(null);
  15220. };
  15221. /**
  15222. * Set the compressed texture format to use, based on the formats you have, and the formats
  15223. * supported by the hardware / browser.
  15224. *
  15225. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  15226. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  15227. * to API arguments needed to compressed textures. This puts the burden on the container
  15228. * generator to house the arcane code for determining these for current & future formats.
  15229. *
  15230. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  15231. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  15232. *
  15233. * Note: The result of this call is not taken into account when a texture is base64.
  15234. *
  15235. * @param formatsAvailable defines the list of those format families you have created
  15236. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  15237. *
  15238. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15239. * @returns The extension selected.
  15240. */
  15241. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15242. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15243. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15244. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15245. return this._textureFormatInUse = this._texturesSupported[i];
  15246. }
  15247. }
  15248. }
  15249. // actively set format to nothing, to allow this to be called more than once
  15250. // and possibly fail the 2nd time
  15251. this._textureFormatInUse = null;
  15252. return null;
  15253. };
  15254. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15255. var gl = this._gl;
  15256. var magFilter = gl.NEAREST;
  15257. var minFilter = gl.NEAREST;
  15258. switch (samplingMode) {
  15259. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15260. magFilter = gl.LINEAR;
  15261. if (generateMipMaps) {
  15262. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15263. }
  15264. else {
  15265. minFilter = gl.LINEAR;
  15266. }
  15267. break;
  15268. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15269. magFilter = gl.LINEAR;
  15270. if (generateMipMaps) {
  15271. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15272. }
  15273. else {
  15274. minFilter = gl.LINEAR;
  15275. }
  15276. break;
  15277. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15278. magFilter = gl.NEAREST;
  15279. if (generateMipMaps) {
  15280. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15281. }
  15282. else {
  15283. minFilter = gl.NEAREST;
  15284. }
  15285. break;
  15286. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15287. magFilter = gl.NEAREST;
  15288. if (generateMipMaps) {
  15289. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15290. }
  15291. else {
  15292. minFilter = gl.NEAREST;
  15293. }
  15294. break;
  15295. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15296. magFilter = gl.NEAREST;
  15297. if (generateMipMaps) {
  15298. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15299. }
  15300. else {
  15301. minFilter = gl.LINEAR;
  15302. }
  15303. break;
  15304. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15305. magFilter = gl.NEAREST;
  15306. if (generateMipMaps) {
  15307. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15308. }
  15309. else {
  15310. minFilter = gl.LINEAR;
  15311. }
  15312. break;
  15313. case Engine.TEXTURE_NEAREST_LINEAR:
  15314. magFilter = gl.NEAREST;
  15315. minFilter = gl.LINEAR;
  15316. break;
  15317. case Engine.TEXTURE_NEAREST_NEAREST:
  15318. magFilter = gl.NEAREST;
  15319. minFilter = gl.NEAREST;
  15320. break;
  15321. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15322. magFilter = gl.LINEAR;
  15323. if (generateMipMaps) {
  15324. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15325. }
  15326. else {
  15327. minFilter = gl.NEAREST;
  15328. }
  15329. break;
  15330. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15331. magFilter = gl.LINEAR;
  15332. if (generateMipMaps) {
  15333. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15334. }
  15335. else {
  15336. minFilter = gl.NEAREST;
  15337. }
  15338. break;
  15339. case Engine.TEXTURE_LINEAR_LINEAR:
  15340. magFilter = gl.LINEAR;
  15341. minFilter = gl.LINEAR;
  15342. break;
  15343. case Engine.TEXTURE_LINEAR_NEAREST:
  15344. magFilter = gl.LINEAR;
  15345. minFilter = gl.NEAREST;
  15346. break;
  15347. }
  15348. return {
  15349. min: minFilter,
  15350. mag: magFilter
  15351. };
  15352. };
  15353. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15354. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15355. var img;
  15356. var onload = function () {
  15357. loadedImages[index] = img;
  15358. loadedImages._internalCount++;
  15359. if (scene) {
  15360. scene._removePendingData(img);
  15361. }
  15362. if (loadedImages._internalCount === 6) {
  15363. onfinish(loadedImages);
  15364. }
  15365. };
  15366. var onerror = function (message, exception) {
  15367. if (scene) {
  15368. scene._removePendingData(img);
  15369. }
  15370. if (onErrorCallBack) {
  15371. onErrorCallBack(message, exception);
  15372. }
  15373. };
  15374. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null);
  15375. if (scene) {
  15376. scene._addPendingData(img);
  15377. }
  15378. };
  15379. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15380. if (onError === void 0) { onError = null; }
  15381. var loadedImages = [];
  15382. loadedImages._internalCount = 0;
  15383. for (var index = 0; index < 6; index++) {
  15384. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15385. }
  15386. };
  15387. /** @hidden */
  15388. Engine.prototype._createTexture = function () {
  15389. var texture = this._gl.createTexture();
  15390. if (!texture) {
  15391. throw new Error("Unable to create texture");
  15392. }
  15393. return texture;
  15394. };
  15395. /**
  15396. * Usually called from BABYLON.Texture.ts.
  15397. * Passed information to create a WebGLTexture
  15398. * @param urlArg defines a value which contains one of the following:
  15399. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15400. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15401. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15402. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15403. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15404. * @param scene needed for loading to the correct scene
  15405. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15406. * @param onLoad optional callback to be called upon successful completion
  15407. * @param onError optional callback to be called upon failure
  15408. * @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
  15409. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15410. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15411. * @param forcedExtension defines the extension to use to pick the right loader
  15412. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15413. */
  15414. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15415. var _this = this;
  15416. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15417. if (onLoad === void 0) { onLoad = null; }
  15418. if (onError === void 0) { onError = null; }
  15419. if (buffer === void 0) { buffer = null; }
  15420. if (fallback === void 0) { fallback = null; }
  15421. if (format === void 0) { format = null; }
  15422. if (forcedExtension === void 0) { forcedExtension = null; }
  15423. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15424. var fromData = url.substr(0, 5) === "data:";
  15425. var fromBlob = url.substr(0, 5) === "blob:";
  15426. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15427. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15428. // establish the file extension, if possible
  15429. var lastDot = url.lastIndexOf('.');
  15430. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15431. var loader = null;
  15432. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15433. var availableLoader = _a[_i];
  15434. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15435. loader = availableLoader;
  15436. break;
  15437. }
  15438. }
  15439. if (loader) {
  15440. url = loader.transformUrl(url, this._textureFormatInUse);
  15441. }
  15442. if (scene) {
  15443. scene._addPendingData(texture);
  15444. }
  15445. texture.url = url;
  15446. texture.generateMipMaps = !noMipmap;
  15447. texture.samplingMode = samplingMode;
  15448. texture.invertY = invertY;
  15449. if (!this._doNotHandleContextLost) {
  15450. // Keep a link to the buffer only if we plan to handle context lost
  15451. texture._buffer = buffer;
  15452. }
  15453. var onLoadObserver = null;
  15454. if (onLoad && !fallback) {
  15455. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15456. }
  15457. if (!fallback) {
  15458. this._internalTexturesCache.push(texture);
  15459. }
  15460. var onInternalError = function (message, exception) {
  15461. if (scene) {
  15462. scene._removePendingData(texture);
  15463. }
  15464. var customFallback = false;
  15465. if (loader) {
  15466. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15467. if (fallbackUrl) {
  15468. // Add Back
  15469. customFallback = true;
  15470. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15471. }
  15472. }
  15473. if (!customFallback) {
  15474. if (onLoadObserver) {
  15475. texture.onLoadedObservable.remove(onLoadObserver);
  15476. }
  15477. if (BABYLON.Tools.UseFallbackTexture) {
  15478. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15479. }
  15480. }
  15481. if (onError) {
  15482. onError(message || "Unknown error", exception);
  15483. }
  15484. };
  15485. // processing for non-image formats
  15486. if (loader) {
  15487. var callback = function (data) {
  15488. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15489. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15490. done();
  15491. return false;
  15492. }, samplingMode);
  15493. });
  15494. };
  15495. if (!buffer) {
  15496. this._loadFile(url, callback, undefined, scene ? scene.offlineProvider : undefined, true, function (request, exception) {
  15497. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15498. });
  15499. }
  15500. else {
  15501. callback(buffer);
  15502. }
  15503. }
  15504. else {
  15505. var onload = function (img) {
  15506. if (fromBlob && !_this._doNotHandleContextLost) {
  15507. // We need to store the image if we need to rebuild the texture
  15508. // in case of a webgl context lost
  15509. texture._buffer = img;
  15510. }
  15511. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15512. var gl = _this._gl;
  15513. var isPot = (img.width === potWidth && img.height === potHeight);
  15514. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15515. if (isPot) {
  15516. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15517. return false;
  15518. }
  15519. var maxTextureSize = _this._caps.maxTextureSize;
  15520. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15521. _this._prepareWorkingCanvas();
  15522. if (!_this._workingCanvas || !_this._workingContext) {
  15523. return false;
  15524. }
  15525. _this._workingCanvas.width = potWidth;
  15526. _this._workingCanvas.height = potHeight;
  15527. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15528. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15529. texture.width = potWidth;
  15530. texture.height = potHeight;
  15531. return false;
  15532. }
  15533. else {
  15534. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15535. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15536. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15537. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15538. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15539. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15540. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15541. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15542. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15543. _this._releaseTexture(source_1);
  15544. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15545. continuationCallback();
  15546. });
  15547. }
  15548. return true;
  15549. }, samplingMode);
  15550. };
  15551. if (!fromData || isBase64) {
  15552. if (buffer instanceof HTMLImageElement) {
  15553. onload(buffer);
  15554. }
  15555. else {
  15556. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null);
  15557. }
  15558. }
  15559. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15560. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null);
  15561. }
  15562. else {
  15563. onload(buffer);
  15564. }
  15565. }
  15566. return texture;
  15567. };
  15568. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15569. var _this = this;
  15570. var rtt = this.createRenderTargetTexture({
  15571. width: destination.width,
  15572. height: destination.height,
  15573. }, {
  15574. generateMipMaps: false,
  15575. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15576. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15577. generateDepthBuffer: false,
  15578. generateStencilBuffer: false
  15579. });
  15580. if (!this._rescalePostProcess) {
  15581. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15582. }
  15583. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15584. _this._rescalePostProcess.onApply = function (effect) {
  15585. effect._bindTexture("textureSampler", source);
  15586. };
  15587. var hostingScene = scene;
  15588. if (!hostingScene) {
  15589. hostingScene = _this.scenes[_this.scenes.length - 1];
  15590. }
  15591. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15592. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15593. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15594. _this.unBindFramebuffer(rtt);
  15595. _this._releaseTexture(rtt);
  15596. if (onComplete) {
  15597. onComplete();
  15598. }
  15599. });
  15600. };
  15601. /**
  15602. * Update a raw texture
  15603. * @param texture defines the texture to update
  15604. * @param data defines the data to store in the texture
  15605. * @param format defines the format of the data
  15606. * @param invertY defines if data must be stored with Y axis inverted
  15607. * @param compression defines the compression used (null by default)
  15608. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15609. */
  15610. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15611. if (compression === void 0) { compression = null; }
  15612. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15613. if (!texture) {
  15614. return;
  15615. }
  15616. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15617. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15618. // babylon's internalFormat but gl's texImage2D format
  15619. var internalFormat = this._getInternalFormat(format);
  15620. var textureType = this._getWebGLTextureType(type);
  15621. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15622. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15623. if (!this._doNotHandleContextLost) {
  15624. texture._bufferView = data;
  15625. texture.format = format;
  15626. texture.type = type;
  15627. texture.invertY = invertY;
  15628. texture._compression = compression;
  15629. }
  15630. if (texture.width % 4 !== 0) {
  15631. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15632. }
  15633. if (compression && data) {
  15634. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15635. }
  15636. else {
  15637. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15638. }
  15639. if (texture.generateMipMaps) {
  15640. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15641. }
  15642. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15643. // this.resetTextureCache();
  15644. texture.isReady = true;
  15645. };
  15646. /**
  15647. * Creates a raw texture
  15648. * @param data defines the data to store in the texture
  15649. * @param width defines the width of the texture
  15650. * @param height defines the height of the texture
  15651. * @param format defines the format of the data
  15652. * @param generateMipMaps defines if the engine should generate the mip levels
  15653. * @param invertY defines if data must be stored with Y axis inverted
  15654. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15655. * @param compression defines the compression used (null by default)
  15656. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15657. * @returns the raw texture inside an InternalTexture
  15658. */
  15659. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15660. if (compression === void 0) { compression = null; }
  15661. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15662. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15663. texture.baseWidth = width;
  15664. texture.baseHeight = height;
  15665. texture.width = width;
  15666. texture.height = height;
  15667. texture.format = format;
  15668. texture.generateMipMaps = generateMipMaps;
  15669. texture.samplingMode = samplingMode;
  15670. texture.invertY = invertY;
  15671. texture._compression = compression;
  15672. texture.type = type;
  15673. if (!this._doNotHandleContextLost) {
  15674. texture._bufferView = data;
  15675. }
  15676. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15677. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15678. // Filters
  15679. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15680. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15681. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15682. if (generateMipMaps) {
  15683. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15684. }
  15685. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15686. this._internalTexturesCache.push(texture);
  15687. return texture;
  15688. };
  15689. /** @hidden */
  15690. Engine.prototype._unpackFlipY = function (value) {
  15691. if (this._unpackFlipYCached !== value) {
  15692. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15693. if (this.enableUnpackFlipYCached) {
  15694. this._unpackFlipYCached = value;
  15695. }
  15696. }
  15697. };
  15698. /** @hidden */
  15699. Engine.prototype._getUnpackAlignement = function () {
  15700. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15701. };
  15702. /**
  15703. * Creates a dynamic texture
  15704. * @param width defines the width of the texture
  15705. * @param height defines the height of the texture
  15706. * @param generateMipMaps defines if the engine should generate the mip levels
  15707. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15708. * @returns the dynamic texture inside an InternalTexture
  15709. */
  15710. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15711. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15712. texture.baseWidth = width;
  15713. texture.baseHeight = height;
  15714. if (generateMipMaps) {
  15715. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15716. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15717. }
  15718. // this.resetTextureCache();
  15719. texture.width = width;
  15720. texture.height = height;
  15721. texture.isReady = false;
  15722. texture.generateMipMaps = generateMipMaps;
  15723. texture.samplingMode = samplingMode;
  15724. this.updateTextureSamplingMode(samplingMode, texture);
  15725. this._internalTexturesCache.push(texture);
  15726. return texture;
  15727. };
  15728. /**
  15729. * Update the sampling mode of a given texture
  15730. * @param samplingMode defines the required sampling mode
  15731. * @param texture defines the texture to update
  15732. */
  15733. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15734. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15735. if (texture.isCube) {
  15736. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15737. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15738. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15739. }
  15740. else if (texture.is3D) {
  15741. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15742. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15743. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15744. }
  15745. else {
  15746. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15747. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15748. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15749. }
  15750. texture.samplingMode = samplingMode;
  15751. };
  15752. /**
  15753. * Update the content of a dynamic texture
  15754. * @param texture defines the texture to update
  15755. * @param canvas defines the canvas containing the source
  15756. * @param invertY defines if data must be stored with Y axis inverted
  15757. * @param premulAlpha defines if alpha is stored as premultiplied
  15758. * @param format defines the format of the data
  15759. */
  15760. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15761. if (premulAlpha === void 0) { premulAlpha = false; }
  15762. if (!texture) {
  15763. return;
  15764. }
  15765. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15766. this._unpackFlipY(invertY);
  15767. if (premulAlpha) {
  15768. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15769. }
  15770. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15771. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15772. if (texture.generateMipMaps) {
  15773. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15774. }
  15775. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15776. if (premulAlpha) {
  15777. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15778. }
  15779. texture.isReady = true;
  15780. };
  15781. /**
  15782. * Update a video texture
  15783. * @param texture defines the texture to update
  15784. * @param video defines the video element to use
  15785. * @param invertY defines if data must be stored with Y axis inverted
  15786. */
  15787. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15788. if (!texture || texture._isDisabled) {
  15789. return;
  15790. }
  15791. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15792. this._unpackFlipY(!invertY); // Video are upside down by default
  15793. try {
  15794. // Testing video texture support
  15795. if (this._videoTextureSupported === undefined) {
  15796. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15797. if (this._gl.getError() !== 0) {
  15798. this._videoTextureSupported = false;
  15799. }
  15800. else {
  15801. this._videoTextureSupported = true;
  15802. }
  15803. }
  15804. // Copy video through the current working canvas if video texture is not supported
  15805. if (!this._videoTextureSupported) {
  15806. if (!texture._workingCanvas) {
  15807. texture._workingCanvas = document.createElement("canvas");
  15808. var context = texture._workingCanvas.getContext("2d");
  15809. if (!context) {
  15810. throw new Error("Unable to get 2d context");
  15811. }
  15812. texture._workingContext = context;
  15813. texture._workingCanvas.width = texture.width;
  15814. texture._workingCanvas.height = texture.height;
  15815. }
  15816. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15817. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15818. }
  15819. else {
  15820. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15821. }
  15822. if (texture.generateMipMaps) {
  15823. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15824. }
  15825. if (!wasPreviouslyBound) {
  15826. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15827. }
  15828. // this.resetTextureCache();
  15829. texture.isReady = true;
  15830. }
  15831. catch (ex) {
  15832. // Something unexpected
  15833. // Let's disable the texture
  15834. texture._isDisabled = true;
  15835. }
  15836. };
  15837. /**
  15838. * Updates a depth texture Comparison Mode and Function.
  15839. * If the comparison Function is equal to 0, the mode will be set to none.
  15840. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15841. * @param texture The texture to set the comparison function for
  15842. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15843. */
  15844. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15845. if (this.webGLVersion === 1) {
  15846. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15847. return;
  15848. }
  15849. var gl = this._gl;
  15850. if (texture.isCube) {
  15851. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15852. if (comparisonFunction === 0) {
  15853. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15854. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15855. }
  15856. else {
  15857. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15858. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15859. }
  15860. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15861. }
  15862. else {
  15863. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15864. if (comparisonFunction === 0) {
  15865. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15866. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15867. }
  15868. else {
  15869. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15871. }
  15872. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15873. }
  15874. texture._comparisonFunction = comparisonFunction;
  15875. };
  15876. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15877. var width = size.width || size;
  15878. var height = size.height || size;
  15879. internalTexture.baseWidth = width;
  15880. internalTexture.baseHeight = height;
  15881. internalTexture.width = width;
  15882. internalTexture.height = height;
  15883. internalTexture.isReady = true;
  15884. internalTexture.samples = 1;
  15885. internalTexture.generateMipMaps = false;
  15886. internalTexture._generateDepthBuffer = true;
  15887. internalTexture._generateStencilBuffer = generateStencil;
  15888. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15889. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15890. internalTexture._comparisonFunction = comparisonFunction;
  15891. var gl = this._gl;
  15892. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15893. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15894. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15895. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15896. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15897. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15898. if (comparisonFunction === 0) {
  15899. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15900. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15901. }
  15902. else {
  15903. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15904. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15905. }
  15906. };
  15907. /**
  15908. * Creates a depth stencil texture.
  15909. * This is only available in WebGL 2 or with the depth texture extension available.
  15910. * @param size The size of face edge in the texture.
  15911. * @param options The options defining the texture.
  15912. * @returns The texture
  15913. */
  15914. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15915. if (options.isCube) {
  15916. var width = size.width || size;
  15917. return this._createDepthStencilCubeTexture(width, options);
  15918. }
  15919. else {
  15920. return this._createDepthStencilTexture(size, options);
  15921. }
  15922. };
  15923. /**
  15924. * Creates a depth stencil texture.
  15925. * This is only available in WebGL 2 or with the depth texture extension available.
  15926. * @param size The size of face edge in the texture.
  15927. * @param options The options defining the texture.
  15928. * @returns The texture
  15929. */
  15930. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15931. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15932. if (!this._caps.depthTextureExtension) {
  15933. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15934. return internalTexture;
  15935. }
  15936. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15937. var gl = this._gl;
  15938. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15939. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15940. if (this.webGLVersion > 1) {
  15941. if (internalOptions.generateStencil) {
  15942. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15943. }
  15944. else {
  15945. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15946. }
  15947. }
  15948. else {
  15949. if (internalOptions.generateStencil) {
  15950. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15951. }
  15952. else {
  15953. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15954. }
  15955. }
  15956. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15957. return internalTexture;
  15958. };
  15959. /**
  15960. * Creates a depth stencil cube texture.
  15961. * This is only available in WebGL 2.
  15962. * @param size The size of face edge in the cube texture.
  15963. * @param options The options defining the cube texture.
  15964. * @returns The cube texture
  15965. */
  15966. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15967. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15968. internalTexture.isCube = true;
  15969. if (this.webGLVersion === 1) {
  15970. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15971. return internalTexture;
  15972. }
  15973. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15974. var gl = this._gl;
  15975. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15976. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15977. // Create the depth/stencil buffer
  15978. for (var face = 0; face < 6; face++) {
  15979. if (internalOptions.generateStencil) {
  15980. 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);
  15981. }
  15982. else {
  15983. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15984. }
  15985. }
  15986. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15987. return internalTexture;
  15988. };
  15989. /**
  15990. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15991. * @param renderTarget The render target to set the frame buffer for
  15992. */
  15993. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15994. // Create the framebuffer
  15995. var internalTexture = renderTarget.getInternalTexture();
  15996. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15997. return;
  15998. }
  15999. var gl = this._gl;
  16000. var depthStencilTexture = renderTarget.depthStencilTexture;
  16001. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  16002. if (depthStencilTexture.isCube) {
  16003. if (depthStencilTexture._generateStencilBuffer) {
  16004. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  16005. }
  16006. else {
  16007. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  16008. }
  16009. }
  16010. else {
  16011. if (depthStencilTexture._generateStencilBuffer) {
  16012. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  16013. }
  16014. else {
  16015. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  16016. }
  16017. }
  16018. this.bindUnboundFramebuffer(null);
  16019. };
  16020. /**
  16021. * Creates a new render target texture
  16022. * @param size defines the size of the texture
  16023. * @param options defines the options used to create the texture
  16024. * @returns a new render target texture stored in an InternalTexture
  16025. */
  16026. Engine.prototype.createRenderTargetTexture = function (size, options) {
  16027. var fullOptions = new RenderTargetCreationOptions();
  16028. if (options !== undefined && typeof options === "object") {
  16029. fullOptions.generateMipMaps = options.generateMipMaps;
  16030. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16031. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  16032. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  16033. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  16034. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  16035. }
  16036. else {
  16037. fullOptions.generateMipMaps = options;
  16038. fullOptions.generateDepthBuffer = true;
  16039. fullOptions.generateStencilBuffer = false;
  16040. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16041. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16042. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  16043. }
  16044. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16045. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16046. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16047. }
  16048. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16049. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16050. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16051. }
  16052. var gl = this._gl;
  16053. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16054. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16055. var width = size.width || size;
  16056. var height = size.height || size;
  16057. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  16058. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16059. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16060. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16061. }
  16062. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16064. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16065. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16066. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  16067. // Create the framebuffer
  16068. var currentFrameBuffer = this._currentFramebuffer;
  16069. var framebuffer = gl.createFramebuffer();
  16070. this.bindUnboundFramebuffer(framebuffer);
  16071. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16072. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  16073. if (fullOptions.generateMipMaps) {
  16074. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16075. }
  16076. // Unbind
  16077. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16078. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16079. this.bindUnboundFramebuffer(currentFrameBuffer);
  16080. texture._framebuffer = framebuffer;
  16081. texture.baseWidth = width;
  16082. texture.baseHeight = height;
  16083. texture.width = width;
  16084. texture.height = height;
  16085. texture.isReady = true;
  16086. texture.samples = 1;
  16087. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  16088. texture.samplingMode = fullOptions.samplingMode;
  16089. texture.type = fullOptions.type;
  16090. texture.format = fullOptions.format;
  16091. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16092. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  16093. // this.resetTextureCache();
  16094. this._internalTexturesCache.push(texture);
  16095. return texture;
  16096. };
  16097. /**
  16098. * Create a multi render target texture
  16099. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  16100. * @param size defines the size of the texture
  16101. * @param options defines the creation options
  16102. * @returns the cube texture as an InternalTexture
  16103. */
  16104. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  16105. var generateMipMaps = false;
  16106. var generateDepthBuffer = true;
  16107. var generateStencilBuffer = false;
  16108. var generateDepthTexture = false;
  16109. var textureCount = 1;
  16110. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  16111. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16112. var types = new Array();
  16113. var samplingModes = new Array();
  16114. if (options !== undefined) {
  16115. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  16116. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16117. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  16118. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  16119. textureCount = options.textureCount || 1;
  16120. if (options.types) {
  16121. types = options.types;
  16122. }
  16123. if (options.samplingModes) {
  16124. samplingModes = options.samplingModes;
  16125. }
  16126. }
  16127. var gl = this._gl;
  16128. // Create the framebuffer
  16129. var framebuffer = gl.createFramebuffer();
  16130. this.bindUnboundFramebuffer(framebuffer);
  16131. var width = size.width || size;
  16132. var height = size.height || size;
  16133. var textures = [];
  16134. var attachments = [];
  16135. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  16136. for (var i = 0; i < textureCount; i++) {
  16137. var samplingMode = samplingModes[i] || defaultSamplingMode;
  16138. var type = types[i] || defaultType;
  16139. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16140. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16141. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16142. }
  16143. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16144. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16145. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16146. }
  16147. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16148. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16149. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16150. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16151. }
  16152. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16153. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16154. textures.push(texture);
  16155. attachments.push(attachment);
  16156. gl.activeTexture(gl["TEXTURE" + i]);
  16157. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  16158. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16159. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16160. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16161. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16162. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16163. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16164. if (generateMipMaps) {
  16165. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16166. }
  16167. // Unbind
  16168. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16169. texture._framebuffer = framebuffer;
  16170. texture._depthStencilBuffer = depthStencilBuffer;
  16171. texture.baseWidth = width;
  16172. texture.baseHeight = height;
  16173. texture.width = width;
  16174. texture.height = height;
  16175. texture.isReady = true;
  16176. texture.samples = 1;
  16177. texture.generateMipMaps = generateMipMaps;
  16178. texture.samplingMode = samplingMode;
  16179. texture.type = type;
  16180. texture._generateDepthBuffer = generateDepthBuffer;
  16181. texture._generateStencilBuffer = generateStencilBuffer;
  16182. texture._attachments = attachments;
  16183. this._internalTexturesCache.push(texture);
  16184. }
  16185. if (generateDepthTexture && this._caps.depthTextureExtension) {
  16186. // Depth texture
  16187. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16188. gl.activeTexture(gl.TEXTURE0);
  16189. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  16190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16191. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16192. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16194. 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);
  16195. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  16196. depthTexture._framebuffer = framebuffer;
  16197. depthTexture.baseWidth = width;
  16198. depthTexture.baseHeight = height;
  16199. depthTexture.width = width;
  16200. depthTexture.height = height;
  16201. depthTexture.isReady = true;
  16202. depthTexture.samples = 1;
  16203. depthTexture.generateMipMaps = generateMipMaps;
  16204. depthTexture.samplingMode = gl.NEAREST;
  16205. depthTexture._generateDepthBuffer = generateDepthBuffer;
  16206. depthTexture._generateStencilBuffer = generateStencilBuffer;
  16207. textures.push(depthTexture);
  16208. this._internalTexturesCache.push(depthTexture);
  16209. }
  16210. gl.drawBuffers(attachments);
  16211. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16212. this.bindUnboundFramebuffer(null);
  16213. this.resetTextureCache();
  16214. return textures;
  16215. };
  16216. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  16217. if (samples === void 0) { samples = 1; }
  16218. var depthStencilBuffer = null;
  16219. var gl = this._gl;
  16220. // Create the depth/stencil buffer
  16221. if (generateStencilBuffer) {
  16222. depthStencilBuffer = gl.createRenderbuffer();
  16223. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16224. if (samples > 1) {
  16225. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  16226. }
  16227. else {
  16228. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  16229. }
  16230. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16231. }
  16232. else if (generateDepthBuffer) {
  16233. depthStencilBuffer = gl.createRenderbuffer();
  16234. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16235. if (samples > 1) {
  16236. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  16237. }
  16238. else {
  16239. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16240. }
  16241. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16242. }
  16243. return depthStencilBuffer;
  16244. };
  16245. /**
  16246. * Updates the sample count of a render target texture
  16247. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16248. * @param texture defines the texture to update
  16249. * @param samples defines the sample count to set
  16250. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16251. */
  16252. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16253. if (this.webGLVersion < 2 || !texture) {
  16254. return 1;
  16255. }
  16256. if (texture.samples === samples) {
  16257. return samples;
  16258. }
  16259. var gl = this._gl;
  16260. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16261. // Dispose previous render buffers
  16262. if (texture._depthStencilBuffer) {
  16263. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16264. texture._depthStencilBuffer = null;
  16265. }
  16266. if (texture._MSAAFramebuffer) {
  16267. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16268. texture._MSAAFramebuffer = null;
  16269. }
  16270. if (texture._MSAARenderBuffer) {
  16271. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16272. texture._MSAARenderBuffer = null;
  16273. }
  16274. if (samples > 1) {
  16275. var framebuffer = gl.createFramebuffer();
  16276. if (!framebuffer) {
  16277. throw new Error("Unable to create multi sampled framebuffer");
  16278. }
  16279. texture._MSAAFramebuffer = framebuffer;
  16280. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16281. var colorRenderbuffer = gl.createRenderbuffer();
  16282. if (!colorRenderbuffer) {
  16283. throw new Error("Unable to create multi sampled framebuffer");
  16284. }
  16285. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16286. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16287. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16288. texture._MSAARenderBuffer = colorRenderbuffer;
  16289. }
  16290. else {
  16291. this.bindUnboundFramebuffer(texture._framebuffer);
  16292. }
  16293. texture.samples = samples;
  16294. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16295. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16296. this.bindUnboundFramebuffer(null);
  16297. return samples;
  16298. };
  16299. /**
  16300. * Update the sample count for a given multiple render target texture
  16301. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16302. * @param textures defines the textures to update
  16303. * @param samples defines the sample count to set
  16304. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16305. */
  16306. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16307. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16308. return 1;
  16309. }
  16310. if (textures[0].samples === samples) {
  16311. return samples;
  16312. }
  16313. var gl = this._gl;
  16314. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16315. // Dispose previous render buffers
  16316. if (textures[0]._depthStencilBuffer) {
  16317. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16318. textures[0]._depthStencilBuffer = null;
  16319. }
  16320. if (textures[0]._MSAAFramebuffer) {
  16321. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16322. textures[0]._MSAAFramebuffer = null;
  16323. }
  16324. for (var i = 0; i < textures.length; i++) {
  16325. if (textures[i]._MSAARenderBuffer) {
  16326. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16327. textures[i]._MSAARenderBuffer = null;
  16328. }
  16329. }
  16330. if (samples > 1) {
  16331. var framebuffer = gl.createFramebuffer();
  16332. if (!framebuffer) {
  16333. throw new Error("Unable to create multi sampled framebuffer");
  16334. }
  16335. this.bindUnboundFramebuffer(framebuffer);
  16336. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16337. var attachments = [];
  16338. for (var i = 0; i < textures.length; i++) {
  16339. var texture = textures[i];
  16340. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16341. var colorRenderbuffer = gl.createRenderbuffer();
  16342. if (!colorRenderbuffer) {
  16343. throw new Error("Unable to create multi sampled framebuffer");
  16344. }
  16345. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16346. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16347. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16348. texture._MSAAFramebuffer = framebuffer;
  16349. texture._MSAARenderBuffer = colorRenderbuffer;
  16350. texture.samples = samples;
  16351. texture._depthStencilBuffer = depthStencilBuffer;
  16352. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16353. attachments.push(attachment);
  16354. }
  16355. gl.drawBuffers(attachments);
  16356. }
  16357. else {
  16358. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16359. }
  16360. this.bindUnboundFramebuffer(null);
  16361. return samples;
  16362. };
  16363. /** @hidden */
  16364. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16365. if (faceIndex === void 0) { faceIndex = 0; }
  16366. if (lod === void 0) { lod = 0; }
  16367. var gl = this._gl;
  16368. var target = gl.TEXTURE_2D;
  16369. if (texture.isCube) {
  16370. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16371. }
  16372. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16373. };
  16374. /** @hidden */
  16375. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16376. if (faceIndex === void 0) { faceIndex = 0; }
  16377. if (lod === void 0) { lod = 0; }
  16378. var gl = this._gl;
  16379. var textureType = this._getWebGLTextureType(texture.type);
  16380. var format = this._getInternalFormat(texture.format);
  16381. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16382. this._unpackFlipY(texture.invertY);
  16383. var target = gl.TEXTURE_2D;
  16384. if (texture.isCube) {
  16385. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16386. }
  16387. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16388. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16389. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16390. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16391. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16392. };
  16393. /** @hidden */
  16394. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16395. if (faceIndex === void 0) { faceIndex = 0; }
  16396. if (lod === void 0) { lod = 0; }
  16397. var gl = this._gl;
  16398. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16399. this._bindTextureDirectly(bindTarget, texture, true);
  16400. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16401. this._bindTextureDirectly(bindTarget, null, true);
  16402. };
  16403. /** @hidden */
  16404. Engine.prototype._uploadImageToTexture = function (texture, image, 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. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16412. this._bindTextureDirectly(bindTarget, texture, true);
  16413. this._unpackFlipY(texture.invertY);
  16414. var target = gl.TEXTURE_2D;
  16415. if (texture.isCube) {
  16416. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16417. }
  16418. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16419. this._bindTextureDirectly(bindTarget, null, true);
  16420. };
  16421. /**
  16422. * Creates a new render target cube texture
  16423. * @param size defines the size of the texture
  16424. * @param options defines the options used to create the texture
  16425. * @returns a new render target cube texture stored in an InternalTexture
  16426. */
  16427. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16428. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16429. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16430. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16431. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16432. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16433. }
  16434. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16435. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16436. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16437. }
  16438. var gl = this._gl;
  16439. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16440. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16441. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16442. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16443. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16444. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16445. }
  16446. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16447. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16448. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16449. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16450. for (var face = 0; face < 6; face++) {
  16451. 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);
  16452. }
  16453. // Create the framebuffer
  16454. var framebuffer = gl.createFramebuffer();
  16455. this.bindUnboundFramebuffer(framebuffer);
  16456. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16457. // MipMaps
  16458. if (fullOptions.generateMipMaps) {
  16459. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16460. }
  16461. // Unbind
  16462. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16463. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16464. this.bindUnboundFramebuffer(null);
  16465. texture._framebuffer = framebuffer;
  16466. texture.width = size;
  16467. texture.height = size;
  16468. texture.isReady = true;
  16469. texture.isCube = true;
  16470. texture.samples = 1;
  16471. texture.generateMipMaps = fullOptions.generateMipMaps;
  16472. texture.samplingMode = fullOptions.samplingMode;
  16473. texture.type = fullOptions.type;
  16474. texture.format = fullOptions.format;
  16475. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16476. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16477. this._internalTexturesCache.push(texture);
  16478. return texture;
  16479. };
  16480. /**
  16481. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16482. * @param rootUrl defines the url where the file to load is located
  16483. * @param scene defines the current scene
  16484. * @param lodScale defines scale to apply to the mip map selection
  16485. * @param lodOffset defines offset to apply to the mip map selection
  16486. * @param onLoad defines an optional callback raised when the texture is loaded
  16487. * @param onError defines an optional callback raised if there is an issue to load the texture
  16488. * @param format defines the format of the data
  16489. * @param forcedExtension defines the extension to use to pick the right loader
  16490. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16491. * @returns the cube texture as an InternalTexture
  16492. */
  16493. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16494. var _this = this;
  16495. if (onLoad === void 0) { onLoad = null; }
  16496. if (onError === void 0) { onError = null; }
  16497. if (forcedExtension === void 0) { forcedExtension = null; }
  16498. if (createPolynomials === void 0) { createPolynomials = true; }
  16499. var callback = function (loadData) {
  16500. if (!loadData) {
  16501. if (onLoad) {
  16502. onLoad(null);
  16503. }
  16504. return;
  16505. }
  16506. var texture = loadData.texture;
  16507. if (!createPolynomials) {
  16508. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16509. }
  16510. else if (loadData.info.sphericalPolynomial) {
  16511. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16512. }
  16513. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16514. if (_this._caps.textureLOD) {
  16515. // Do not add extra process if texture lod is supported.
  16516. if (onLoad) {
  16517. onLoad(texture);
  16518. }
  16519. return;
  16520. }
  16521. var mipSlices = 3;
  16522. var gl = _this._gl;
  16523. var width = loadData.width;
  16524. if (!width) {
  16525. return;
  16526. }
  16527. var textures = [];
  16528. for (var i = 0; i < mipSlices; i++) {
  16529. //compute LOD from even spacing in smoothness (matching shader calculation)
  16530. var smoothness = i / (mipSlices - 1);
  16531. var roughness = 1 - smoothness;
  16532. var minLODIndex = lodOffset; // roughness = 0
  16533. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16534. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16535. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16536. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16537. glTextureFromLod.type = texture.type;
  16538. glTextureFromLod.format = texture.format;
  16539. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16540. glTextureFromLod.height = glTextureFromLod.width;
  16541. glTextureFromLod.isCube = true;
  16542. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16543. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16544. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16545. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16546. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16547. if (loadData.isDDS) {
  16548. var info = loadData.info;
  16549. var data = loadData.data;
  16550. _this._unpackFlipY(info.isCompressed);
  16551. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16552. }
  16553. else {
  16554. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16555. }
  16556. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16557. // Wrap in a base texture for easy binding.
  16558. var lodTexture = new BABYLON.BaseTexture(scene);
  16559. lodTexture.isCube = true;
  16560. lodTexture._texture = glTextureFromLod;
  16561. glTextureFromLod.isReady = true;
  16562. textures.push(lodTexture);
  16563. }
  16564. texture._lodTextureHigh = textures[2];
  16565. texture._lodTextureMid = textures[1];
  16566. texture._lodTextureLow = textures[0];
  16567. if (onLoad) {
  16568. onLoad(texture);
  16569. }
  16570. };
  16571. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16572. };
  16573. /**
  16574. * Creates a cube texture
  16575. * @param rootUrl defines the url where the files to load is located
  16576. * @param scene defines the current scene
  16577. * @param files defines the list of files to load (1 per face)
  16578. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16579. * @param onLoad defines an optional callback raised when the texture is loaded
  16580. * @param onError defines an optional callback raised if there is an issue to load the texture
  16581. * @param format defines the format of the data
  16582. * @param forcedExtension defines the extension to use to pick the right loader
  16583. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16584. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16585. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16586. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16587. * @returns the cube texture as an InternalTexture
  16588. */
  16589. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16590. var _this = this;
  16591. if (onLoad === void 0) { onLoad = null; }
  16592. if (onError === void 0) { onError = null; }
  16593. if (forcedExtension === void 0) { forcedExtension = null; }
  16594. if (createPolynomials === void 0) { createPolynomials = false; }
  16595. if (lodScale === void 0) { lodScale = 0; }
  16596. if (lodOffset === void 0) { lodOffset = 0; }
  16597. if (fallback === void 0) { fallback = null; }
  16598. var gl = this._gl;
  16599. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16600. texture.isCube = true;
  16601. texture.url = rootUrl;
  16602. texture.generateMipMaps = !noMipmap;
  16603. texture._lodGenerationScale = lodScale;
  16604. texture._lodGenerationOffset = lodOffset;
  16605. if (!this._doNotHandleContextLost) {
  16606. texture._extension = forcedExtension;
  16607. texture._files = files;
  16608. }
  16609. var lastDot = rootUrl.lastIndexOf('.');
  16610. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16611. var loader = null;
  16612. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16613. var availableLoader = _a[_i];
  16614. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16615. loader = availableLoader;
  16616. break;
  16617. }
  16618. }
  16619. var onInternalError = function (request, exception) {
  16620. if (loader) {
  16621. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16622. if (fallbackUrl) {
  16623. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16624. }
  16625. }
  16626. if (onError && request) {
  16627. onError(request.status + " " + request.statusText, exception);
  16628. }
  16629. };
  16630. if (loader) {
  16631. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16632. var onloaddata = function (data) {
  16633. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16634. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16635. };
  16636. if (files && files.length === 6) {
  16637. if (loader.supportCascades) {
  16638. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16639. }
  16640. else if (onError) {
  16641. onError("Textures type does not support cascades.");
  16642. }
  16643. }
  16644. else {
  16645. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16646. }
  16647. }
  16648. else {
  16649. if (!files) {
  16650. throw new Error("Cannot load cubemap because files were not defined");
  16651. }
  16652. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16653. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16654. var height = width;
  16655. _this._prepareWorkingCanvas();
  16656. if (!_this._workingCanvas || !_this._workingContext) {
  16657. return;
  16658. }
  16659. _this._workingCanvas.width = width;
  16660. _this._workingCanvas.height = height;
  16661. var faces = [
  16662. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16663. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16664. ];
  16665. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16666. _this._unpackFlipY(false);
  16667. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16668. for (var index = 0; index < faces.length; index++) {
  16669. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16670. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16671. }
  16672. if (!noMipmap) {
  16673. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16674. }
  16675. _this._setCubeMapTextureParams(!noMipmap);
  16676. texture.width = width;
  16677. texture.height = height;
  16678. texture.isReady = true;
  16679. if (format) {
  16680. texture.format = format;
  16681. }
  16682. texture.onLoadedObservable.notifyObservers(texture);
  16683. texture.onLoadedObservable.clear();
  16684. if (onLoad) {
  16685. onLoad();
  16686. }
  16687. }, files, onError);
  16688. }
  16689. this._internalTexturesCache.push(texture);
  16690. return texture;
  16691. };
  16692. /**
  16693. * @hidden
  16694. */
  16695. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16696. var gl = this._gl;
  16697. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16698. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16699. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16700. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16701. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16702. // this.resetTextureCache();
  16703. };
  16704. /**
  16705. * Update a raw cube texture
  16706. * @param texture defines the texture to udpdate
  16707. * @param data defines the data to store
  16708. * @param format defines the data format
  16709. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16710. * @param invertY defines if data must be stored with Y axis inverted
  16711. * @param compression defines the compression used (null by default)
  16712. * @param level defines which level of the texture to update
  16713. */
  16714. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16715. if (compression === void 0) { compression = null; }
  16716. if (level === void 0) { level = 0; }
  16717. texture._bufferViewArray = data;
  16718. texture.format = format;
  16719. texture.type = type;
  16720. texture.invertY = invertY;
  16721. texture._compression = compression;
  16722. var gl = this._gl;
  16723. var textureType = this._getWebGLTextureType(type);
  16724. var internalFormat = this._getInternalFormat(format);
  16725. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16726. var needConversion = false;
  16727. if (internalFormat === gl.RGB) {
  16728. internalFormat = gl.RGBA;
  16729. needConversion = true;
  16730. }
  16731. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16732. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16733. if (texture.width % 4 !== 0) {
  16734. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16735. }
  16736. // Data are known to be in +X +Y +Z -X -Y -Z
  16737. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16738. var faceData = data[faceIndex];
  16739. if (compression) {
  16740. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16741. }
  16742. else {
  16743. if (needConversion) {
  16744. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16745. }
  16746. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16747. }
  16748. }
  16749. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16750. if (isPot && texture.generateMipMaps && level === 0) {
  16751. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16752. }
  16753. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16754. // this.resetTextureCache();
  16755. texture.isReady = true;
  16756. };
  16757. /**
  16758. * Creates a new raw cube texture
  16759. * @param data defines the array of data to use to create each face
  16760. * @param size defines the size of the textures
  16761. * @param format defines the format of the data
  16762. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16763. * @param generateMipMaps defines if the engine should generate the mip levels
  16764. * @param invertY defines if data must be stored with Y axis inverted
  16765. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16766. * @param compression defines the compression used (null by default)
  16767. * @returns the cube texture as an InternalTexture
  16768. */
  16769. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16770. if (compression === void 0) { compression = null; }
  16771. var gl = this._gl;
  16772. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16773. texture.isCube = true;
  16774. texture.format = format;
  16775. texture.type = type;
  16776. if (!this._doNotHandleContextLost) {
  16777. texture._bufferViewArray = data;
  16778. }
  16779. var textureType = this._getWebGLTextureType(type);
  16780. var internalFormat = this._getInternalFormat(format);
  16781. if (internalFormat === gl.RGB) {
  16782. internalFormat = gl.RGBA;
  16783. }
  16784. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16785. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16786. generateMipMaps = false;
  16787. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16788. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16789. }
  16790. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16791. generateMipMaps = false;
  16792. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16793. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16794. }
  16795. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16796. generateMipMaps = false;
  16797. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16798. }
  16799. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16800. generateMipMaps = false;
  16801. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16802. }
  16803. var width = size;
  16804. var height = width;
  16805. texture.width = width;
  16806. texture.height = height;
  16807. // Double check on POT to generate Mips.
  16808. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16809. if (!isPot) {
  16810. generateMipMaps = false;
  16811. }
  16812. // Upload data if needed. The texture won't be ready until then.
  16813. if (data) {
  16814. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16815. }
  16816. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16817. // Filters
  16818. if (data && generateMipMaps) {
  16819. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16820. }
  16821. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16822. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16824. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16825. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16826. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16827. texture.generateMipMaps = generateMipMaps;
  16828. return texture;
  16829. };
  16830. /**
  16831. * Creates a new raw cube texture from a specified url
  16832. * @param url defines the url where the data is located
  16833. * @param scene defines the current scene
  16834. * @param size defines the size of the textures
  16835. * @param format defines the format of the data
  16836. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16837. * @param noMipmap defines if the engine should avoid generating the mip levels
  16838. * @param callback defines a callback used to extract texture data from loaded data
  16839. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16840. * @param onLoad defines a callback called when texture is loaded
  16841. * @param onError defines a callback called if there is an error
  16842. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16843. * @param invertY defines if data must be stored with Y axis inverted
  16844. * @returns the cube texture as an InternalTexture
  16845. */
  16846. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16847. var _this = this;
  16848. if (onLoad === void 0) { onLoad = null; }
  16849. if (onError === void 0) { onError = null; }
  16850. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16851. if (invertY === void 0) { invertY = false; }
  16852. var gl = this._gl;
  16853. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16854. scene._addPendingData(texture);
  16855. texture.url = url;
  16856. this._internalTexturesCache.push(texture);
  16857. var onerror = function (request, exception) {
  16858. scene._removePendingData(texture);
  16859. if (onError && request) {
  16860. onError(request.status + " " + request.statusText, exception);
  16861. }
  16862. };
  16863. var internalCallback = function (data) {
  16864. var width = texture.width;
  16865. var faceDataArrays = callback(data);
  16866. if (!faceDataArrays) {
  16867. return;
  16868. }
  16869. if (mipmapGenerator) {
  16870. var textureType = _this._getWebGLTextureType(type);
  16871. var internalFormat = _this._getInternalFormat(format);
  16872. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16873. var needConversion = false;
  16874. if (internalFormat === gl.RGB) {
  16875. internalFormat = gl.RGBA;
  16876. needConversion = true;
  16877. }
  16878. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16879. _this._unpackFlipY(false);
  16880. var mipData = mipmapGenerator(faceDataArrays);
  16881. for (var level = 0; level < mipData.length; level++) {
  16882. var mipSize = width >> level;
  16883. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16884. var mipFaceData = mipData[level][faceIndex];
  16885. if (needConversion) {
  16886. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16887. }
  16888. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16889. }
  16890. }
  16891. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16892. }
  16893. else {
  16894. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16895. }
  16896. texture.isReady = true;
  16897. // this.resetTextureCache();
  16898. scene._removePendingData(texture);
  16899. if (onLoad) {
  16900. onLoad();
  16901. }
  16902. };
  16903. this._loadFile(url, function (data) {
  16904. internalCallback(data);
  16905. }, undefined, scene.offlineProvider, true, onerror);
  16906. return texture;
  16907. };
  16908. /**
  16909. * Update a raw 3D texture
  16910. * @param texture defines the texture to update
  16911. * @param data defines the data to store
  16912. * @param format defines the data format
  16913. * @param invertY defines if data must be stored with Y axis inverted
  16914. * @param compression defines the used compression (can be null)
  16915. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16916. */
  16917. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16918. if (compression === void 0) { compression = null; }
  16919. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16920. var internalType = this._getWebGLTextureType(textureType);
  16921. var internalFormat = this._getInternalFormat(format);
  16922. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16923. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16924. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16925. if (!this._doNotHandleContextLost) {
  16926. texture._bufferView = data;
  16927. texture.format = format;
  16928. texture.invertY = invertY;
  16929. texture._compression = compression;
  16930. }
  16931. if (texture.width % 4 !== 0) {
  16932. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16933. }
  16934. if (compression && data) {
  16935. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16936. }
  16937. else {
  16938. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16939. }
  16940. if (texture.generateMipMaps) {
  16941. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16942. }
  16943. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16944. // this.resetTextureCache();
  16945. texture.isReady = true;
  16946. };
  16947. /**
  16948. * Creates a new raw 3D texture
  16949. * @param data defines the data used to create the texture
  16950. * @param width defines the width of the texture
  16951. * @param height defines the height of the texture
  16952. * @param depth defines the depth of the texture
  16953. * @param format defines the format of the texture
  16954. * @param generateMipMaps defines if the engine must generate mip levels
  16955. * @param invertY defines if data must be stored with Y axis inverted
  16956. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16957. * @param compression defines the compressed used (can be null)
  16958. * @param textureType defines the compressed used (can be null)
  16959. * @returns a new raw 3D texture (stored in an InternalTexture)
  16960. */
  16961. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16962. if (compression === void 0) { compression = null; }
  16963. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16964. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16965. texture.baseWidth = width;
  16966. texture.baseHeight = height;
  16967. texture.baseDepth = depth;
  16968. texture.width = width;
  16969. texture.height = height;
  16970. texture.depth = depth;
  16971. texture.format = format;
  16972. texture.type = textureType;
  16973. texture.generateMipMaps = generateMipMaps;
  16974. texture.samplingMode = samplingMode;
  16975. texture.is3D = true;
  16976. if (!this._doNotHandleContextLost) {
  16977. texture._bufferView = data;
  16978. }
  16979. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16980. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16981. // Filters
  16982. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16983. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16984. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16985. if (generateMipMaps) {
  16986. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16987. }
  16988. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16989. this._internalTexturesCache.push(texture);
  16990. return texture;
  16991. };
  16992. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16993. var gl = this._gl;
  16994. if (!gl) {
  16995. return;
  16996. }
  16997. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  17000. if (!noMipmap && !isCompressed) {
  17001. gl.generateMipmap(gl.TEXTURE_2D);
  17002. }
  17003. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  17004. // this.resetTextureCache();
  17005. if (scene) {
  17006. scene._removePendingData(texture);
  17007. }
  17008. texture.onLoadedObservable.notifyObservers(texture);
  17009. texture.onLoadedObservable.clear();
  17010. };
  17011. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  17012. var _this = this;
  17013. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  17014. var maxTextureSize = this.getCaps().maxTextureSize;
  17015. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  17016. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  17017. var gl = this._gl;
  17018. if (!gl) {
  17019. return;
  17020. }
  17021. if (!texture._webGLTexture) {
  17022. // this.resetTextureCache();
  17023. if (scene) {
  17024. scene._removePendingData(texture);
  17025. }
  17026. return;
  17027. }
  17028. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  17029. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  17030. texture.baseWidth = width;
  17031. texture.baseHeight = height;
  17032. texture.width = potWidth;
  17033. texture.height = potHeight;
  17034. texture.isReady = true;
  17035. if (processFunction(potWidth, potHeight, function () {
  17036. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  17037. })) {
  17038. // Returning as texture needs extra async steps
  17039. return;
  17040. }
  17041. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  17042. };
  17043. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  17044. // Create new RGBA data container.
  17045. var rgbaData;
  17046. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  17047. rgbaData = new Float32Array(width * height * 4);
  17048. }
  17049. else {
  17050. rgbaData = new Uint32Array(width * height * 4);
  17051. }
  17052. // Convert each pixel.
  17053. for (var x = 0; x < width; x++) {
  17054. for (var y = 0; y < height; y++) {
  17055. var index = (y * width + x) * 3;
  17056. var newIndex = (y * width + x) * 4;
  17057. // Map Old Value to new value.
  17058. rgbaData[newIndex + 0] = rgbData[index + 0];
  17059. rgbaData[newIndex + 1] = rgbData[index + 1];
  17060. rgbaData[newIndex + 2] = rgbData[index + 2];
  17061. // Add fully opaque alpha channel.
  17062. rgbaData[newIndex + 3] = 1;
  17063. }
  17064. }
  17065. return rgbaData;
  17066. };
  17067. /** @hidden */
  17068. Engine.prototype._releaseFramebufferObjects = function (texture) {
  17069. var gl = this._gl;
  17070. if (texture._framebuffer) {
  17071. gl.deleteFramebuffer(texture._framebuffer);
  17072. texture._framebuffer = null;
  17073. }
  17074. if (texture._depthStencilBuffer) {
  17075. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  17076. texture._depthStencilBuffer = null;
  17077. }
  17078. if (texture._MSAAFramebuffer) {
  17079. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  17080. texture._MSAAFramebuffer = null;
  17081. }
  17082. if (texture._MSAARenderBuffer) {
  17083. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  17084. texture._MSAARenderBuffer = null;
  17085. }
  17086. };
  17087. /** @hidden */
  17088. Engine.prototype._releaseTexture = function (texture) {
  17089. var gl = this._gl;
  17090. this._releaseFramebufferObjects(texture);
  17091. gl.deleteTexture(texture._webGLTexture);
  17092. // Unbind channels
  17093. this.unbindAllTextures();
  17094. var index = this._internalTexturesCache.indexOf(texture);
  17095. if (index !== -1) {
  17096. this._internalTexturesCache.splice(index, 1);
  17097. }
  17098. // Integrated fixed lod samplers.
  17099. if (texture._lodTextureHigh) {
  17100. texture._lodTextureHigh.dispose();
  17101. }
  17102. if (texture._lodTextureMid) {
  17103. texture._lodTextureMid.dispose();
  17104. }
  17105. if (texture._lodTextureLow) {
  17106. texture._lodTextureLow.dispose();
  17107. }
  17108. // Set output texture of post process to null if the texture has been released/disposed
  17109. this.scenes.forEach(function (scene) {
  17110. scene.postProcesses.forEach(function (postProcess) {
  17111. if (postProcess._outputTexture == texture) {
  17112. postProcess._outputTexture = null;
  17113. }
  17114. });
  17115. scene.cameras.forEach(function (camera) {
  17116. camera._postProcesses.forEach(function (postProcess) {
  17117. if (postProcess) {
  17118. if (postProcess._outputTexture == texture) {
  17119. postProcess._outputTexture = null;
  17120. }
  17121. }
  17122. });
  17123. });
  17124. });
  17125. };
  17126. Engine.prototype.setProgram = function (program) {
  17127. if (this._currentProgram !== program) {
  17128. this._gl.useProgram(program);
  17129. this._currentProgram = program;
  17130. }
  17131. };
  17132. /**
  17133. * Binds an effect to the webGL context
  17134. * @param effect defines the effect to bind
  17135. */
  17136. Engine.prototype.bindSamplers = function (effect) {
  17137. this.setProgram(effect.getProgram());
  17138. var samplers = effect.getSamplers();
  17139. for (var index = 0; index < samplers.length; index++) {
  17140. var uniform = effect.getUniform(samplers[index]);
  17141. if (uniform) {
  17142. this._boundUniforms[index] = uniform;
  17143. }
  17144. }
  17145. this._currentEffect = null;
  17146. };
  17147. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  17148. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  17149. return;
  17150. }
  17151. // Remove
  17152. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17153. // Bind last to it
  17154. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  17155. // Bind to dummy
  17156. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  17157. };
  17158. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  17159. if (!internalTexture) {
  17160. return -1;
  17161. }
  17162. internalTexture._initialSlot = channel;
  17163. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  17164. if (channel !== internalTexture._designatedSlot) {
  17165. this._textureCollisions.addCount(1, false);
  17166. }
  17167. }
  17168. else {
  17169. if (channel !== internalTexture._designatedSlot) {
  17170. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  17171. return internalTexture._designatedSlot;
  17172. }
  17173. else {
  17174. // No slot for this texture, let's pick a new one (if we find a free slot)
  17175. if (this._nextFreeTextureSlots.length) {
  17176. return this._nextFreeTextureSlots[0];
  17177. }
  17178. // We need to recycle the oldest bound texture, sorry.
  17179. this._textureCollisions.addCount(1, false);
  17180. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  17181. }
  17182. }
  17183. }
  17184. return channel;
  17185. };
  17186. Engine.prototype._linkTrackers = function (previous, next) {
  17187. previous.next = next;
  17188. next.previous = previous;
  17189. };
  17190. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  17191. var currentSlot = internalTexture._designatedSlot;
  17192. if (currentSlot === -1) {
  17193. return -1;
  17194. }
  17195. internalTexture._designatedSlot = -1;
  17196. if (this.disableTextureBindingOptimization) {
  17197. return -1;
  17198. }
  17199. // Remove from bound list
  17200. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17201. // Free the slot
  17202. this._boundTexturesCache[currentSlot] = null;
  17203. this._nextFreeTextureSlots.push(currentSlot);
  17204. return currentSlot;
  17205. };
  17206. Engine.prototype._activateCurrentTexture = function () {
  17207. if (this._currentTextureChannel !== this._activeChannel) {
  17208. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  17209. this._currentTextureChannel = this._activeChannel;
  17210. }
  17211. };
  17212. /** @hidden */
  17213. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  17214. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  17215. if (force === void 0) { force = false; }
  17216. var wasPreviouslyBound = false;
  17217. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  17218. this._activeChannel = texture._designatedSlot;
  17219. }
  17220. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  17221. var isTextureForRendering = texture && texture._initialSlot > -1;
  17222. if (currentTextureBound !== texture || force) {
  17223. if (currentTextureBound) {
  17224. this._removeDesignatedSlot(currentTextureBound);
  17225. }
  17226. this._activateCurrentTexture();
  17227. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  17228. this._boundTexturesCache[this._activeChannel] = texture;
  17229. if (texture) {
  17230. if (!this.disableTextureBindingOptimization) {
  17231. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  17232. if (slotIndex > -1) {
  17233. this._nextFreeTextureSlots.splice(slotIndex, 1);
  17234. }
  17235. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  17236. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  17237. }
  17238. texture._designatedSlot = this._activeChannel;
  17239. }
  17240. }
  17241. else if (forTextureDataUpdate) {
  17242. wasPreviouslyBound = true;
  17243. this._activateCurrentTexture();
  17244. }
  17245. if (isTextureForRendering && !forTextureDataUpdate) {
  17246. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17247. }
  17248. return wasPreviouslyBound;
  17249. };
  17250. /** @hidden */
  17251. Engine.prototype._bindTexture = function (channel, texture) {
  17252. if (channel < 0) {
  17253. return;
  17254. }
  17255. if (texture) {
  17256. channel = this._getCorrectTextureChannel(channel, texture);
  17257. }
  17258. this._activeChannel = channel;
  17259. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17260. };
  17261. /**
  17262. * Sets a texture to the webGL context from a postprocess
  17263. * @param channel defines the channel to use
  17264. * @param postProcess defines the source postprocess
  17265. */
  17266. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17267. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17268. };
  17269. /**
  17270. * Binds the output of the passed in post process to the texture channel specified
  17271. * @param channel The channel the texture should be bound to
  17272. * @param postProcess The post process which's output should be bound
  17273. */
  17274. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17275. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17276. };
  17277. /**
  17278. * Unbind all textures from the webGL context
  17279. */
  17280. Engine.prototype.unbindAllTextures = function () {
  17281. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17282. this._activeChannel = channel;
  17283. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17284. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17285. if (this.webGLVersion > 1) {
  17286. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17287. }
  17288. }
  17289. };
  17290. /**
  17291. * Sets a texture to the according uniform.
  17292. * @param channel The texture channel
  17293. * @param uniform The uniform to set
  17294. * @param texture The texture to apply
  17295. */
  17296. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17297. if (channel < 0) {
  17298. return;
  17299. }
  17300. if (uniform) {
  17301. this._boundUniforms[channel] = uniform;
  17302. }
  17303. this._setTexture(channel, texture);
  17304. };
  17305. /**
  17306. * Sets a depth stencil texture from a render target to the according uniform.
  17307. * @param channel The texture channel
  17308. * @param uniform The uniform to set
  17309. * @param texture The render target texture containing the depth stencil texture to apply
  17310. */
  17311. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17312. if (channel < 0) {
  17313. return;
  17314. }
  17315. if (uniform) {
  17316. this._boundUniforms[channel] = uniform;
  17317. }
  17318. if (!texture || !texture.depthStencilTexture) {
  17319. this._setTexture(channel, null);
  17320. }
  17321. else {
  17322. this._setTexture(channel, texture, false, true);
  17323. }
  17324. };
  17325. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17326. var uniform = this._boundUniforms[sourceSlot];
  17327. if (uniform._currentState === destination) {
  17328. return;
  17329. }
  17330. this._gl.uniform1i(uniform, destination);
  17331. uniform._currentState = destination;
  17332. };
  17333. Engine.prototype._getTextureWrapMode = function (mode) {
  17334. switch (mode) {
  17335. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17336. return this._gl.REPEAT;
  17337. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17338. return this._gl.CLAMP_TO_EDGE;
  17339. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17340. return this._gl.MIRRORED_REPEAT;
  17341. }
  17342. return this._gl.REPEAT;
  17343. };
  17344. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17345. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17346. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17347. // Not ready?
  17348. if (!texture) {
  17349. if (this._boundTexturesCache[channel] != null) {
  17350. this._activeChannel = channel;
  17351. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17352. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17353. if (this.webGLVersion > 1) {
  17354. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17355. }
  17356. }
  17357. return false;
  17358. }
  17359. // Video
  17360. if (texture.video) {
  17361. this._activeChannel = channel;
  17362. texture.update();
  17363. }
  17364. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17365. texture.delayLoad();
  17366. return false;
  17367. }
  17368. var internalTexture;
  17369. if (depthStencilTexture) {
  17370. internalTexture = texture.depthStencilTexture;
  17371. }
  17372. else if (texture.isReady()) {
  17373. internalTexture = texture.getInternalTexture();
  17374. }
  17375. else if (texture.isCube) {
  17376. internalTexture = this.emptyCubeTexture;
  17377. }
  17378. else if (texture.is3D) {
  17379. internalTexture = this.emptyTexture3D;
  17380. }
  17381. else {
  17382. internalTexture = this.emptyTexture;
  17383. }
  17384. if (!isPartOfTextureArray) {
  17385. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17386. }
  17387. var needToBind = true;
  17388. if (this._boundTexturesCache[channel] === internalTexture) {
  17389. this._moveBoundTextureOnTop(internalTexture);
  17390. if (!isPartOfTextureArray) {
  17391. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17392. }
  17393. needToBind = false;
  17394. }
  17395. this._activeChannel = channel;
  17396. if (internalTexture && internalTexture.is3D) {
  17397. if (needToBind) {
  17398. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17399. }
  17400. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17401. internalTexture._cachedWrapU = texture.wrapU;
  17402. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17403. }
  17404. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17405. internalTexture._cachedWrapV = texture.wrapV;
  17406. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17407. }
  17408. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17409. internalTexture._cachedWrapR = texture.wrapR;
  17410. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17411. }
  17412. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17413. }
  17414. else if (internalTexture && internalTexture.isCube) {
  17415. if (needToBind) {
  17416. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17417. }
  17418. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17419. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17420. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17421. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17422. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17423. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17424. }
  17425. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17426. }
  17427. else {
  17428. if (needToBind) {
  17429. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17430. }
  17431. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17432. internalTexture._cachedWrapU = texture.wrapU;
  17433. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17434. }
  17435. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17436. internalTexture._cachedWrapV = texture.wrapV;
  17437. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17438. }
  17439. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17440. }
  17441. return true;
  17442. };
  17443. /**
  17444. * Sets an array of texture to the webGL context
  17445. * @param channel defines the channel where the texture array must be set
  17446. * @param uniform defines the associated uniform location
  17447. * @param textures defines the array of textures to bind
  17448. */
  17449. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17450. if (channel < 0 || !uniform) {
  17451. return;
  17452. }
  17453. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17454. this._textureUnits = new Int32Array(textures.length);
  17455. }
  17456. for (var i = 0; i < textures.length; i++) {
  17457. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17458. }
  17459. this._gl.uniform1iv(uniform, this._textureUnits);
  17460. for (var index = 0; index < textures.length; index++) {
  17461. this._setTexture(this._textureUnits[index], textures[index], true);
  17462. }
  17463. };
  17464. /** @hidden */
  17465. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17466. var internalTexture = texture.getInternalTexture();
  17467. if (!internalTexture) {
  17468. return;
  17469. }
  17470. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17471. var value = texture.anisotropicFilteringLevel;
  17472. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17473. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17474. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17475. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17476. }
  17477. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17478. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17479. internalTexture._cachedAnisotropicFilteringLevel = value;
  17480. }
  17481. };
  17482. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17483. this._bindTextureDirectly(target, texture, true, true);
  17484. this._gl.texParameterf(target, parameter, value);
  17485. };
  17486. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17487. if (texture) {
  17488. this._bindTextureDirectly(target, texture, true, true);
  17489. }
  17490. this._gl.texParameteri(target, parameter, value);
  17491. };
  17492. /**
  17493. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17494. * @param x defines the x coordinate of the rectangle where pixels must be read
  17495. * @param y defines the y coordinate of the rectangle where pixels must be read
  17496. * @param width defines the width of the rectangle where pixels must be read
  17497. * @param height defines the height of the rectangle where pixels must be read
  17498. * @returns a Uint8Array containing RGBA colors
  17499. */
  17500. Engine.prototype.readPixels = function (x, y, width, height) {
  17501. var data = new Uint8Array(height * width * 4);
  17502. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17503. return data;
  17504. };
  17505. /**
  17506. * Add an externaly attached data from its key.
  17507. * This method call will fail and return false, if such key already exists.
  17508. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17509. * @param key the unique key that identifies the data
  17510. * @param data the data object to associate to the key for this Engine instance
  17511. * @return true if no such key were already present and the data was added successfully, false otherwise
  17512. */
  17513. Engine.prototype.addExternalData = function (key, data) {
  17514. if (!this._externalData) {
  17515. this._externalData = new BABYLON.StringDictionary();
  17516. }
  17517. return this._externalData.add(key, data);
  17518. };
  17519. /**
  17520. * Get an externaly attached data from its key
  17521. * @param key the unique key that identifies the data
  17522. * @return the associated data, if present (can be null), or undefined if not present
  17523. */
  17524. Engine.prototype.getExternalData = function (key) {
  17525. if (!this._externalData) {
  17526. this._externalData = new BABYLON.StringDictionary();
  17527. }
  17528. return this._externalData.get(key);
  17529. };
  17530. /**
  17531. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17532. * @param key the unique key that identifies the data
  17533. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17534. * @return the associated data, can be null if the factory returned null.
  17535. */
  17536. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17537. if (!this._externalData) {
  17538. this._externalData = new BABYLON.StringDictionary();
  17539. }
  17540. return this._externalData.getOrAddWithFactory(key, factory);
  17541. };
  17542. /**
  17543. * Remove an externaly attached data from the Engine instance
  17544. * @param key the unique key that identifies the data
  17545. * @return true if the data was successfully removed, false if it doesn't exist
  17546. */
  17547. Engine.prototype.removeExternalData = function (key) {
  17548. if (!this._externalData) {
  17549. this._externalData = new BABYLON.StringDictionary();
  17550. }
  17551. return this._externalData.remove(key);
  17552. };
  17553. /**
  17554. * Unbind all vertex attributes from the webGL context
  17555. */
  17556. Engine.prototype.unbindAllAttributes = function () {
  17557. if (this._mustWipeVertexAttributes) {
  17558. this._mustWipeVertexAttributes = false;
  17559. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17560. this._gl.disableVertexAttribArray(i);
  17561. this._vertexAttribArraysEnabled[i] = false;
  17562. this._currentBufferPointers[i].active = false;
  17563. }
  17564. return;
  17565. }
  17566. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17567. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17568. continue;
  17569. }
  17570. this._gl.disableVertexAttribArray(i);
  17571. this._vertexAttribArraysEnabled[i] = false;
  17572. this._currentBufferPointers[i].active = false;
  17573. }
  17574. };
  17575. /**
  17576. * 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
  17577. */
  17578. Engine.prototype.releaseEffects = function () {
  17579. for (var name in this._compiledEffects) {
  17580. this._deleteProgram(this._compiledEffects[name]._program);
  17581. }
  17582. this._compiledEffects = {};
  17583. };
  17584. /**
  17585. * Dispose and release all associated resources
  17586. */
  17587. Engine.prototype.dispose = function () {
  17588. this.hideLoadingUI();
  17589. this.stopRenderLoop();
  17590. // Release postProcesses
  17591. while (this.postProcesses.length) {
  17592. this.postProcesses[0].dispose();
  17593. }
  17594. // Empty texture
  17595. if (this._emptyTexture) {
  17596. this._releaseTexture(this._emptyTexture);
  17597. this._emptyTexture = null;
  17598. }
  17599. if (this._emptyCubeTexture) {
  17600. this._releaseTexture(this._emptyCubeTexture);
  17601. this._emptyCubeTexture = null;
  17602. }
  17603. // Rescale PP
  17604. if (this._rescalePostProcess) {
  17605. this._rescalePostProcess.dispose();
  17606. }
  17607. // Release scenes
  17608. while (this.scenes.length) {
  17609. this.scenes[0].dispose();
  17610. }
  17611. // Release audio engine
  17612. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17613. Engine.audioEngine.dispose();
  17614. }
  17615. // Release effects
  17616. this.releaseEffects();
  17617. // Unbind
  17618. this.unbindAllAttributes();
  17619. this._boundUniforms = [];
  17620. if (this._dummyFramebuffer) {
  17621. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17622. }
  17623. //WebVR
  17624. this.disableVR();
  17625. // Events
  17626. if (BABYLON.Tools.IsWindowObjectExist()) {
  17627. window.removeEventListener("blur", this._onBlur);
  17628. window.removeEventListener("focus", this._onFocus);
  17629. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17630. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17631. if (this._renderingCanvas) {
  17632. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17633. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17634. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17635. if (!this._doNotHandleContextLost) {
  17636. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17637. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17638. }
  17639. }
  17640. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17641. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17642. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17643. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17644. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17645. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17646. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17647. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17648. if (this._onVrDisplayConnect) {
  17649. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17650. if (this._onVrDisplayDisconnect) {
  17651. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17652. }
  17653. if (this._onVrDisplayPresentChange) {
  17654. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17655. }
  17656. this._onVrDisplayConnect = null;
  17657. this._onVrDisplayDisconnect = null;
  17658. }
  17659. }
  17660. // Remove from Instances
  17661. var index = Engine.Instances.indexOf(this);
  17662. if (index >= 0) {
  17663. Engine.Instances.splice(index, 1);
  17664. }
  17665. this._workingCanvas = null;
  17666. this._workingContext = null;
  17667. this._currentBufferPointers = [];
  17668. this._renderingCanvas = null;
  17669. this._currentProgram = null;
  17670. this._bindedRenderFunction = null;
  17671. this.onResizeObservable.clear();
  17672. this.onCanvasBlurObservable.clear();
  17673. this.onCanvasFocusObservable.clear();
  17674. this.onCanvasPointerOutObservable.clear();
  17675. this.onBeginFrameObservable.clear();
  17676. this.onEndFrameObservable.clear();
  17677. BABYLON.Effect.ResetCache();
  17678. // Abort active requests
  17679. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17680. var request = _a[_i];
  17681. request.abort();
  17682. }
  17683. };
  17684. // Loading screen
  17685. /**
  17686. * Display the loading screen
  17687. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17688. */
  17689. Engine.prototype.displayLoadingUI = function () {
  17690. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17691. return;
  17692. }
  17693. var loadingScreen = this.loadingScreen;
  17694. if (loadingScreen) {
  17695. loadingScreen.displayLoadingUI();
  17696. }
  17697. };
  17698. /**
  17699. * Hide the loading screen
  17700. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17701. */
  17702. Engine.prototype.hideLoadingUI = function () {
  17703. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17704. return;
  17705. }
  17706. var loadingScreen = this.loadingScreen;
  17707. if (loadingScreen) {
  17708. loadingScreen.hideLoadingUI();
  17709. }
  17710. };
  17711. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17712. /**
  17713. * Gets the current loading screen object
  17714. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17715. */
  17716. get: function () {
  17717. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas) {
  17718. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17719. }
  17720. return this._loadingScreen;
  17721. },
  17722. /**
  17723. * Sets the current loading screen object
  17724. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17725. */
  17726. set: function (loadingScreen) {
  17727. this._loadingScreen = loadingScreen;
  17728. },
  17729. enumerable: true,
  17730. configurable: true
  17731. });
  17732. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17733. /**
  17734. * Sets the current loading screen text
  17735. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17736. */
  17737. set: function (text) {
  17738. this.loadingScreen.loadingUIText = text;
  17739. },
  17740. enumerable: true,
  17741. configurable: true
  17742. });
  17743. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17744. /**
  17745. * Sets the current loading screen background color
  17746. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17747. */
  17748. set: function (color) {
  17749. this.loadingScreen.loadingUIBackgroundColor = color;
  17750. },
  17751. enumerable: true,
  17752. configurable: true
  17753. });
  17754. /**
  17755. * Attach a new callback raised when context lost event is fired
  17756. * @param callback defines the callback to call
  17757. */
  17758. Engine.prototype.attachContextLostEvent = function (callback) {
  17759. if (this._renderingCanvas) {
  17760. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17761. }
  17762. };
  17763. /**
  17764. * Attach a new callback raised when context restored event is fired
  17765. * @param callback defines the callback to call
  17766. */
  17767. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17768. if (this._renderingCanvas) {
  17769. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17770. }
  17771. };
  17772. /**
  17773. * Gets the source code of the vertex shader associated with a specific webGL program
  17774. * @param program defines the program to use
  17775. * @returns a string containing the source code of the vertex shader associated with the program
  17776. */
  17777. Engine.prototype.getVertexShaderSource = function (program) {
  17778. var shaders = this._gl.getAttachedShaders(program);
  17779. if (!shaders) {
  17780. return null;
  17781. }
  17782. return this._gl.getShaderSource(shaders[0]);
  17783. };
  17784. /**
  17785. * Gets the source code of the fragment shader associated with a specific webGL program
  17786. * @param program defines the program to use
  17787. * @returns a string containing the source code of the fragment shader associated with the program
  17788. */
  17789. Engine.prototype.getFragmentShaderSource = function (program) {
  17790. var shaders = this._gl.getAttachedShaders(program);
  17791. if (!shaders) {
  17792. return null;
  17793. }
  17794. return this._gl.getShaderSource(shaders[1]);
  17795. };
  17796. /**
  17797. * Get the current error code of the webGL context
  17798. * @returns the error code
  17799. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17800. */
  17801. Engine.prototype.getError = function () {
  17802. return this._gl.getError();
  17803. };
  17804. // FPS
  17805. /**
  17806. * Gets the current framerate
  17807. * @returns a number representing the framerate
  17808. */
  17809. Engine.prototype.getFps = function () {
  17810. return this._fps;
  17811. };
  17812. /**
  17813. * Gets the time spent between current and previous frame
  17814. * @returns a number representing the delta time in ms
  17815. */
  17816. Engine.prototype.getDeltaTime = function () {
  17817. return this._deltaTime;
  17818. };
  17819. Engine.prototype._measureFps = function () {
  17820. this._performanceMonitor.sampleFrame();
  17821. this._fps = this._performanceMonitor.averageFPS;
  17822. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17823. };
  17824. /** @hidden */
  17825. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17826. if (faceIndex === void 0) { faceIndex = -1; }
  17827. if (level === void 0) { level = 0; }
  17828. if (buffer === void 0) { buffer = null; }
  17829. var gl = this._gl;
  17830. if (!this._dummyFramebuffer) {
  17831. var dummy = gl.createFramebuffer();
  17832. if (!dummy) {
  17833. throw new Error("Unable to create dummy framebuffer");
  17834. }
  17835. this._dummyFramebuffer = dummy;
  17836. }
  17837. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17838. if (faceIndex > -1) {
  17839. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17840. }
  17841. else {
  17842. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17843. }
  17844. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17845. switch (readType) {
  17846. case gl.UNSIGNED_BYTE:
  17847. if (!buffer) {
  17848. buffer = new Uint8Array(4 * width * height);
  17849. }
  17850. readType = gl.UNSIGNED_BYTE;
  17851. break;
  17852. default:
  17853. if (!buffer) {
  17854. buffer = new Float32Array(4 * width * height);
  17855. }
  17856. readType = gl.FLOAT;
  17857. break;
  17858. }
  17859. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17860. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17861. return buffer;
  17862. };
  17863. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17864. if (this._webGLVersion > 1) {
  17865. return this._caps.colorBufferFloat;
  17866. }
  17867. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17868. };
  17869. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17870. if (this._webGLVersion > 1) {
  17871. return this._caps.colorBufferFloat;
  17872. }
  17873. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17874. };
  17875. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17876. Engine.prototype._canRenderToFramebuffer = function (type) {
  17877. var gl = this._gl;
  17878. //clear existing errors
  17879. while (gl.getError() !== gl.NO_ERROR) { }
  17880. var successful = true;
  17881. var texture = gl.createTexture();
  17882. gl.bindTexture(gl.TEXTURE_2D, texture);
  17883. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17884. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17885. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17886. var fb = gl.createFramebuffer();
  17887. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17888. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17889. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17890. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17891. successful = successful && (gl.getError() === gl.NO_ERROR);
  17892. //try render by clearing frame buffer's color buffer
  17893. if (successful) {
  17894. gl.clear(gl.COLOR_BUFFER_BIT);
  17895. successful = successful && (gl.getError() === gl.NO_ERROR);
  17896. }
  17897. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17898. if (successful) {
  17899. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17900. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17901. var readFormat = gl.RGBA;
  17902. var readType = gl.UNSIGNED_BYTE;
  17903. var buffer = new Uint8Array(4);
  17904. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17905. successful = successful && (gl.getError() === gl.NO_ERROR);
  17906. }
  17907. //clean up
  17908. gl.deleteTexture(texture);
  17909. gl.deleteFramebuffer(fb);
  17910. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17911. //clear accumulated errors
  17912. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17913. return successful;
  17914. };
  17915. /** @hidden */
  17916. Engine.prototype._getWebGLTextureType = function (type) {
  17917. if (this._webGLVersion === 1) {
  17918. switch (type) {
  17919. case Engine.TEXTURETYPE_FLOAT:
  17920. return this._gl.FLOAT;
  17921. case Engine.TEXTURETYPE_HALF_FLOAT:
  17922. return this._gl.HALF_FLOAT_OES;
  17923. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17924. return this._gl.UNSIGNED_BYTE;
  17925. }
  17926. return this._gl.UNSIGNED_BYTE;
  17927. }
  17928. switch (type) {
  17929. case Engine.TEXTURETYPE_BYTE:
  17930. return this._gl.BYTE;
  17931. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17932. return this._gl.UNSIGNED_BYTE;
  17933. case Engine.TEXTURETYPE_SHORT:
  17934. return this._gl.SHORT;
  17935. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17936. return this._gl.UNSIGNED_SHORT;
  17937. case Engine.TEXTURETYPE_INT:
  17938. return this._gl.INT;
  17939. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17940. return this._gl.UNSIGNED_INT;
  17941. case Engine.TEXTURETYPE_FLOAT:
  17942. return this._gl.FLOAT;
  17943. case Engine.TEXTURETYPE_HALF_FLOAT:
  17944. return this._gl.HALF_FLOAT;
  17945. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17946. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17947. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17948. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17949. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17950. return this._gl.UNSIGNED_SHORT_5_6_5;
  17951. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17952. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17953. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17954. return this._gl.UNSIGNED_INT_24_8;
  17955. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17956. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17957. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17958. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17959. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17960. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17961. }
  17962. return this._gl.UNSIGNED_BYTE;
  17963. };
  17964. Engine.prototype._getInternalFormat = function (format) {
  17965. var internalFormat = this._gl.RGBA;
  17966. switch (format) {
  17967. case Engine.TEXTUREFORMAT_ALPHA:
  17968. internalFormat = this._gl.ALPHA;
  17969. break;
  17970. case Engine.TEXTUREFORMAT_LUMINANCE:
  17971. internalFormat = this._gl.LUMINANCE;
  17972. break;
  17973. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17974. internalFormat = this._gl.LUMINANCE_ALPHA;
  17975. break;
  17976. case Engine.TEXTUREFORMAT_RED:
  17977. internalFormat = this._gl.RED;
  17978. break;
  17979. case Engine.TEXTUREFORMAT_RG:
  17980. internalFormat = this._gl.RG;
  17981. break;
  17982. case Engine.TEXTUREFORMAT_RGB:
  17983. internalFormat = this._gl.RGB;
  17984. break;
  17985. case Engine.TEXTUREFORMAT_RGBA:
  17986. internalFormat = this._gl.RGBA;
  17987. break;
  17988. }
  17989. if (this._webGLVersion > 1) {
  17990. switch (format) {
  17991. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17992. internalFormat = this._gl.RED_INTEGER;
  17993. break;
  17994. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17995. internalFormat = this._gl.RG_INTEGER;
  17996. break;
  17997. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17998. internalFormat = this._gl.RGB_INTEGER;
  17999. break;
  18000. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18001. internalFormat = this._gl.RGBA_INTEGER;
  18002. break;
  18003. }
  18004. }
  18005. return internalFormat;
  18006. };
  18007. /** @hidden */
  18008. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  18009. if (this._webGLVersion === 1) {
  18010. if (format !== undefined) {
  18011. switch (format) {
  18012. case Engine.TEXTUREFORMAT_ALPHA:
  18013. return this._gl.ALPHA;
  18014. case Engine.TEXTUREFORMAT_LUMINANCE:
  18015. return this._gl.LUMINANCE;
  18016. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  18017. return this._gl.LUMINANCE_ALPHA;
  18018. }
  18019. }
  18020. return this._gl.RGBA;
  18021. }
  18022. switch (type) {
  18023. case Engine.TEXTURETYPE_BYTE:
  18024. switch (format) {
  18025. case Engine.TEXTUREFORMAT_RED:
  18026. return this._gl.R8_SNORM;
  18027. case Engine.TEXTUREFORMAT_RG:
  18028. return this._gl.RG8_SNORM;
  18029. case Engine.TEXTUREFORMAT_RGB:
  18030. return this._gl.RGB8_SNORM;
  18031. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18032. return this._gl.R8I;
  18033. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18034. return this._gl.RG8I;
  18035. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18036. return this._gl.RGB8I;
  18037. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18038. return this._gl.RGBA8I;
  18039. default:
  18040. return this._gl.RGBA8_SNORM;
  18041. }
  18042. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18043. switch (format) {
  18044. case Engine.TEXTUREFORMAT_RED:
  18045. return this._gl.R8;
  18046. case Engine.TEXTUREFORMAT_RG:
  18047. return this._gl.RG8;
  18048. case Engine.TEXTUREFORMAT_RGB:
  18049. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  18050. case Engine.TEXTUREFORMAT_RGBA:
  18051. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  18052. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18053. return this._gl.R8UI;
  18054. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18055. return this._gl.RG8UI;
  18056. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18057. return this._gl.RGB8UI;
  18058. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18059. return this._gl.RGBA8UI;
  18060. default:
  18061. return this._gl.RGBA8;
  18062. }
  18063. case Engine.TEXTURETYPE_SHORT:
  18064. switch (format) {
  18065. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18066. return this._gl.R16I;
  18067. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18068. return this._gl.RG16I;
  18069. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18070. return this._gl.RGB16I;
  18071. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18072. return this._gl.RGBA16I;
  18073. default:
  18074. return this._gl.RGBA16I;
  18075. }
  18076. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  18077. switch (format) {
  18078. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18079. return this._gl.R16UI;
  18080. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18081. return this._gl.RG16UI;
  18082. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18083. return this._gl.RGB16UI;
  18084. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18085. return this._gl.RGBA16UI;
  18086. default:
  18087. return this._gl.RGBA16UI;
  18088. }
  18089. case Engine.TEXTURETYPE_INT:
  18090. switch (format) {
  18091. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18092. return this._gl.R32I;
  18093. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18094. return this._gl.RG32I;
  18095. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18096. return this._gl.RGB32I;
  18097. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18098. return this._gl.RGBA32I;
  18099. default:
  18100. return this._gl.RGBA32I;
  18101. }
  18102. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18103. switch (format) {
  18104. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18105. return this._gl.R32UI;
  18106. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18107. return this._gl.RG32UI;
  18108. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18109. return this._gl.RGB32UI;
  18110. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18111. return this._gl.RGBA32UI;
  18112. default:
  18113. return this._gl.RGBA32UI;
  18114. }
  18115. case Engine.TEXTURETYPE_FLOAT:
  18116. switch (format) {
  18117. case Engine.TEXTUREFORMAT_RED:
  18118. return this._gl.R32F; // By default. Other possibility is R16F.
  18119. case Engine.TEXTUREFORMAT_RG:
  18120. return this._gl.RG32F; // By default. Other possibility is RG16F.
  18121. case Engine.TEXTUREFORMAT_RGB:
  18122. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  18123. case Engine.TEXTUREFORMAT_RGBA:
  18124. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  18125. default:
  18126. return this._gl.RGBA32F;
  18127. }
  18128. case Engine.TEXTURETYPE_HALF_FLOAT:
  18129. switch (format) {
  18130. case Engine.TEXTUREFORMAT_RED:
  18131. return this._gl.R16F;
  18132. case Engine.TEXTUREFORMAT_RG:
  18133. return this._gl.RG16F;
  18134. case Engine.TEXTUREFORMAT_RGB:
  18135. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  18136. case Engine.TEXTUREFORMAT_RGBA:
  18137. return this._gl.RGBA16F;
  18138. default:
  18139. return this._gl.RGBA16F;
  18140. }
  18141. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18142. return this._gl.RGB565;
  18143. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18144. return this._gl.R11F_G11F_B10F;
  18145. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18146. return this._gl.RGB9_E5;
  18147. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18148. return this._gl.RGBA4;
  18149. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18150. return this._gl.RGB5_A1;
  18151. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18152. switch (format) {
  18153. case Engine.TEXTUREFORMAT_RGBA:
  18154. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  18155. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18156. return this._gl.RGB10_A2UI;
  18157. default:
  18158. return this._gl.RGB10_A2;
  18159. }
  18160. }
  18161. return this._gl.RGBA8;
  18162. };
  18163. /** @hidden */
  18164. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  18165. if (type === Engine.TEXTURETYPE_FLOAT) {
  18166. return this._gl.RGBA32F;
  18167. }
  18168. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18169. return this._gl.RGBA16F;
  18170. }
  18171. return this._gl.RGBA8;
  18172. };
  18173. /** @hidden */
  18174. Engine.prototype._loadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
  18175. var _this = this;
  18176. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  18177. this._activeRequests.push(request);
  18178. request.onCompleteObservable.add(function (request) {
  18179. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  18180. });
  18181. return request;
  18182. };
  18183. /** @hidden */
  18184. Engine.prototype._loadFileAsync = function (url, offlineProvider, useArrayBuffer) {
  18185. var _this = this;
  18186. return new Promise(function (resolve, reject) {
  18187. _this._loadFile(url, function (data) {
  18188. resolve(data);
  18189. }, undefined, offlineProvider, useArrayBuffer, function (request, exception) {
  18190. reject(exception);
  18191. });
  18192. });
  18193. };
  18194. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  18195. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  18196. var onload = function (data) {
  18197. loadedFiles[index] = data;
  18198. loadedFiles._internalCount++;
  18199. if (loadedFiles._internalCount === 6) {
  18200. onfinish(loadedFiles);
  18201. }
  18202. };
  18203. var onerror = function (request, exception) {
  18204. if (onErrorCallBack && request) {
  18205. onErrorCallBack(request.status + " " + request.statusText, exception);
  18206. }
  18207. };
  18208. this._loadFile(url, onload, undefined, undefined, true, onerror);
  18209. };
  18210. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  18211. if (onError === void 0) { onError = null; }
  18212. var loadedFiles = [];
  18213. loadedFiles._internalCount = 0;
  18214. for (var index = 0; index < 6; index++) {
  18215. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  18216. }
  18217. };
  18218. // Statics
  18219. /**
  18220. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  18221. * @returns true if the engine can be created
  18222. * @ignorenaming
  18223. */
  18224. Engine.isSupported = function () {
  18225. try {
  18226. var tempcanvas = document.createElement("canvas");
  18227. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  18228. return gl != null && !!window.WebGLRenderingContext;
  18229. }
  18230. catch (e) {
  18231. return false;
  18232. }
  18233. };
  18234. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  18235. Engine.ExceptionList = [
  18236. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18237. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18238. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18239. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18240. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18241. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18242. ];
  18243. /** Gets the list of created engines */
  18244. Engine.Instances = new Array();
  18245. /**
  18246. * Hidden
  18247. */
  18248. Engine._TextureLoaders = [];
  18249. // Const statics
  18250. /** Defines that alpha blending is disabled */
  18251. Engine.ALPHA_DISABLE = 0;
  18252. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18253. Engine.ALPHA_ADD = 1;
  18254. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18255. Engine.ALPHA_COMBINE = 2;
  18256. /** Defines that alpha blending to DEST - SRC * DEST */
  18257. Engine.ALPHA_SUBTRACT = 3;
  18258. /** Defines that alpha blending to SRC * DEST */
  18259. Engine.ALPHA_MULTIPLY = 4;
  18260. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18261. Engine.ALPHA_MAXIMIZED = 5;
  18262. /** Defines that alpha blending to SRC + DEST */
  18263. Engine.ALPHA_ONEONE = 6;
  18264. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18265. Engine.ALPHA_PREMULTIPLIED = 7;
  18266. /**
  18267. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18268. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18269. */
  18270. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18271. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18272. Engine.ALPHA_INTERPOLATE = 9;
  18273. /**
  18274. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18275. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18276. */
  18277. Engine.ALPHA_SCREENMODE = 10;
  18278. /** Defines that the ressource is not delayed*/
  18279. Engine.DELAYLOADSTATE_NONE = 0;
  18280. /** Defines that the ressource was successfully delay loaded */
  18281. Engine.DELAYLOADSTATE_LOADED = 1;
  18282. /** Defines that the ressource is currently delay loading */
  18283. Engine.DELAYLOADSTATE_LOADING = 2;
  18284. /** Defines that the ressource is delayed and has not started loading */
  18285. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18286. // Depht or Stencil test Constants.
  18287. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18288. Engine.NEVER = 0x0200;
  18289. /** 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 */
  18290. Engine.ALWAYS = 0x0207;
  18291. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18292. Engine.LESS = 0x0201;
  18293. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18294. Engine.EQUAL = 0x0202;
  18295. /** 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 */
  18296. Engine.LEQUAL = 0x0203;
  18297. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18298. Engine.GREATER = 0x0204;
  18299. /** 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 */
  18300. Engine.GEQUAL = 0x0206;
  18301. /** 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 */
  18302. Engine.NOTEQUAL = 0x0205;
  18303. // Stencil Actions Constants.
  18304. /** Passed to stencilOperation to specify that stencil value must be kept */
  18305. Engine.KEEP = 0x1E00;
  18306. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18307. Engine.REPLACE = 0x1E01;
  18308. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18309. Engine.INCR = 0x1E02;
  18310. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18311. Engine.DECR = 0x1E03;
  18312. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18313. Engine.INVERT = 0x150A;
  18314. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18315. Engine.INCR_WRAP = 0x8507;
  18316. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18317. Engine.DECR_WRAP = 0x8508;
  18318. /** Texture is not repeating outside of 0..1 UVs */
  18319. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18320. /** Texture is repeating outside of 0..1 UVs */
  18321. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18322. /** Texture is repeating and mirrored */
  18323. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18324. /** ALPHA */
  18325. Engine.TEXTUREFORMAT_ALPHA = 0;
  18326. /** LUMINANCE */
  18327. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18328. /** LUMINANCE_ALPHA */
  18329. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18330. /** RGB */
  18331. Engine.TEXTUREFORMAT_RGB = 4;
  18332. /** RGBA */
  18333. Engine.TEXTUREFORMAT_RGBA = 5;
  18334. /** RED */
  18335. Engine.TEXTUREFORMAT_RED = 6;
  18336. /** RED (2nd reference) */
  18337. Engine.TEXTUREFORMAT_R = 6;
  18338. /** RG */
  18339. Engine.TEXTUREFORMAT_RG = 7;
  18340. /** RED_INTEGER */
  18341. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18342. /** RED_INTEGER (2nd reference) */
  18343. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18344. /** RG_INTEGER */
  18345. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18346. /** RGB_INTEGER */
  18347. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18348. /** RGBA_INTEGER */
  18349. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18350. /** UNSIGNED_BYTE */
  18351. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18352. /** UNSIGNED_BYTE (2nd reference) */
  18353. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18354. /** FLOAT */
  18355. Engine.TEXTURETYPE_FLOAT = 1;
  18356. /** HALF_FLOAT */
  18357. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18358. /** BYTE */
  18359. Engine.TEXTURETYPE_BYTE = 3;
  18360. /** SHORT */
  18361. Engine.TEXTURETYPE_SHORT = 4;
  18362. /** UNSIGNED_SHORT */
  18363. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18364. /** INT */
  18365. Engine.TEXTURETYPE_INT = 6;
  18366. /** UNSIGNED_INT */
  18367. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18368. /** UNSIGNED_SHORT_4_4_4_4 */
  18369. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18370. /** UNSIGNED_SHORT_5_5_5_1 */
  18371. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18372. /** UNSIGNED_SHORT_5_6_5 */
  18373. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18374. /** UNSIGNED_INT_2_10_10_10_REV */
  18375. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18376. /** UNSIGNED_INT_24_8 */
  18377. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18378. /** UNSIGNED_INT_10F_11F_11F_REV */
  18379. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18380. /** UNSIGNED_INT_5_9_9_9_REV */
  18381. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18382. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18383. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18384. /** nearest is mag = nearest and min = nearest and mip = linear */
  18385. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18386. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18387. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18388. /** Trilinear is mag = linear and min = linear and mip = linear */
  18389. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18390. /** nearest is mag = nearest and min = nearest and mip = linear */
  18391. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18392. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18393. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18394. /** Trilinear is mag = linear and min = linear and mip = linear */
  18395. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18396. /** mag = nearest and min = nearest and mip = nearest */
  18397. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18398. /** mag = nearest and min = linear and mip = nearest */
  18399. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18400. /** mag = nearest and min = linear and mip = linear */
  18401. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18402. /** mag = nearest and min = linear and mip = none */
  18403. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18404. /** mag = nearest and min = nearest and mip = none */
  18405. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18406. /** mag = linear and min = nearest and mip = nearest */
  18407. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18408. /** mag = linear and min = nearest and mip = linear */
  18409. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18410. /** mag = linear and min = linear and mip = none */
  18411. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18412. /** mag = linear and min = nearest and mip = none */
  18413. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18414. /** Explicit coordinates mode */
  18415. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18416. /** Spherical coordinates mode */
  18417. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18418. /** Planar coordinates mode */
  18419. Engine.TEXTURE_PLANAR_MODE = 2;
  18420. /** Cubic coordinates mode */
  18421. Engine.TEXTURE_CUBIC_MODE = 3;
  18422. /** Projection coordinates mode */
  18423. Engine.TEXTURE_PROJECTION_MODE = 4;
  18424. /** Skybox coordinates mode */
  18425. Engine.TEXTURE_SKYBOX_MODE = 5;
  18426. /** Inverse Cubic coordinates mode */
  18427. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18428. /** Equirectangular coordinates mode */
  18429. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18430. /** Equirectangular Fixed coordinates mode */
  18431. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18432. /** Equirectangular Fixed Mirrored coordinates mode */
  18433. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18434. // Texture rescaling mode
  18435. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18436. Engine.SCALEMODE_FLOOR = 1;
  18437. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18438. Engine.SCALEMODE_NEAREST = 2;
  18439. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18440. Engine.SCALEMODE_CEILING = 3;
  18441. // Updatable statics so stick with vars here
  18442. /**
  18443. * Gets or sets the epsilon value used by collision engine
  18444. */
  18445. Engine.CollisionsEpsilon = 0.001;
  18446. /**
  18447. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18448. */
  18449. Engine.CodeRepository = "src/";
  18450. /**
  18451. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18452. */
  18453. Engine.ShadersRepository = "src/Shaders/";
  18454. return Engine;
  18455. }());
  18456. BABYLON.Engine = Engine;
  18457. })(BABYLON || (BABYLON = {}));
  18458. //# sourceMappingURL=babylon.engine.js.map
  18459. var BABYLON;
  18460. (function (BABYLON) {
  18461. /**
  18462. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18463. */
  18464. var Node = /** @class */ (function () {
  18465. /**
  18466. * Creates a new Node
  18467. * @param name the name and id to be given to this node
  18468. * @param scene the scene this node will be added to
  18469. */
  18470. function Node(name, scene) {
  18471. if (scene === void 0) { scene = null; }
  18472. /**
  18473. * Gets or sets a string used to store user defined state for the node
  18474. */
  18475. this.state = "";
  18476. /**
  18477. * Gets or sets an object used to store user defined information for the node
  18478. */
  18479. this.metadata = null;
  18480. /**
  18481. * Gets or sets a boolean used to define if the node must be serialized
  18482. */
  18483. this.doNotSerialize = false;
  18484. /** @hidden */
  18485. this._isDisposed = false;
  18486. /**
  18487. * Gets a list of Animations associated with the node
  18488. */
  18489. this.animations = new Array();
  18490. this._ranges = {};
  18491. this._isEnabled = true;
  18492. this._isParentEnabled = true;
  18493. this._isReady = true;
  18494. /** @hidden */
  18495. this._currentRenderId = -1;
  18496. this._parentRenderId = -1;
  18497. this._childRenderId = -1;
  18498. /** @hidden */
  18499. this._worldMatrix = BABYLON.Matrix.Identity();
  18500. /** @hidden */
  18501. this._worldMatrixDeterminant = 0;
  18502. /** @hidden */
  18503. this._sceneRootNodesIndex = -1;
  18504. this._animationPropertiesOverride = null;
  18505. /**
  18506. * An event triggered when the mesh is disposed
  18507. */
  18508. this.onDisposeObservable = new BABYLON.Observable();
  18509. // Behaviors
  18510. this._behaviors = new Array();
  18511. this.name = name;
  18512. this.id = name;
  18513. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18514. this.uniqueId = this._scene.getUniqueId();
  18515. this._initCache();
  18516. this.addToSceneRootNodes();
  18517. }
  18518. /**
  18519. * Add a new node constructor
  18520. * @param type defines the type name of the node to construct
  18521. * @param constructorFunc defines the constructor function
  18522. */
  18523. Node.AddNodeConstructor = function (type, constructorFunc) {
  18524. this._NodeConstructors[type] = constructorFunc;
  18525. };
  18526. /**
  18527. * Returns a node constructor based on type name
  18528. * @param type defines the type name
  18529. * @param name defines the new node name
  18530. * @param scene defines the hosting scene
  18531. * @param options defines optional options to transmit to constructors
  18532. * @returns the new constructor or null
  18533. */
  18534. Node.Construct = function (type, name, scene, options) {
  18535. var constructorFunc = this._NodeConstructors[type];
  18536. if (!constructorFunc) {
  18537. return null;
  18538. }
  18539. return constructorFunc(name, scene, options);
  18540. };
  18541. /**
  18542. * Gets a boolean indicating if the node has been disposed
  18543. * @returns true if the node was disposed
  18544. */
  18545. Node.prototype.isDisposed = function () {
  18546. return this._isDisposed;
  18547. };
  18548. Object.defineProperty(Node.prototype, "parent", {
  18549. get: function () {
  18550. return this._parentNode;
  18551. },
  18552. /**
  18553. * Gets or sets the parent of the node
  18554. */
  18555. set: function (parent) {
  18556. if (this._parentNode === parent) {
  18557. return;
  18558. }
  18559. var previousParentNode = this._parentNode;
  18560. // Remove self from list of children of parent
  18561. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18562. var index = this._parentNode._children.indexOf(this);
  18563. if (index !== -1) {
  18564. this._parentNode._children.splice(index, 1);
  18565. }
  18566. if (!parent) {
  18567. this.addToSceneRootNodes();
  18568. }
  18569. }
  18570. // Store new parent
  18571. this._parentNode = parent;
  18572. // Add as child to new parent
  18573. if (this._parentNode) {
  18574. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18575. this._parentNode._children = new Array();
  18576. }
  18577. this._parentNode._children.push(this);
  18578. if (!previousParentNode) {
  18579. this.removeFromSceneRootNodes();
  18580. }
  18581. }
  18582. // Enabled state
  18583. this._syncParentEnabledState();
  18584. },
  18585. enumerable: true,
  18586. configurable: true
  18587. });
  18588. Node.prototype.addToSceneRootNodes = function () {
  18589. if (this._sceneRootNodesIndex === -1) {
  18590. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18591. this._scene.rootNodes.push(this);
  18592. }
  18593. };
  18594. Node.prototype.removeFromSceneRootNodes = function () {
  18595. if (this._sceneRootNodesIndex !== -1) {
  18596. var rootNodes = this._scene.rootNodes;
  18597. var lastIdx = rootNodes.length - 1;
  18598. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18599. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18600. this._scene.rootNodes.pop();
  18601. this._sceneRootNodesIndex = -1;
  18602. }
  18603. };
  18604. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18605. /**
  18606. * Gets or sets the animation properties override
  18607. */
  18608. get: function () {
  18609. if (!this._animationPropertiesOverride) {
  18610. return this._scene.animationPropertiesOverride;
  18611. }
  18612. return this._animationPropertiesOverride;
  18613. },
  18614. set: function (value) {
  18615. this._animationPropertiesOverride = value;
  18616. },
  18617. enumerable: true,
  18618. configurable: true
  18619. });
  18620. /**
  18621. * Gets a string idenfifying the name of the class
  18622. * @returns "Node" string
  18623. */
  18624. Node.prototype.getClassName = function () {
  18625. return "Node";
  18626. };
  18627. Object.defineProperty(Node.prototype, "onDispose", {
  18628. /**
  18629. * Sets a callback that will be raised when the node will be disposed
  18630. */
  18631. set: function (callback) {
  18632. if (this._onDisposeObserver) {
  18633. this.onDisposeObservable.remove(this._onDisposeObserver);
  18634. }
  18635. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18636. },
  18637. enumerable: true,
  18638. configurable: true
  18639. });
  18640. /**
  18641. * Gets the scene of the node
  18642. * @returns a scene
  18643. */
  18644. Node.prototype.getScene = function () {
  18645. return this._scene;
  18646. };
  18647. /**
  18648. * Gets the engine of the node
  18649. * @returns a Engine
  18650. */
  18651. Node.prototype.getEngine = function () {
  18652. return this._scene.getEngine();
  18653. };
  18654. /**
  18655. * Attach a behavior to the node
  18656. * @see http://doc.babylonjs.com/features/behaviour
  18657. * @param behavior defines the behavior to attach
  18658. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18659. * @returns the current Node
  18660. */
  18661. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18662. var _this = this;
  18663. if (attachImmediately === void 0) { attachImmediately = false; }
  18664. var index = this._behaviors.indexOf(behavior);
  18665. if (index !== -1) {
  18666. return this;
  18667. }
  18668. behavior.init();
  18669. if (this._scene.isLoading && !attachImmediately) {
  18670. // We defer the attach when the scene will be loaded
  18671. this._scene.onDataLoadedObservable.addOnce(function () {
  18672. behavior.attach(_this);
  18673. });
  18674. }
  18675. else {
  18676. behavior.attach(this);
  18677. }
  18678. this._behaviors.push(behavior);
  18679. return this;
  18680. };
  18681. /**
  18682. * Remove an attached behavior
  18683. * @see http://doc.babylonjs.com/features/behaviour
  18684. * @param behavior defines the behavior to attach
  18685. * @returns the current Node
  18686. */
  18687. Node.prototype.removeBehavior = function (behavior) {
  18688. var index = this._behaviors.indexOf(behavior);
  18689. if (index === -1) {
  18690. return this;
  18691. }
  18692. this._behaviors[index].detach();
  18693. this._behaviors.splice(index, 1);
  18694. return this;
  18695. };
  18696. Object.defineProperty(Node.prototype, "behaviors", {
  18697. /**
  18698. * Gets the list of attached behaviors
  18699. * @see http://doc.babylonjs.com/features/behaviour
  18700. */
  18701. get: function () {
  18702. return this._behaviors;
  18703. },
  18704. enumerable: true,
  18705. configurable: true
  18706. });
  18707. /**
  18708. * Gets an attached behavior by name
  18709. * @param name defines the name of the behavior to look for
  18710. * @see http://doc.babylonjs.com/features/behaviour
  18711. * @returns null if behavior was not found else the requested behavior
  18712. */
  18713. Node.prototype.getBehaviorByName = function (name) {
  18714. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18715. var behavior = _a[_i];
  18716. if (behavior.name === name) {
  18717. return behavior;
  18718. }
  18719. }
  18720. return null;
  18721. };
  18722. /**
  18723. * Returns the latest update of the World matrix
  18724. * @returns a Matrix
  18725. */
  18726. Node.prototype.getWorldMatrix = function () {
  18727. if (this._currentRenderId !== this._scene.getRenderId()) {
  18728. this.computeWorldMatrix();
  18729. }
  18730. return this._worldMatrix;
  18731. };
  18732. /** @hidden */
  18733. Node.prototype._getWorldMatrixDeterminant = function () {
  18734. return this._worldMatrixDeterminant;
  18735. };
  18736. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18737. /**
  18738. * Returns directly the latest state of the mesh World matrix.
  18739. * A Matrix is returned.
  18740. */
  18741. get: function () {
  18742. return this._worldMatrix;
  18743. },
  18744. enumerable: true,
  18745. configurable: true
  18746. });
  18747. // override it in derived class if you add new variables to the cache
  18748. // and call the parent class method
  18749. /** @hidden */
  18750. Node.prototype._initCache = function () {
  18751. this._cache = {};
  18752. this._cache.parent = undefined;
  18753. };
  18754. /** @hidden */
  18755. Node.prototype.updateCache = function (force) {
  18756. if (!force && this.isSynchronized()) {
  18757. return;
  18758. }
  18759. this._cache.parent = this.parent;
  18760. this._updateCache();
  18761. };
  18762. // override it in derived class if you add new variables to the cache
  18763. // and call the parent class method if !ignoreParentClass
  18764. /** @hidden */
  18765. Node.prototype._updateCache = function (ignoreParentClass) {
  18766. };
  18767. // override it in derived class if you add new variables to the cache
  18768. /** @hidden */
  18769. Node.prototype._isSynchronized = function () {
  18770. return true;
  18771. };
  18772. /** @hidden */
  18773. Node.prototype._markSyncedWithParent = function () {
  18774. if (this._parentNode) {
  18775. this._parentRenderId = this._parentNode._childRenderId;
  18776. }
  18777. };
  18778. /** @hidden */
  18779. Node.prototype.isSynchronizedWithParent = function () {
  18780. if (!this._parentNode) {
  18781. return true;
  18782. }
  18783. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18784. return false;
  18785. }
  18786. return this._parentNode.isSynchronized();
  18787. };
  18788. /** @hidden */
  18789. Node.prototype.isSynchronized = function () {
  18790. if (this._cache.parent != this._parentNode) {
  18791. this._cache.parent = this._parentNode;
  18792. return false;
  18793. }
  18794. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18795. return false;
  18796. }
  18797. return this._isSynchronized();
  18798. };
  18799. /**
  18800. * Is this node ready to be used/rendered
  18801. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18802. * @return true if the node is ready
  18803. */
  18804. Node.prototype.isReady = function (completeCheck) {
  18805. if (completeCheck === void 0) { completeCheck = false; }
  18806. return this._isReady;
  18807. };
  18808. /**
  18809. * Is this node enabled?
  18810. * 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
  18811. * @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
  18812. * @return whether this node (and its parent) is enabled
  18813. */
  18814. Node.prototype.isEnabled = function (checkAncestors) {
  18815. if (checkAncestors === void 0) { checkAncestors = true; }
  18816. if (checkAncestors === false) {
  18817. return this._isEnabled;
  18818. }
  18819. if (!this._isEnabled) {
  18820. return false;
  18821. }
  18822. return this._isParentEnabled;
  18823. };
  18824. /** @hidden */
  18825. Node.prototype._syncParentEnabledState = function () {
  18826. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18827. if (this._children) {
  18828. this._children.forEach(function (c) {
  18829. c._syncParentEnabledState(); // Force children to update accordingly
  18830. });
  18831. }
  18832. };
  18833. /**
  18834. * Set the enabled state of this node
  18835. * @param value defines the new enabled state
  18836. */
  18837. Node.prototype.setEnabled = function (value) {
  18838. this._isEnabled = value;
  18839. this._syncParentEnabledState();
  18840. };
  18841. /**
  18842. * Is this node a descendant of the given node?
  18843. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18844. * @param ancestor defines the parent node to inspect
  18845. * @returns a boolean indicating if this node is a descendant of the given node
  18846. */
  18847. Node.prototype.isDescendantOf = function (ancestor) {
  18848. if (this.parent) {
  18849. if (this.parent === ancestor) {
  18850. return true;
  18851. }
  18852. return this.parent.isDescendantOf(ancestor);
  18853. }
  18854. return false;
  18855. };
  18856. /** @hidden */
  18857. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18858. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18859. if (!this._children) {
  18860. return;
  18861. }
  18862. for (var index = 0; index < this._children.length; index++) {
  18863. var item = this._children[index];
  18864. if (!predicate || predicate(item)) {
  18865. results.push(item);
  18866. }
  18867. if (!directDescendantsOnly) {
  18868. item._getDescendants(results, false, predicate);
  18869. }
  18870. }
  18871. };
  18872. /**
  18873. * Will return all nodes that have this node as ascendant
  18874. * @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
  18875. * @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
  18876. * @return all children nodes of all types
  18877. */
  18878. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18879. var results = new Array();
  18880. this._getDescendants(results, directDescendantsOnly, predicate);
  18881. return results;
  18882. };
  18883. /**
  18884. * Get all child-meshes of this node
  18885. * @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
  18886. * @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
  18887. * @returns an array of AbstractMesh
  18888. */
  18889. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18890. var results = [];
  18891. this._getDescendants(results, directDescendantsOnly, function (node) {
  18892. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18893. });
  18894. return results;
  18895. };
  18896. /**
  18897. * Get all child-transformNodes of this node
  18898. * @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
  18899. * @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
  18900. * @returns an array of TransformNode
  18901. */
  18902. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18903. var results = [];
  18904. this._getDescendants(results, directDescendantsOnly, function (node) {
  18905. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18906. });
  18907. return results;
  18908. };
  18909. /**
  18910. * Get all direct children of this node
  18911. * @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
  18912. * @returns an array of Node
  18913. */
  18914. Node.prototype.getChildren = function (predicate) {
  18915. return this.getDescendants(true, predicate);
  18916. };
  18917. /** @hidden */
  18918. Node.prototype._setReady = function (state) {
  18919. if (state === this._isReady) {
  18920. return;
  18921. }
  18922. if (!state) {
  18923. this._isReady = false;
  18924. return;
  18925. }
  18926. if (this.onReady) {
  18927. this.onReady(this);
  18928. }
  18929. this._isReady = true;
  18930. };
  18931. /**
  18932. * Get an animation by name
  18933. * @param name defines the name of the animation to look for
  18934. * @returns null if not found else the requested animation
  18935. */
  18936. Node.prototype.getAnimationByName = function (name) {
  18937. for (var i = 0; i < this.animations.length; i++) {
  18938. var animation = this.animations[i];
  18939. if (animation.name === name) {
  18940. return animation;
  18941. }
  18942. }
  18943. return null;
  18944. };
  18945. /**
  18946. * Creates an animation range for this node
  18947. * @param name defines the name of the range
  18948. * @param from defines the starting key
  18949. * @param to defines the end key
  18950. */
  18951. Node.prototype.createAnimationRange = function (name, from, to) {
  18952. // check name not already in use
  18953. if (!this._ranges[name]) {
  18954. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18955. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18956. if (this.animations[i]) {
  18957. this.animations[i].createRange(name, from, to);
  18958. }
  18959. }
  18960. }
  18961. };
  18962. /**
  18963. * Delete a specific animation range
  18964. * @param name defines the name of the range to delete
  18965. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18966. */
  18967. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18968. if (deleteFrames === void 0) { deleteFrames = true; }
  18969. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18970. if (this.animations[i]) {
  18971. this.animations[i].deleteRange(name, deleteFrames);
  18972. }
  18973. }
  18974. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18975. };
  18976. /**
  18977. * Get an animation range by name
  18978. * @param name defines the name of the animation range to look for
  18979. * @returns null if not found else the requested animation range
  18980. */
  18981. Node.prototype.getAnimationRange = function (name) {
  18982. return this._ranges[name];
  18983. };
  18984. /**
  18985. * Will start the animation sequence
  18986. * @param name defines the range frames for animation sequence
  18987. * @param loop defines if the animation should loop (false by default)
  18988. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18989. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18990. * @returns the object created for this animation. If range does not exist, it will return null
  18991. */
  18992. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18993. var range = this.getAnimationRange(name);
  18994. if (!range) {
  18995. return null;
  18996. }
  18997. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18998. };
  18999. /**
  19000. * Serialize animation ranges into a JSON compatible object
  19001. * @returns serialization object
  19002. */
  19003. Node.prototype.serializeAnimationRanges = function () {
  19004. var serializationRanges = [];
  19005. for (var name in this._ranges) {
  19006. var localRange = this._ranges[name];
  19007. if (!localRange) {
  19008. continue;
  19009. }
  19010. var range = {};
  19011. range.name = name;
  19012. range.from = localRange.from;
  19013. range.to = localRange.to;
  19014. serializationRanges.push(range);
  19015. }
  19016. return serializationRanges;
  19017. };
  19018. /**
  19019. * Computes the world matrix of the node
  19020. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19021. * @returns the world matrix
  19022. */
  19023. Node.prototype.computeWorldMatrix = function (force) {
  19024. if (!this._worldMatrix) {
  19025. this._worldMatrix = BABYLON.Matrix.Identity();
  19026. }
  19027. return this._worldMatrix;
  19028. };
  19029. /**
  19030. * Releases resources associated with this node.
  19031. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19032. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19033. */
  19034. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19035. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19036. if (!doNotRecurse) {
  19037. var nodes = this.getDescendants(true);
  19038. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  19039. var node = nodes_1[_i];
  19040. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  19041. }
  19042. }
  19043. else {
  19044. var transformNodes = this.getChildTransformNodes(true);
  19045. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  19046. var transformNode = transformNodes_1[_a];
  19047. transformNode.parent = null;
  19048. transformNode.computeWorldMatrix(true);
  19049. }
  19050. }
  19051. if (!this.parent) {
  19052. this.removeFromSceneRootNodes();
  19053. }
  19054. else {
  19055. this.parent = null;
  19056. }
  19057. // Callback
  19058. this.onDisposeObservable.notifyObservers(this);
  19059. this.onDisposeObservable.clear();
  19060. // Behaviors
  19061. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  19062. var behavior = _c[_b];
  19063. behavior.detach();
  19064. }
  19065. this._behaviors = [];
  19066. this._isDisposed = true;
  19067. };
  19068. /**
  19069. * Parse animation range data from a serialization object and store them into a given node
  19070. * @param node defines where to store the animation ranges
  19071. * @param parsedNode defines the serialization object to read data from
  19072. * @param scene defines the hosting scene
  19073. */
  19074. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  19075. if (parsedNode.ranges) {
  19076. for (var index = 0; index < parsedNode.ranges.length; index++) {
  19077. var data = parsedNode.ranges[index];
  19078. node.createAnimationRange(data.name, data.from, data.to);
  19079. }
  19080. }
  19081. };
  19082. Node._NodeConstructors = {};
  19083. __decorate([
  19084. BABYLON.serialize()
  19085. ], Node.prototype, "name", void 0);
  19086. __decorate([
  19087. BABYLON.serialize()
  19088. ], Node.prototype, "id", void 0);
  19089. __decorate([
  19090. BABYLON.serialize()
  19091. ], Node.prototype, "uniqueId", void 0);
  19092. __decorate([
  19093. BABYLON.serialize()
  19094. ], Node.prototype, "state", void 0);
  19095. __decorate([
  19096. BABYLON.serialize()
  19097. ], Node.prototype, "metadata", void 0);
  19098. return Node;
  19099. }());
  19100. BABYLON.Node = Node;
  19101. })(BABYLON || (BABYLON = {}));
  19102. //# sourceMappingURL=babylon.node.js.map
  19103. var BABYLON;
  19104. (function (BABYLON) {
  19105. /**
  19106. * Class used to store bounding sphere information
  19107. */
  19108. var BoundingSphere = /** @class */ (function () {
  19109. /**
  19110. * Creates a new bounding sphere
  19111. * @param min defines the minimum vector (in local space)
  19112. * @param max defines the maximum vector (in local space)
  19113. * @param worldMatrix defines the new world matrix
  19114. */
  19115. function BoundingSphere(min, max, worldMatrix) {
  19116. /**
  19117. * Gets the center of the bounding sphere in local space
  19118. */
  19119. this.center = BABYLON.Vector3.Zero();
  19120. /**
  19121. * Gets the center of the bounding sphere in world space
  19122. */
  19123. this.centerWorld = BABYLON.Vector3.Zero();
  19124. /**
  19125. * Gets the minimum vector in local space
  19126. */
  19127. this.minimum = BABYLON.Vector3.Zero();
  19128. /**
  19129. * Gets the maximum vector in local space
  19130. */
  19131. this.maximum = BABYLON.Vector3.Zero();
  19132. this.reConstruct(min, max, worldMatrix);
  19133. }
  19134. /**
  19135. * Recreates the entire bounding sphere from scratch as if we call the constructor in place
  19136. * @param min defines the new minimum vector (in local space)
  19137. * @param max defines the new maximum vector (in local space)
  19138. * @param worldMatrix defines the new world matrix
  19139. */
  19140. BoundingSphere.prototype.reConstruct = function (min, max, worldMatrix) {
  19141. this.minimum.copyFrom(min);
  19142. this.maximum.copyFrom(max);
  19143. var distance = BABYLON.Vector3.Distance(min, max);
  19144. max.addToRef(min, this.center).scaleInPlace(0.5);
  19145. this.radius = distance * 0.5;
  19146. this._update(worldMatrix || BABYLON.Matrix.IdentityReadOnly);
  19147. };
  19148. /**
  19149. * Scale the current bounding sphere by applying a scale factor
  19150. * @param factor defines the scale factor to apply
  19151. * @returns the current bounding box
  19152. */
  19153. BoundingSphere.prototype.scale = function (factor) {
  19154. var newRadius = this.radius * factor;
  19155. var tmpVectors = BoundingSphere.TmpVector3;
  19156. var tempRadiusVector = tmpVectors[0].setAll(newRadius);
  19157. var min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]);
  19158. var max = this.center.addToRef(tempRadiusVector, tmpVectors[2]);
  19159. this.reConstruct(min, max, this._worldMatrix);
  19160. return this;
  19161. };
  19162. /**
  19163. * Gets the world matrix of the bounding box
  19164. * @returns a matrix
  19165. */
  19166. BoundingSphere.prototype.getWorldMatrix = function () {
  19167. return this._worldMatrix;
  19168. };
  19169. // Methods
  19170. /** @hidden */
  19171. BoundingSphere.prototype._update = function (worldMatrix) {
  19172. if (!worldMatrix.isIdentity()) {
  19173. BABYLON.Vector3.TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld);
  19174. var tempVector = BoundingSphere.TmpVector3[0];
  19175. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, worldMatrix, tempVector);
  19176. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  19177. }
  19178. else {
  19179. this.centerWorld.copyFrom(this.center);
  19180. this.radiusWorld = this.radius;
  19181. }
  19182. };
  19183. /**
  19184. * Tests if the bounding sphere is intersecting the frustum planes
  19185. * @param frustumPlanes defines the frustum planes to test
  19186. * @returns true if there is an intersection
  19187. */
  19188. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  19189. for (var i = 0; i < 6; i++) {
  19190. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld) {
  19191. return false;
  19192. }
  19193. }
  19194. return true;
  19195. };
  19196. /**
  19197. * Tests if a point is inside the bounding sphere
  19198. * @param point defines the point to test
  19199. * @returns true if the point is inside the bounding sphere
  19200. */
  19201. BoundingSphere.prototype.intersectsPoint = function (point) {
  19202. var squareDistance = BABYLON.Vector3.DistanceSquared(this.centerWorld, point);
  19203. if (this.radiusWorld * this.radiusWorld < squareDistance) {
  19204. return false;
  19205. }
  19206. return true;
  19207. };
  19208. // Statics
  19209. /**
  19210. * Checks if two sphere intersct
  19211. * @param sphere0 sphere 0
  19212. * @param sphere1 sphere 1
  19213. * @returns true if the speres intersect
  19214. */
  19215. BoundingSphere.Intersects = function (sphere0, sphere1) {
  19216. var squareDistance = BABYLON.Vector3.DistanceSquared(sphere0.centerWorld, sphere1.centerWorld);
  19217. var radiusSum = sphere0.radiusWorld + sphere1.radiusWorld;
  19218. if (radiusSum * radiusSum < squareDistance) {
  19219. return false;
  19220. }
  19221. return true;
  19222. };
  19223. BoundingSphere.TmpVector3 = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19224. return BoundingSphere;
  19225. }());
  19226. BABYLON.BoundingSphere = BoundingSphere;
  19227. })(BABYLON || (BABYLON = {}));
  19228. //# sourceMappingURL=babylon.boundingSphere.js.map
  19229. var BABYLON;
  19230. (function (BABYLON) {
  19231. /**
  19232. * Class used to store bounding box information
  19233. */
  19234. var BoundingBox = /** @class */ (function () {
  19235. /**
  19236. * Creates a new bounding box
  19237. * @param min defines the minimum vector (in local space)
  19238. * @param max defines the maximum vector (in local space)
  19239. * @param worldMatrix defines the new world matrix
  19240. */
  19241. function BoundingBox(min, max, worldMatrix) {
  19242. /**
  19243. * Gets the 8 vectors representing the bounding box in local space
  19244. */
  19245. this.vectors = BABYLON.Tools.BuildArray(8, BABYLON.Vector3.Zero);
  19246. /**
  19247. * Gets the center of the bounding box in local space
  19248. */
  19249. this.center = BABYLON.Vector3.Zero();
  19250. /**
  19251. * Gets the center of the bounding box in world space
  19252. */
  19253. this.centerWorld = BABYLON.Vector3.Zero();
  19254. /**
  19255. * Gets the extend size in local space
  19256. */
  19257. this.extendSize = BABYLON.Vector3.Zero();
  19258. /**
  19259. * Gets the extend size in world space
  19260. */
  19261. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19262. /**
  19263. * Gets the OBB (object bounding box) directions
  19264. */
  19265. this.directions = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19266. /**
  19267. * Gets the 8 vectors representing the bounding box in world space
  19268. */
  19269. this.vectorsWorld = BABYLON.Tools.BuildArray(8, BABYLON.Vector3.Zero);
  19270. /**
  19271. * Gets the minimum vector in world space
  19272. */
  19273. this.minimumWorld = BABYLON.Vector3.Zero();
  19274. /**
  19275. * Gets the maximum vector in world space
  19276. */
  19277. this.maximumWorld = BABYLON.Vector3.Zero();
  19278. /**
  19279. * Gets the minimum vector in local space
  19280. */
  19281. this.minimum = BABYLON.Vector3.Zero();
  19282. /**
  19283. * Gets the maximum vector in local space
  19284. */
  19285. this.maximum = BABYLON.Vector3.Zero();
  19286. this.reConstruct(min, max, worldMatrix);
  19287. }
  19288. // Methods
  19289. /**
  19290. * Recreates the entire bounding box from scratch as if we call the constructor in place
  19291. * @param min defines the new minimum vector (in local space)
  19292. * @param max defines the new maximum vector (in local space)
  19293. * @param worldMatrix defines the new world matrix
  19294. */
  19295. BoundingBox.prototype.reConstruct = function (min, max, worldMatrix) {
  19296. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19297. var vectors = this.vectors;
  19298. this.minimum.copyFromFloats(minX, minY, minZ);
  19299. this.maximum.copyFromFloats(maxX, maxY, maxZ);
  19300. vectors[0].copyFromFloats(minX, minY, minZ);
  19301. vectors[1].copyFromFloats(maxX, maxY, maxZ);
  19302. vectors[2].copyFromFloats(maxX, minY, minZ);
  19303. vectors[3].copyFromFloats(minX, maxY, minZ);
  19304. vectors[4].copyFromFloats(minX, minY, maxZ);
  19305. vectors[5].copyFromFloats(maxX, maxY, minZ);
  19306. vectors[6].copyFromFloats(minX, maxY, maxZ);
  19307. vectors[7].copyFromFloats(maxX, minY, maxZ);
  19308. // OBB
  19309. max.addToRef(min, this.center).scaleInPlace(0.5);
  19310. max.subtractToRef(min, this.extendSize).scaleInPlace(0.5);
  19311. this._update(worldMatrix || BABYLON.Matrix.IdentityReadOnly);
  19312. };
  19313. /**
  19314. * Scale the current bounding box by applying a scale factor
  19315. * @param factor defines the scale factor to apply
  19316. * @returns the current bounding box
  19317. */
  19318. BoundingBox.prototype.scale = function (factor) {
  19319. var tmpVectors = BoundingBox.TmpVector3;
  19320. var diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]);
  19321. var len = diff.length();
  19322. diff.normalizeFromLength(len);
  19323. var distance = len * factor;
  19324. var newRadius = diff.scaleInPlace(distance * 0.5);
  19325. var min = this.center.subtractToRef(newRadius, tmpVectors[1]);
  19326. var max = this.center.addToRef(newRadius, tmpVectors[2]);
  19327. this.reConstruct(min, max, this._worldMatrix);
  19328. return this;
  19329. };
  19330. /**
  19331. * Gets the world matrix of the bounding box
  19332. * @returns a matrix
  19333. */
  19334. BoundingBox.prototype.getWorldMatrix = function () {
  19335. return this._worldMatrix;
  19336. };
  19337. /** @hidden */
  19338. BoundingBox.prototype._update = function (world) {
  19339. var minWorld = this.minimumWorld;
  19340. var maxWorld = this.maximumWorld;
  19341. var directions = this.directions;
  19342. var vectorsWorld = this.vectorsWorld;
  19343. var vectors = this.vectors;
  19344. if (!world.isIdentity()) {
  19345. minWorld.setAll(Number.MAX_VALUE);
  19346. maxWorld.setAll(-Number.MAX_VALUE);
  19347. for (var index = 0; index < 8; ++index) {
  19348. var v = vectorsWorld[index];
  19349. BABYLON.Vector3.TransformCoordinatesToRef(vectors[index], world, v);
  19350. minWorld.minimizeInPlace(v);
  19351. maxWorld.maximizeInPlace(v);
  19352. }
  19353. // Extend
  19354. maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5);
  19355. maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5);
  19356. }
  19357. else {
  19358. minWorld.copyFrom(this.minimum);
  19359. maxWorld.copyFrom(this.maximum);
  19360. for (var index = 0; index < 8; ++index) {
  19361. vectorsWorld[index].copyFrom(vectors[index]);
  19362. }
  19363. // Extend
  19364. this.extendSizeWorld.copyFrom(this.extendSize);
  19365. this.centerWorld.copyFrom(this.center);
  19366. }
  19367. BABYLON.Vector3.FromArrayToRef(world.m, 0, directions[0]);
  19368. BABYLON.Vector3.FromArrayToRef(world.m, 4, directions[1]);
  19369. BABYLON.Vector3.FromArrayToRef(world.m, 8, directions[2]);
  19370. this._worldMatrix = world;
  19371. };
  19372. /**
  19373. * Tests if the bounding box is intersecting the frustum planes
  19374. * @param frustumPlanes defines the frustum planes to test
  19375. * @returns true if there is an intersection
  19376. */
  19377. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19378. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19379. };
  19380. /**
  19381. * Tests if the bounding box is entirely inside the frustum planes
  19382. * @param frustumPlanes defines the frustum planes to test
  19383. * @returns true if there is an inclusion
  19384. */
  19385. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19386. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19387. };
  19388. /**
  19389. * Tests if a point is inside the bounding box
  19390. * @param point defines the point to test
  19391. * @returns true if the point is inside the bounding box
  19392. */
  19393. BoundingBox.prototype.intersectsPoint = function (point) {
  19394. var min = this.minimumWorld;
  19395. var max = this.maximumWorld;
  19396. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19397. var pointX = point.x, pointY = point.y, pointZ = point.z;
  19398. var delta = -BABYLON.Epsilon;
  19399. if (maxX - pointX < delta || delta > pointX - minX) {
  19400. return false;
  19401. }
  19402. if (maxY - pointY < delta || delta > pointY - minY) {
  19403. return false;
  19404. }
  19405. if (maxZ - pointZ < delta || delta > pointZ - minZ) {
  19406. return false;
  19407. }
  19408. return true;
  19409. };
  19410. /**
  19411. * Tests if the bounding box intersects with a bounding sphere
  19412. * @param sphere defines the sphere to test
  19413. * @returns true if there is an intersection
  19414. */
  19415. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19416. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19417. };
  19418. /**
  19419. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19420. * @param min defines the min vector to use
  19421. * @param max defines the max vector to use
  19422. * @returns true if there is an intersection
  19423. */
  19424. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19425. var myMin = this.minimumWorld;
  19426. var myMax = this.maximumWorld;
  19427. var myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z;
  19428. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19429. if (myMaxX < minX || myMinX > maxX) {
  19430. return false;
  19431. }
  19432. if (myMaxY < minY || myMinY > maxY) {
  19433. return false;
  19434. }
  19435. if (myMaxZ < minZ || myMinZ > maxZ) {
  19436. return false;
  19437. }
  19438. return true;
  19439. };
  19440. // Statics
  19441. /**
  19442. * Tests if two bounding boxes are intersections
  19443. * @param box0 defines the first box to test
  19444. * @param box1 defines the second box to test
  19445. * @returns true if there is an intersection
  19446. */
  19447. BoundingBox.Intersects = function (box0, box1) {
  19448. return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld);
  19449. };
  19450. /**
  19451. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19452. * @param minPoint defines the minimum vector of the bounding box
  19453. * @param maxPoint defines the maximum vector of the bounding box
  19454. * @param sphereCenter defines the sphere center
  19455. * @param sphereRadius defines the sphere radius
  19456. * @returns true if there is an intersection
  19457. */
  19458. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19459. var vector = BoundingBox.TmpVector3[0];
  19460. BABYLON.Vector3.ClampToRef(sphereCenter, minPoint, maxPoint, vector);
  19461. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19462. return (num <= (sphereRadius * sphereRadius));
  19463. };
  19464. /**
  19465. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19466. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19467. * @param frustumPlanes defines the frustum planes to test
  19468. * @return true if there is an inclusion
  19469. */
  19470. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19471. for (var p = 0; p < 6; ++p) {
  19472. var frustumPlane = frustumPlanes[p];
  19473. for (var i = 0; i < 8; ++i) {
  19474. if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) {
  19475. return false;
  19476. }
  19477. }
  19478. }
  19479. return true;
  19480. };
  19481. /**
  19482. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19483. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19484. * @param frustumPlanes defines the frustum planes to test
  19485. * @return true if there is an intersection
  19486. */
  19487. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19488. for (var p = 0; p < 6; ++p) {
  19489. var canReturnFalse = true;
  19490. var frustumPlane = frustumPlanes[p];
  19491. for (var i = 0; i < 8; ++i) {
  19492. if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) {
  19493. canReturnFalse = false;
  19494. break;
  19495. }
  19496. }
  19497. if (canReturnFalse) {
  19498. return false;
  19499. }
  19500. }
  19501. return true;
  19502. };
  19503. BoundingBox.TmpVector3 = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19504. return BoundingBox;
  19505. }());
  19506. BABYLON.BoundingBox = BoundingBox;
  19507. })(BABYLON || (BABYLON = {}));
  19508. //# sourceMappingURL=babylon.boundingBox.js.map
  19509. var BABYLON;
  19510. (function (BABYLON) {
  19511. var _result0 = { min: 0, max: 0 };
  19512. var _result1 = { min: 0, max: 0 };
  19513. var computeBoxExtents = function (axis, box, result) {
  19514. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19515. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19516. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19517. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19518. var r = r0 + r1 + r2;
  19519. result.min = p - r;
  19520. result.max = p + r;
  19521. };
  19522. var axisOverlap = function (axis, box0, box1) {
  19523. computeBoxExtents(axis, box0, _result0);
  19524. computeBoxExtents(axis, box1, _result1);
  19525. return !(_result0.min > _result1.max || _result1.min > _result0.max);
  19526. };
  19527. /**
  19528. * Info for a bounding data of a mesh
  19529. */
  19530. var BoundingInfo = /** @class */ (function () {
  19531. /**
  19532. * Constructs bounding info
  19533. * @param minimum min vector of the bounding box/sphere
  19534. * @param maximum max vector of the bounding box/sphere
  19535. * @param worldMatrix defines the new world matrix
  19536. */
  19537. function BoundingInfo(minimum, maximum, worldMatrix) {
  19538. this._isLocked = false;
  19539. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum, worldMatrix);
  19540. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum, worldMatrix);
  19541. }
  19542. /**
  19543. * Recreates the entire bounding info from scratch as if we call the constructor in place
  19544. * @param min defines the new minimum vector (in local space)
  19545. * @param max defines the new maximum vector (in local space)
  19546. * @param worldMatrix defines the new world matrix
  19547. */
  19548. BoundingInfo.prototype.reConstruct = function (min, max, worldMatrix) {
  19549. this.boundingBox.reConstruct(min, max, worldMatrix);
  19550. this.boundingSphere.reConstruct(min, max, worldMatrix);
  19551. };
  19552. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19553. /**
  19554. * min vector of the bounding box/sphere
  19555. */
  19556. get: function () {
  19557. return this.boundingBox.minimum;
  19558. },
  19559. enumerable: true,
  19560. configurable: true
  19561. });
  19562. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19563. /**
  19564. * max vector of the bounding box/sphere
  19565. */
  19566. get: function () {
  19567. return this.boundingBox.maximum;
  19568. },
  19569. enumerable: true,
  19570. configurable: true
  19571. });
  19572. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19573. /**
  19574. * If the info is locked and won't be updated to avoid perf overhead
  19575. */
  19576. get: function () {
  19577. return this._isLocked;
  19578. },
  19579. set: function (value) {
  19580. this._isLocked = value;
  19581. },
  19582. enumerable: true,
  19583. configurable: true
  19584. });
  19585. // Methods
  19586. /**
  19587. * Updates the bounding sphere and box
  19588. * @param world world matrix to be used to update
  19589. */
  19590. BoundingInfo.prototype.update = function (world) {
  19591. if (this._isLocked) {
  19592. return;
  19593. }
  19594. this.boundingBox._update(world);
  19595. this.boundingSphere._update(world);
  19596. };
  19597. /**
  19598. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19599. * @param center New center of the bounding info
  19600. * @param extend New extend of the bounding info
  19601. * @returns the current bounding info
  19602. */
  19603. BoundingInfo.prototype.centerOn = function (center, extend) {
  19604. var minimum = BoundingInfo.TmpVector3[0].copyFrom(center).subtractInPlace(extend);
  19605. var maximum = BoundingInfo.TmpVector3[1].copyFrom(center).addInPlace(extend);
  19606. this.boundingBox.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
  19607. this.boundingSphere.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
  19608. return this;
  19609. };
  19610. /**
  19611. * Scale the current bounding info by applying a scale factor
  19612. * @param factor defines the scale factor to apply
  19613. * @returns the current bounding info
  19614. */
  19615. BoundingInfo.prototype.scale = function (factor) {
  19616. this.boundingBox.scale(factor);
  19617. this.boundingSphere.scale(factor);
  19618. return this;
  19619. };
  19620. /**
  19621. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19622. * @param frustumPlanes defines the frustum to test
  19623. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19624. * @returns true if the bounding info is in the frustum planes
  19625. */
  19626. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19627. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19628. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19629. return false;
  19630. }
  19631. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19632. return true;
  19633. }
  19634. return this.boundingBox.isInFrustum(frustumPlanes);
  19635. };
  19636. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19637. /**
  19638. * Gets the world distance between the min and max points of the bounding box
  19639. */
  19640. get: function () {
  19641. var boundingBox = this.boundingBox;
  19642. var diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, BoundingInfo.TmpVector3[0]);
  19643. return diag.length();
  19644. },
  19645. enumerable: true,
  19646. configurable: true
  19647. });
  19648. /**
  19649. * Checks if a cullable object (mesh...) is in the camera frustum
  19650. * Unlike isInFrustum this cheks the full bounding box
  19651. * @param frustumPlanes Camera near/planes
  19652. * @returns true if the object is in frustum otherwise false
  19653. */
  19654. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19655. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19656. };
  19657. /** @hidden */
  19658. BoundingInfo.prototype._checkCollision = function (collider) {
  19659. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19660. };
  19661. /**
  19662. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19663. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19664. * @param point the point to check intersection with
  19665. * @returns if the point intersects
  19666. */
  19667. BoundingInfo.prototype.intersectsPoint = function (point) {
  19668. if (!this.boundingSphere.centerWorld) {
  19669. return false;
  19670. }
  19671. if (!this.boundingSphere.intersectsPoint(point)) {
  19672. return false;
  19673. }
  19674. if (!this.boundingBox.intersectsPoint(point)) {
  19675. return false;
  19676. }
  19677. return true;
  19678. };
  19679. /**
  19680. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19681. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19682. * @param boundingInfo the bounding info to check intersection with
  19683. * @param precise if the intersection should be done using OBB
  19684. * @returns if the bounding info intersects
  19685. */
  19686. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19687. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19688. return false;
  19689. }
  19690. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19691. return false;
  19692. }
  19693. if (!precise) {
  19694. return true;
  19695. }
  19696. var box0 = this.boundingBox;
  19697. var box1 = boundingInfo.boundingBox;
  19698. if (!axisOverlap(box0.directions[0], box0, box1)) {
  19699. return false;
  19700. }
  19701. if (!axisOverlap(box0.directions[1], box0, box1)) {
  19702. return false;
  19703. }
  19704. if (!axisOverlap(box0.directions[2], box0, box1)) {
  19705. return false;
  19706. }
  19707. if (!axisOverlap(box1.directions[0], box0, box1)) {
  19708. return false;
  19709. }
  19710. if (!axisOverlap(box1.directions[1], box0, box1)) {
  19711. return false;
  19712. }
  19713. if (!axisOverlap(box1.directions[2], box0, box1)) {
  19714. return false;
  19715. }
  19716. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
  19717. return false;
  19718. }
  19719. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
  19720. return false;
  19721. }
  19722. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
  19723. return false;
  19724. }
  19725. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
  19726. return false;
  19727. }
  19728. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
  19729. return false;
  19730. }
  19731. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
  19732. return false;
  19733. }
  19734. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
  19735. return false;
  19736. }
  19737. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
  19738. return false;
  19739. }
  19740. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
  19741. return false;
  19742. }
  19743. return true;
  19744. };
  19745. BoundingInfo.TmpVector3 = BABYLON.Tools.BuildArray(2, BABYLON.Vector3.Zero);
  19746. return BoundingInfo;
  19747. }());
  19748. BABYLON.BoundingInfo = BoundingInfo;
  19749. })(BABYLON || (BABYLON = {}));
  19750. //# sourceMappingURL=babylon.boundingInfo.js.map
  19751. var BABYLON;
  19752. (function (BABYLON) {
  19753. /**
  19754. * 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.
  19755. * @see https://doc.babylonjs.com/how_to/transformnode
  19756. */
  19757. var TransformNode = /** @class */ (function (_super) {
  19758. __extends(TransformNode, _super);
  19759. function TransformNode(name, scene, isPure) {
  19760. if (scene === void 0) { scene = null; }
  19761. if (isPure === void 0) { isPure = true; }
  19762. var _this = _super.call(this, name, scene) || this;
  19763. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19764. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19765. _this._up = new BABYLON.Vector3(0, 1, 0);
  19766. _this._right = new BABYLON.Vector3(1, 0, 0);
  19767. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19768. // Properties
  19769. _this._position = BABYLON.Vector3.Zero();
  19770. _this._rotation = BABYLON.Vector3.Zero();
  19771. _this._scaling = BABYLON.Vector3.One();
  19772. _this._isDirty = false;
  19773. /**
  19774. * Set the billboard mode. Default is 0.
  19775. *
  19776. * | Value | Type | Description |
  19777. * | --- | --- | --- |
  19778. * | 0 | BILLBOARDMODE_NONE | |
  19779. * | 1 | BILLBOARDMODE_X | |
  19780. * | 2 | BILLBOARDMODE_Y | |
  19781. * | 4 | BILLBOARDMODE_Z | |
  19782. * | 7 | BILLBOARDMODE_ALL | |
  19783. *
  19784. */
  19785. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19786. /**
  19787. * 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
  19788. */
  19789. _this.scalingDeterminant = 1;
  19790. /**
  19791. * Sets the distance of the object to max, often used by skybox
  19792. */
  19793. _this.infiniteDistance = false;
  19794. /**
  19795. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19796. * By default the system will update normals to compensate
  19797. */
  19798. _this.ignoreNonUniformScaling = false;
  19799. _this._localWorld = BABYLON.Matrix.Zero();
  19800. _this._absolutePosition = BABYLON.Vector3.Zero();
  19801. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19802. _this._postMultiplyPivotMatrix = false;
  19803. _this._isWorldMatrixFrozen = false;
  19804. /** @hidden */
  19805. _this._indexInSceneTransformNodesArray = -1;
  19806. /**
  19807. * An event triggered after the world matrix is updated
  19808. */
  19809. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19810. _this._nonUniformScaling = false;
  19811. if (isPure) {
  19812. _this.getScene().addTransformNode(_this);
  19813. }
  19814. return _this;
  19815. }
  19816. /**
  19817. * Gets a string identifying the name of the class
  19818. * @returns "TransformNode" string
  19819. */
  19820. TransformNode.prototype.getClassName = function () {
  19821. return "TransformNode";
  19822. };
  19823. Object.defineProperty(TransformNode.prototype, "position", {
  19824. /**
  19825. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19826. */
  19827. get: function () {
  19828. return this._position;
  19829. },
  19830. set: function (newPosition) {
  19831. this._position = newPosition;
  19832. this._isDirty = true;
  19833. },
  19834. enumerable: true,
  19835. configurable: true
  19836. });
  19837. Object.defineProperty(TransformNode.prototype, "rotation", {
  19838. /**
  19839. * 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)).
  19840. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19841. */
  19842. get: function () {
  19843. return this._rotation;
  19844. },
  19845. set: function (newRotation) {
  19846. this._rotation = newRotation;
  19847. this._isDirty = true;
  19848. },
  19849. enumerable: true,
  19850. configurable: true
  19851. });
  19852. Object.defineProperty(TransformNode.prototype, "scaling", {
  19853. /**
  19854. * 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)).
  19855. */
  19856. get: function () {
  19857. return this._scaling;
  19858. },
  19859. set: function (newScaling) {
  19860. this._scaling = newScaling;
  19861. this._isDirty = true;
  19862. },
  19863. enumerable: true,
  19864. configurable: true
  19865. });
  19866. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19867. /**
  19868. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19869. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19870. */
  19871. get: function () {
  19872. return this._rotationQuaternion;
  19873. },
  19874. set: function (quaternion) {
  19875. this._rotationQuaternion = quaternion;
  19876. //reset the rotation vector.
  19877. if (quaternion) {
  19878. this.rotation.setAll(0.0);
  19879. }
  19880. },
  19881. enumerable: true,
  19882. configurable: true
  19883. });
  19884. Object.defineProperty(TransformNode.prototype, "forward", {
  19885. /**
  19886. * The forward direction of that transform in world space.
  19887. */
  19888. get: function () {
  19889. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19890. },
  19891. enumerable: true,
  19892. configurable: true
  19893. });
  19894. Object.defineProperty(TransformNode.prototype, "up", {
  19895. /**
  19896. * The up direction of that transform in world space.
  19897. */
  19898. get: function () {
  19899. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19900. },
  19901. enumerable: true,
  19902. configurable: true
  19903. });
  19904. Object.defineProperty(TransformNode.prototype, "right", {
  19905. /**
  19906. * The right direction of that transform in world space.
  19907. */
  19908. get: function () {
  19909. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. /**
  19915. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19916. * @param matrix the matrix to copy the pose from
  19917. * @returns this TransformNode.
  19918. */
  19919. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19920. this._poseMatrix.copyFrom(matrix);
  19921. return this;
  19922. };
  19923. /**
  19924. * Returns the mesh Pose matrix.
  19925. * @returns the pose matrix
  19926. */
  19927. TransformNode.prototype.getPoseMatrix = function () {
  19928. return this._poseMatrix;
  19929. };
  19930. /** @hidden */
  19931. TransformNode.prototype._isSynchronized = function () {
  19932. if (this._isDirty) {
  19933. return false;
  19934. }
  19935. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19936. return false;
  19937. }
  19938. if (this._cache.pivotMatrixUpdated) {
  19939. return false;
  19940. }
  19941. if (this.infiniteDistance) {
  19942. return false;
  19943. }
  19944. if (!this._cache.position.equals(this._position)) {
  19945. return false;
  19946. }
  19947. if (this._rotationQuaternion) {
  19948. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion)) {
  19949. return false;
  19950. }
  19951. }
  19952. if (!this._cache.rotation.equals(this._rotation)) {
  19953. return false;
  19954. }
  19955. if (!this._cache.scaling.equals(this._scaling)) {
  19956. return false;
  19957. }
  19958. return true;
  19959. };
  19960. /** @hidden */
  19961. TransformNode.prototype._initCache = function () {
  19962. _super.prototype._initCache.call(this);
  19963. this._cache.localMatrixUpdated = false;
  19964. this._cache.position = BABYLON.Vector3.Zero();
  19965. this._cache.scaling = BABYLON.Vector3.Zero();
  19966. this._cache.rotation = BABYLON.Vector3.Zero();
  19967. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19968. this._cache.billboardMode = -1;
  19969. };
  19970. /**
  19971. * Flag the transform node as dirty (Forcing it to update everything)
  19972. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  19973. * @returns this transform node
  19974. */
  19975. TransformNode.prototype.markAsDirty = function (property) {
  19976. if (property === "rotation") {
  19977. this.rotationQuaternion = null;
  19978. }
  19979. this._currentRenderId = Number.MAX_VALUE;
  19980. this._isDirty = true;
  19981. return this;
  19982. };
  19983. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19984. /**
  19985. * Returns the current mesh absolute position.
  19986. * Returns a Vector3.
  19987. */
  19988. get: function () {
  19989. return this._absolutePosition;
  19990. },
  19991. enumerable: true,
  19992. configurable: true
  19993. });
  19994. /**
  19995. * Sets a new matrix to apply before all other transformation
  19996. * @param matrix defines the transform matrix
  19997. * @returns the current TransformNode
  19998. */
  19999. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  20000. return this.setPivotMatrix(matrix, false);
  20001. };
  20002. /**
  20003. * Sets a new pivot matrix to the current node
  20004. * @param matrix defines the new pivot matrix to use
  20005. * @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
  20006. * @returns the current TransformNode
  20007. */
  20008. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  20009. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  20010. this._pivotMatrix.copyFrom(matrix);
  20011. this._cache.pivotMatrixUpdated = true;
  20012. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  20013. if (this._postMultiplyPivotMatrix) {
  20014. if (!this._pivotMatrixInverse) {
  20015. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  20016. }
  20017. else {
  20018. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  20019. }
  20020. }
  20021. return this;
  20022. };
  20023. /**
  20024. * Returns the mesh pivot matrix.
  20025. * Default : Identity.
  20026. * @returns the matrix
  20027. */
  20028. TransformNode.prototype.getPivotMatrix = function () {
  20029. return this._pivotMatrix;
  20030. };
  20031. /**
  20032. * Prevents the World matrix to be computed any longer.
  20033. * @returns the TransformNode.
  20034. */
  20035. TransformNode.prototype.freezeWorldMatrix = function () {
  20036. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  20037. this.computeWorldMatrix(true);
  20038. this._isWorldMatrixFrozen = true;
  20039. return this;
  20040. };
  20041. /**
  20042. * Allows back the World matrix computation.
  20043. * @returns the TransformNode.
  20044. */
  20045. TransformNode.prototype.unfreezeWorldMatrix = function () {
  20046. this._isWorldMatrixFrozen = false;
  20047. this.computeWorldMatrix(true);
  20048. return this;
  20049. };
  20050. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  20051. /**
  20052. * True if the World matrix has been frozen.
  20053. */
  20054. get: function () {
  20055. return this._isWorldMatrixFrozen;
  20056. },
  20057. enumerable: true,
  20058. configurable: true
  20059. });
  20060. /**
  20061. * Retuns the mesh absolute position in the World.
  20062. * @returns a Vector3.
  20063. */
  20064. TransformNode.prototype.getAbsolutePosition = function () {
  20065. this.computeWorldMatrix();
  20066. return this._absolutePosition;
  20067. };
  20068. /**
  20069. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  20070. * @param absolutePosition the absolute position to set
  20071. * @returns the TransformNode.
  20072. */
  20073. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  20074. if (!absolutePosition) {
  20075. return this;
  20076. }
  20077. var absolutePositionX;
  20078. var absolutePositionY;
  20079. var absolutePositionZ;
  20080. if (absolutePosition.x === undefined) {
  20081. if (arguments.length < 3) {
  20082. return this;
  20083. }
  20084. absolutePositionX = arguments[0];
  20085. absolutePositionY = arguments[1];
  20086. absolutePositionZ = arguments[2];
  20087. }
  20088. else {
  20089. absolutePositionX = absolutePosition.x;
  20090. absolutePositionY = absolutePosition.y;
  20091. absolutePositionZ = absolutePosition.z;
  20092. }
  20093. if (this.parent) {
  20094. var invertParentWorldMatrix = BABYLON.Tmp.Matrix[0];
  20095. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  20096. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position);
  20097. }
  20098. else {
  20099. this.position.x = absolutePositionX;
  20100. this.position.y = absolutePositionY;
  20101. this.position.z = absolutePositionZ;
  20102. }
  20103. return this;
  20104. };
  20105. /**
  20106. * Sets the mesh position in its local space.
  20107. * @param vector3 the position to set in localspace
  20108. * @returns the TransformNode.
  20109. */
  20110. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  20111. this.computeWorldMatrix();
  20112. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  20113. return this;
  20114. };
  20115. /**
  20116. * Returns the mesh position in the local space from the current World matrix values.
  20117. * @returns a new Vector3.
  20118. */
  20119. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  20120. this.computeWorldMatrix();
  20121. var invLocalWorldMatrix = BABYLON.Tmp.Matrix[0];
  20122. this._localWorld.invertToRef(invLocalWorldMatrix);
  20123. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  20124. };
  20125. /**
  20126. * Translates the mesh along the passed Vector3 in its local space.
  20127. * @param vector3 the distance to translate in localspace
  20128. * @returns the TransformNode.
  20129. */
  20130. TransformNode.prototype.locallyTranslate = function (vector3) {
  20131. this.computeWorldMatrix(true);
  20132. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  20133. return this;
  20134. };
  20135. /**
  20136. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  20137. * @param targetPoint the position (must be in same space as current mesh) to look at
  20138. * @param yawCor optional yaw (y-axis) correction in radians
  20139. * @param pitchCor optional pitch (x-axis) correction in radians
  20140. * @param rollCor optional roll (z-axis) correction in radians
  20141. * @param space the choosen space of the target
  20142. * @returns the TransformNode.
  20143. */
  20144. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  20145. if (yawCor === void 0) { yawCor = 0; }
  20146. if (pitchCor === void 0) { pitchCor = 0; }
  20147. if (rollCor === void 0) { rollCor = 0; }
  20148. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20149. var dv = TransformNode._lookAtVectorCache;
  20150. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  20151. targetPoint.subtractToRef(pos, dv);
  20152. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  20153. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  20154. var pitch = Math.atan2(dv.y, len);
  20155. if (this.rotationQuaternion) {
  20156. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  20157. }
  20158. else {
  20159. this.rotation.x = pitch + pitchCor;
  20160. this.rotation.y = yaw + yawCor;
  20161. this.rotation.z = rollCor;
  20162. }
  20163. return this;
  20164. };
  20165. /**
  20166. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20167. * This Vector3 is expressed in the World space.
  20168. * @param localAxis axis to rotate
  20169. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20170. */
  20171. TransformNode.prototype.getDirection = function (localAxis) {
  20172. var result = BABYLON.Vector3.Zero();
  20173. this.getDirectionToRef(localAxis, result);
  20174. return result;
  20175. };
  20176. /**
  20177. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  20178. * localAxis is expressed in the mesh local space.
  20179. * result is computed in the Wordl space from the mesh World matrix.
  20180. * @param localAxis axis to rotate
  20181. * @param result the resulting transformnode
  20182. * @returns this TransformNode.
  20183. */
  20184. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  20185. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20186. return this;
  20187. };
  20188. /**
  20189. * Sets a new pivot point to the current node
  20190. * @param point defines the new pivot point to use
  20191. * @param space defines if the point is in world or local space (local by default)
  20192. * @returns the current TransformNode
  20193. */
  20194. TransformNode.prototype.setPivotPoint = function (point, space) {
  20195. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20196. if (this.getScene().getRenderId() == 0) {
  20197. this.computeWorldMatrix(true);
  20198. }
  20199. var wm = this.getWorldMatrix();
  20200. if (space == BABYLON.Space.WORLD) {
  20201. var tmat = BABYLON.Tmp.Matrix[0];
  20202. wm.invertToRef(tmat);
  20203. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  20204. }
  20205. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  20206. };
  20207. /**
  20208. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  20209. * @returns the pivot point
  20210. */
  20211. TransformNode.prototype.getPivotPoint = function () {
  20212. var point = BABYLON.Vector3.Zero();
  20213. this.getPivotPointToRef(point);
  20214. return point;
  20215. };
  20216. /**
  20217. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  20218. * @param result the vector3 to store the result
  20219. * @returns this TransformNode.
  20220. */
  20221. TransformNode.prototype.getPivotPointToRef = function (result) {
  20222. result.x = -this._pivotMatrix.m[12];
  20223. result.y = -this._pivotMatrix.m[13];
  20224. result.z = -this._pivotMatrix.m[14];
  20225. return this;
  20226. };
  20227. /**
  20228. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  20229. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  20230. */
  20231. TransformNode.prototype.getAbsolutePivotPoint = function () {
  20232. var point = BABYLON.Vector3.Zero();
  20233. this.getAbsolutePivotPointToRef(point);
  20234. return point;
  20235. };
  20236. /**
  20237. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  20238. * @param result vector3 to store the result
  20239. * @returns this TransformNode.
  20240. */
  20241. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  20242. result.x = this._pivotMatrix.m[12];
  20243. result.y = this._pivotMatrix.m[13];
  20244. result.z = this._pivotMatrix.m[14];
  20245. this.getPivotPointToRef(result);
  20246. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  20247. return this;
  20248. };
  20249. /**
  20250. * Defines the passed node as the parent of the current node.
  20251. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  20252. * @param node the node ot set as the parent
  20253. * @returns this TransformNode.
  20254. */
  20255. TransformNode.prototype.setParent = function (node) {
  20256. if (!node && !this.parent) {
  20257. return this;
  20258. }
  20259. var quatRotation = BABYLON.Tmp.Quaternion[0];
  20260. var position = BABYLON.Tmp.Vector3[0];
  20261. var scale = BABYLON.Tmp.Vector3[1];
  20262. if (!node) {
  20263. if (this.parent && this.parent.computeWorldMatrix) {
  20264. this.parent.computeWorldMatrix(true);
  20265. }
  20266. this.computeWorldMatrix(true);
  20267. this.getWorldMatrix().decompose(scale, quatRotation, position);
  20268. }
  20269. else {
  20270. var diffMatrix = BABYLON.Tmp.Matrix[0];
  20271. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  20272. this.computeWorldMatrix(true);
  20273. node.computeWorldMatrix(true);
  20274. node.getWorldMatrix().invertToRef(invParentMatrix);
  20275. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  20276. diffMatrix.decompose(scale, quatRotation, position);
  20277. }
  20278. if (this.rotationQuaternion) {
  20279. this.rotationQuaternion.copyFrom(quatRotation);
  20280. }
  20281. else {
  20282. quatRotation.toEulerAnglesToRef(this.rotation);
  20283. }
  20284. this.scaling.copyFrom(scale);
  20285. this.position.copyFrom(position);
  20286. this.parent = node;
  20287. return this;
  20288. };
  20289. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20290. /**
  20291. * True if the scaling property of this object is non uniform eg. (1,2,1)
  20292. */
  20293. get: function () {
  20294. return this._nonUniformScaling;
  20295. },
  20296. enumerable: true,
  20297. configurable: true
  20298. });
  20299. /** @hidden */
  20300. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20301. if (this._nonUniformScaling === value) {
  20302. return false;
  20303. }
  20304. this._nonUniformScaling = value;
  20305. return true;
  20306. };
  20307. /**
  20308. * Attach the current TransformNode to another TransformNode associated with a bone
  20309. * @param bone Bone affecting the TransformNode
  20310. * @param affectedTransformNode TransformNode associated with the bone
  20311. * @returns this object
  20312. */
  20313. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20314. this._transformToBoneReferal = affectedTransformNode;
  20315. this.parent = bone;
  20316. if (bone.getWorldMatrix().determinant() < 0) {
  20317. this.scalingDeterminant *= -1;
  20318. }
  20319. return this;
  20320. };
  20321. /**
  20322. * Detach the transform node if its associated with a bone
  20323. * @returns this object
  20324. */
  20325. TransformNode.prototype.detachFromBone = function () {
  20326. if (!this.parent) {
  20327. return this;
  20328. }
  20329. if (this.parent.getWorldMatrix().determinant() < 0) {
  20330. this.scalingDeterminant *= -1;
  20331. }
  20332. this._transformToBoneReferal = null;
  20333. this.parent = null;
  20334. return this;
  20335. };
  20336. /**
  20337. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20338. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20339. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20340. * The passed axis is also normalized.
  20341. * @param axis the axis to rotate around
  20342. * @param amount the amount to rotate in radians
  20343. * @param space Space to rotate in (Default: local)
  20344. * @returns the TransformNode.
  20345. */
  20346. TransformNode.prototype.rotate = function (axis, amount, space) {
  20347. axis.normalize();
  20348. if (!this.rotationQuaternion) {
  20349. this.rotationQuaternion = this.rotation.toQuaternion();
  20350. this.rotation.setAll(0);
  20351. }
  20352. var rotationQuaternion;
  20353. if (!space || space === BABYLON.Space.LOCAL) {
  20354. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20355. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20356. }
  20357. else {
  20358. if (this.parent) {
  20359. var invertParentWorldMatrix = BABYLON.Tmp.Matrix[0];
  20360. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  20361. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20362. }
  20363. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20364. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20365. }
  20366. return this;
  20367. };
  20368. /**
  20369. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20370. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20371. * The passed axis is also normalized. .
  20372. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20373. * @param point the point to rotate around
  20374. * @param axis the axis to rotate around
  20375. * @param amount the amount to rotate in radians
  20376. * @returns the TransformNode
  20377. */
  20378. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20379. axis.normalize();
  20380. if (!this.rotationQuaternion) {
  20381. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20382. this.rotation.setAll(0);
  20383. }
  20384. var tmpVector = BABYLON.Tmp.Vector3[0];
  20385. var finalScale = BABYLON.Tmp.Vector3[1];
  20386. var finalTranslation = BABYLON.Tmp.Vector3[2];
  20387. var finalRotation = BABYLON.Tmp.Quaternion[0];
  20388. var translationMatrix = BABYLON.Tmp.Matrix[0]; // T
  20389. var translationMatrixInv = BABYLON.Tmp.Matrix[1]; // T'
  20390. var rotationMatrix = BABYLON.Tmp.Matrix[2]; // R
  20391. var finalMatrix = BABYLON.Tmp.Matrix[3]; // T' x R x T
  20392. point.subtractToRef(this.position, tmpVector);
  20393. BABYLON.Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); // T
  20394. BABYLON.Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); // T'
  20395. BABYLON.Matrix.RotationAxisToRef(axis, amount, rotationMatrix); // R
  20396. translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R
  20397. finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x T
  20398. finalMatrix.decompose(finalScale, finalRotation, finalTranslation);
  20399. this.position.addInPlace(finalTranslation);
  20400. finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20401. return this;
  20402. };
  20403. /**
  20404. * Translates the mesh along the axis vector for the passed distance in the given space.
  20405. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20406. * @param axis the axis to translate in
  20407. * @param distance the distance to translate
  20408. * @param space Space to rotate in (Default: local)
  20409. * @returns the TransformNode.
  20410. */
  20411. TransformNode.prototype.translate = function (axis, distance, space) {
  20412. var displacementVector = axis.scale(distance);
  20413. if (!space || space === BABYLON.Space.LOCAL) {
  20414. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20415. this.setPositionWithLocalVector(tempV3);
  20416. }
  20417. else {
  20418. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20419. }
  20420. return this;
  20421. };
  20422. /**
  20423. * Adds a rotation step to the mesh current rotation.
  20424. * x, y, z are Euler angles expressed in radians.
  20425. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20426. * This means this rotation is made in the mesh local space only.
  20427. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20428. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20429. * ```javascript
  20430. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20431. * ```
  20432. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20433. * 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.
  20434. * @param x Rotation to add
  20435. * @param y Rotation to add
  20436. * @param z Rotation to add
  20437. * @returns the TransformNode.
  20438. */
  20439. TransformNode.prototype.addRotation = function (x, y, z) {
  20440. var rotationQuaternion;
  20441. if (this.rotationQuaternion) {
  20442. rotationQuaternion = this.rotationQuaternion;
  20443. }
  20444. else {
  20445. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20446. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20447. }
  20448. var accumulation = BABYLON.Tmp.Quaternion[0];
  20449. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20450. rotationQuaternion.multiplyInPlace(accumulation);
  20451. if (!this.rotationQuaternion) {
  20452. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20453. }
  20454. return this;
  20455. };
  20456. /**
  20457. * Computes the world matrix of the node
  20458. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20459. * @returns the world matrix
  20460. */
  20461. TransformNode.prototype.computeWorldMatrix = function (force) {
  20462. if (this._isWorldMatrixFrozen) {
  20463. return this._worldMatrix;
  20464. }
  20465. if (!force && this.isSynchronized()) {
  20466. this._currentRenderId = this.getScene().getRenderId();
  20467. return this._worldMatrix;
  20468. }
  20469. this._updateCache();
  20470. this._cache.position.copyFrom(this.position);
  20471. this._cache.scaling.copyFrom(this.scaling);
  20472. this._cache.pivotMatrixUpdated = false;
  20473. this._cache.billboardMode = this.billboardMode;
  20474. this._currentRenderId = this.getScene().getRenderId();
  20475. this._childRenderId = this.getScene().getRenderId();
  20476. this._isDirty = false;
  20477. // Scaling
  20478. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20479. // Rotation
  20480. //rotate, if quaternion is set and rotation was used
  20481. if (this.rotationQuaternion) {
  20482. var len = this.rotation.length();
  20483. if (len) {
  20484. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20485. this.rotation.copyFromFloats(0, 0, 0);
  20486. }
  20487. }
  20488. if (this.rotationQuaternion) {
  20489. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20490. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20491. }
  20492. else {
  20493. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20494. this._cache.rotation.copyFrom(this.rotation);
  20495. }
  20496. // Translation
  20497. var camera = this.getScene().activeCamera;
  20498. if (this.infiniteDistance && !this.parent && camera) {
  20499. var cameraWorldMatrix = camera.getWorldMatrix();
  20500. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20501. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20502. }
  20503. else {
  20504. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20505. }
  20506. // Composing transformations
  20507. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20508. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20509. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20510. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20511. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20512. // Need to decompose each rotation here
  20513. var currentPosition = BABYLON.Tmp.Vector3[3];
  20514. if (this.parent && this.parent.getWorldMatrix) {
  20515. if (this._transformToBoneReferal) {
  20516. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20517. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20518. }
  20519. else {
  20520. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20521. }
  20522. }
  20523. else {
  20524. currentPosition.copyFrom(this.position);
  20525. }
  20526. currentPosition.subtractInPlace(camera.globalPosition);
  20527. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20528. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20529. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20530. }
  20531. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20532. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20533. }
  20534. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20535. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20536. }
  20537. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20538. }
  20539. else {
  20540. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20541. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20542. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20543. }
  20544. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20545. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20546. }
  20547. // Post multiply inverse of pivotMatrix
  20548. if (this._postMultiplyPivotMatrix) {
  20549. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20550. }
  20551. // Local world
  20552. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20553. // Parent
  20554. if (this.parent && this.parent.getWorldMatrix) {
  20555. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20556. if (this._transformToBoneReferal) {
  20557. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20558. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20559. }
  20560. else {
  20561. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20562. }
  20563. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20564. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20565. this._worldMatrix.copyFrom(this._localWorld);
  20566. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20567. }
  20568. else {
  20569. if (this._transformToBoneReferal) {
  20570. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20571. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20572. }
  20573. else {
  20574. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20575. }
  20576. }
  20577. this._markSyncedWithParent();
  20578. }
  20579. else {
  20580. this._worldMatrix.copyFrom(this._localWorld);
  20581. }
  20582. // Normal matrix
  20583. if (!this.ignoreNonUniformScaling) {
  20584. if (this.scaling.isNonUniform) {
  20585. this._updateNonUniformScalingState(true);
  20586. }
  20587. else if (this.parent && this.parent._nonUniformScaling) {
  20588. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20589. }
  20590. else {
  20591. this._updateNonUniformScalingState(false);
  20592. }
  20593. }
  20594. else {
  20595. this._updateNonUniformScalingState(false);
  20596. }
  20597. this._afterComputeWorldMatrix();
  20598. // Absolute position
  20599. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20600. // Callbacks
  20601. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20602. if (!this._poseMatrix) {
  20603. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20604. }
  20605. // Cache the determinant
  20606. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20607. return this._worldMatrix;
  20608. };
  20609. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20610. };
  20611. /**
  20612. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20613. * @param func callback function to add
  20614. *
  20615. * @returns the TransformNode.
  20616. */
  20617. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20618. this.onAfterWorldMatrixUpdateObservable.add(func);
  20619. return this;
  20620. };
  20621. /**
  20622. * Removes a registered callback function.
  20623. * @param func callback function to remove
  20624. * @returns the TransformNode.
  20625. */
  20626. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20627. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20628. return this;
  20629. };
  20630. /**
  20631. * Clone the current transform node
  20632. * @param name Name of the new clone
  20633. * @param newParent New parent for the clone
  20634. * @param doNotCloneChildren Do not clone children hierarchy
  20635. * @returns the new transform node
  20636. */
  20637. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20638. var _this = this;
  20639. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20640. result.name = name;
  20641. result.id = name;
  20642. if (newParent) {
  20643. result.parent = newParent;
  20644. }
  20645. if (!doNotCloneChildren) {
  20646. // Children
  20647. var directDescendants = this.getDescendants(true);
  20648. for (var index = 0; index < directDescendants.length; index++) {
  20649. var child = directDescendants[index];
  20650. if (child.clone) {
  20651. child.clone(name + "." + child.name, result);
  20652. }
  20653. }
  20654. }
  20655. return result;
  20656. };
  20657. /**
  20658. * Serializes the objects information.
  20659. * @param currentSerializationObject defines the object to serialize in
  20660. * @returns the serialized object
  20661. */
  20662. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20663. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20664. serializationObject.type = this.getClassName();
  20665. // Parent
  20666. if (this.parent) {
  20667. serializationObject.parentId = this.parent.id;
  20668. }
  20669. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20670. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20671. }
  20672. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20673. serializationObject.isEnabled = this.isEnabled();
  20674. // Parent
  20675. if (this.parent) {
  20676. serializationObject.parentId = this.parent.id;
  20677. }
  20678. return serializationObject;
  20679. };
  20680. // Statics
  20681. /**
  20682. * Returns a new TransformNode object parsed from the source provided.
  20683. * @param parsedTransformNode is the source.
  20684. * @param scene the scne the object belongs to
  20685. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20686. * @returns a new TransformNode object parsed from the source provided.
  20687. */
  20688. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20689. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20690. if (BABYLON.Tags) {
  20691. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20692. }
  20693. if (parsedTransformNode.localMatrix) {
  20694. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20695. }
  20696. else if (parsedTransformNode.pivotMatrix) {
  20697. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20698. }
  20699. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20700. // Parent
  20701. if (parsedTransformNode.parentId) {
  20702. transformNode._waitingParentId = parsedTransformNode.parentId;
  20703. }
  20704. return transformNode;
  20705. };
  20706. /**
  20707. * Releases resources associated with this transform node.
  20708. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20709. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20710. */
  20711. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20712. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20713. // Animations
  20714. this.getScene().stopAnimation(this);
  20715. // Remove from scene
  20716. this.getScene().removeTransformNode(this);
  20717. this.onAfterWorldMatrixUpdateObservable.clear();
  20718. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20719. };
  20720. // Statics
  20721. /**
  20722. * Object will not rotate to face the camera
  20723. */
  20724. TransformNode.BILLBOARDMODE_NONE = 0;
  20725. /**
  20726. * Object will rotate to face the camera but only on the x axis
  20727. */
  20728. TransformNode.BILLBOARDMODE_X = 1;
  20729. /**
  20730. * Object will rotate to face the camera but only on the y axis
  20731. */
  20732. TransformNode.BILLBOARDMODE_Y = 2;
  20733. /**
  20734. * Object will rotate to face the camera but only on the z axis
  20735. */
  20736. TransformNode.BILLBOARDMODE_Z = 4;
  20737. /**
  20738. * Object will rotate to face the camera
  20739. */
  20740. TransformNode.BILLBOARDMODE_ALL = 7;
  20741. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20742. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20743. __decorate([
  20744. BABYLON.serializeAsVector3("position")
  20745. ], TransformNode.prototype, "_position", void 0);
  20746. __decorate([
  20747. BABYLON.serializeAsVector3("rotation")
  20748. ], TransformNode.prototype, "_rotation", void 0);
  20749. __decorate([
  20750. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20751. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20752. __decorate([
  20753. BABYLON.serializeAsVector3("scaling")
  20754. ], TransformNode.prototype, "_scaling", void 0);
  20755. __decorate([
  20756. BABYLON.serialize()
  20757. ], TransformNode.prototype, "billboardMode", void 0);
  20758. __decorate([
  20759. BABYLON.serialize()
  20760. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20761. __decorate([
  20762. BABYLON.serialize()
  20763. ], TransformNode.prototype, "infiniteDistance", void 0);
  20764. __decorate([
  20765. BABYLON.serialize()
  20766. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20767. return TransformNode;
  20768. }(BABYLON.Node));
  20769. BABYLON.TransformNode = TransformNode;
  20770. })(BABYLON || (BABYLON = {}));
  20771. //# sourceMappingURL=babylon.transformNode.js.map
  20772. var BABYLON;
  20773. (function (BABYLON) {
  20774. /** @hidden */
  20775. var _FacetDataStorage = /** @class */ (function () {
  20776. function _FacetDataStorage() {
  20777. this.facetNb = 0; // facet number
  20778. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20779. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20780. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20781. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20782. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20783. this.subDiv = {
  20784. max: 1,
  20785. X: 1,
  20786. Y: 1,
  20787. Z: 1
  20788. };
  20789. this.facetDepthSort = false; // is the facet depth sort to be computed
  20790. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20791. }
  20792. return _FacetDataStorage;
  20793. }());
  20794. /**
  20795. * Class used to store all common mesh properties
  20796. */
  20797. var AbstractMesh = /** @class */ (function (_super) {
  20798. __extends(AbstractMesh, _super);
  20799. // Constructor
  20800. /**
  20801. * Creates a new AbstractMesh
  20802. * @param name defines the name of the mesh
  20803. * @param scene defines the hosting scene
  20804. */
  20805. function AbstractMesh(name, scene) {
  20806. if (scene === void 0) { scene = null; }
  20807. var _this = _super.call(this, name, scene, false) || this;
  20808. _this._facetData = new _FacetDataStorage();
  20809. /** Gets ot sets the culling strategy to use to find visible meshes */
  20810. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20811. // Events
  20812. /**
  20813. * An event triggered when this mesh collides with another one
  20814. */
  20815. _this.onCollideObservable = new BABYLON.Observable();
  20816. /**
  20817. * An event triggered when the collision's position changes
  20818. */
  20819. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20820. /**
  20821. * An event triggered when material is changed
  20822. */
  20823. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20824. // Properties
  20825. /**
  20826. * Gets or sets the orientation for POV movement & rotation
  20827. */
  20828. _this.definedFacingForward = true;
  20829. _this._visibility = 1.0;
  20830. /** Gets or sets the alpha index used to sort transparent meshes
  20831. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20832. */
  20833. _this.alphaIndex = Number.MAX_VALUE;
  20834. /**
  20835. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20836. */
  20837. _this.isVisible = true;
  20838. /**
  20839. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20840. */
  20841. _this.isPickable = true;
  20842. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20843. _this.showSubMeshesBoundingBox = false;
  20844. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20845. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20846. */
  20847. _this.isBlocker = false;
  20848. /**
  20849. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20850. */
  20851. _this.enablePointerMoveEvents = false;
  20852. /**
  20853. * Specifies the rendering group id for this mesh (0 by default)
  20854. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20855. */
  20856. _this.renderingGroupId = 0;
  20857. _this._receiveShadows = false;
  20858. /** Defines color to use when rendering outline */
  20859. _this.outlineColor = BABYLON.Color3.Red();
  20860. /** Define width to use when rendering outline */
  20861. _this.outlineWidth = 0.02;
  20862. /** Defines color to use when rendering overlay */
  20863. _this.overlayColor = BABYLON.Color3.Red();
  20864. /** Defines alpha to use when rendering overlay */
  20865. _this.overlayAlpha = 0.5;
  20866. _this._hasVertexAlpha = false;
  20867. _this._useVertexColors = true;
  20868. _this._computeBonesUsingShaders = true;
  20869. _this._numBoneInfluencers = 4;
  20870. _this._applyFog = true;
  20871. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20872. _this.useOctreeForRenderingSelection = true;
  20873. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20874. _this.useOctreeForPicking = true;
  20875. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20876. _this.useOctreeForCollisions = true;
  20877. _this._layerMask = 0x0FFFFFFF;
  20878. /**
  20879. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20880. */
  20881. _this.alwaysSelectAsActiveMesh = false;
  20882. /**
  20883. * Gets or sets the current action manager
  20884. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20885. */
  20886. _this.actionManager = null;
  20887. // Collisions
  20888. _this._checkCollisions = false;
  20889. _this._collisionMask = -1;
  20890. _this._collisionGroup = -1;
  20891. /**
  20892. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20893. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20894. */
  20895. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20896. /**
  20897. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20898. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20899. */
  20900. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20901. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20902. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20903. // Edges
  20904. /**
  20905. * Defines edge width used when edgesRenderer is enabled
  20906. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20907. */
  20908. _this.edgesWidth = 1;
  20909. /**
  20910. * Defines edge color used when edgesRenderer is enabled
  20911. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20912. */
  20913. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20914. /** @hidden */
  20915. _this._renderId = 0;
  20916. /** @hidden */
  20917. _this._intersectionsInProgress = new Array();
  20918. /** @hidden */
  20919. _this._unIndexed = false;
  20920. /** @hidden */
  20921. _this._lightSources = new Array();
  20922. /**
  20923. * An event triggered when the mesh is rebuilt.
  20924. */
  20925. _this.onRebuildObservable = new BABYLON.Observable();
  20926. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20927. if (collidedMesh === void 0) { collidedMesh = null; }
  20928. //TODO move this to the collision coordinator!
  20929. if (_this.getScene().workerCollisions) {
  20930. newPosition.multiplyInPlace(_this._collider._radius);
  20931. }
  20932. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20933. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20934. _this.position.addInPlace(_this._diffPositionForCollisions);
  20935. }
  20936. if (collidedMesh) {
  20937. _this.onCollideObservable.notifyObservers(collidedMesh);
  20938. }
  20939. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20940. };
  20941. _this.getScene().addMesh(_this);
  20942. _this._resyncLightSources();
  20943. return _this;
  20944. }
  20945. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20946. /**
  20947. * No billboard
  20948. */
  20949. get: function () {
  20950. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20951. },
  20952. enumerable: true,
  20953. configurable: true
  20954. });
  20955. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20956. /** Billboard on X axis */
  20957. get: function () {
  20958. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20959. },
  20960. enumerable: true,
  20961. configurable: true
  20962. });
  20963. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20964. /** Billboard on Y axis */
  20965. get: function () {
  20966. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20967. },
  20968. enumerable: true,
  20969. configurable: true
  20970. });
  20971. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20972. /** Billboard on Z axis */
  20973. get: function () {
  20974. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20975. },
  20976. enumerable: true,
  20977. configurable: true
  20978. });
  20979. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20980. /** Billboard on all axes */
  20981. get: function () {
  20982. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20983. },
  20984. enumerable: true,
  20985. configurable: true
  20986. });
  20987. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20988. /**
  20989. * Gets the number of facets in the mesh
  20990. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20991. */
  20992. get: function () {
  20993. return this._facetData.facetNb;
  20994. },
  20995. enumerable: true,
  20996. configurable: true
  20997. });
  20998. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20999. /**
  21000. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  21001. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  21002. */
  21003. get: function () {
  21004. return this._facetData.partitioningSubdivisions;
  21005. },
  21006. set: function (nb) {
  21007. this._facetData.partitioningSubdivisions = nb;
  21008. },
  21009. enumerable: true,
  21010. configurable: true
  21011. });
  21012. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  21013. /**
  21014. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  21015. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  21016. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  21017. */
  21018. get: function () {
  21019. return this._facetData.partitioningBBoxRatio;
  21020. },
  21021. set: function (ratio) {
  21022. this._facetData.partitioningBBoxRatio = ratio;
  21023. },
  21024. enumerable: true,
  21025. configurable: true
  21026. });
  21027. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  21028. /**
  21029. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  21030. * Works only for updatable meshes.
  21031. * Doesn't work with multi-materials
  21032. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  21033. */
  21034. get: function () {
  21035. return this._facetData.facetDepthSort;
  21036. },
  21037. set: function (sort) {
  21038. this._facetData.facetDepthSort = sort;
  21039. },
  21040. enumerable: true,
  21041. configurable: true
  21042. });
  21043. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  21044. /**
  21045. * The location (Vector3) where the facet depth sort must be computed from.
  21046. * By default, the active camera position.
  21047. * Used only when facet depth sort is enabled
  21048. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  21049. */
  21050. get: function () {
  21051. return this._facetData.facetDepthSortFrom;
  21052. },
  21053. set: function (location) {
  21054. this._facetData.facetDepthSortFrom = location;
  21055. },
  21056. enumerable: true,
  21057. configurable: true
  21058. });
  21059. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  21060. /**
  21061. * gets a boolean indicating if facetData is enabled
  21062. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  21063. */
  21064. get: function () {
  21065. return this._facetData.facetDataEnabled;
  21066. },
  21067. enumerable: true,
  21068. configurable: true
  21069. });
  21070. /** @hidden */
  21071. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  21072. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  21073. return false;
  21074. }
  21075. this._markSubMeshesAsMiscDirty();
  21076. return true;
  21077. };
  21078. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  21079. /** Set a function to call when this mesh collides with another one */
  21080. set: function (callback) {
  21081. if (this._onCollideObserver) {
  21082. this.onCollideObservable.remove(this._onCollideObserver);
  21083. }
  21084. this._onCollideObserver = this.onCollideObservable.add(callback);
  21085. },
  21086. enumerable: true,
  21087. configurable: true
  21088. });
  21089. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  21090. /** Set a function to call when the collision's position changes */
  21091. set: function (callback) {
  21092. if (this._onCollisionPositionChangeObserver) {
  21093. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  21094. }
  21095. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  21096. },
  21097. enumerable: true,
  21098. configurable: true
  21099. });
  21100. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  21101. /**
  21102. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21103. */
  21104. get: function () {
  21105. return this._visibility;
  21106. },
  21107. /**
  21108. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21109. */
  21110. set: function (value) {
  21111. if (this._visibility === value) {
  21112. return;
  21113. }
  21114. this._visibility = value;
  21115. this._markSubMeshesAsMiscDirty();
  21116. },
  21117. enumerable: true,
  21118. configurable: true
  21119. });
  21120. Object.defineProperty(AbstractMesh.prototype, "material", {
  21121. /** Gets or sets current material */
  21122. get: function () {
  21123. return this._material;
  21124. },
  21125. set: function (value) {
  21126. if (this._material === value) {
  21127. return;
  21128. }
  21129. // remove from material mesh map id needed
  21130. if (this._material && this._material.meshMap) {
  21131. this._material.meshMap[this.uniqueId] = undefined;
  21132. }
  21133. this._material = value;
  21134. if (value && value.meshMap) {
  21135. value.meshMap[this.uniqueId] = this;
  21136. }
  21137. if (this.onMaterialChangedObservable.hasObservers) {
  21138. this.onMaterialChangedObservable.notifyObservers(this);
  21139. }
  21140. if (!this.subMeshes) {
  21141. return;
  21142. }
  21143. this._unBindEffect();
  21144. },
  21145. enumerable: true,
  21146. configurable: true
  21147. });
  21148. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  21149. /**
  21150. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  21151. * @see http://doc.babylonjs.com/babylon101/shadows
  21152. */
  21153. get: function () {
  21154. return this._receiveShadows;
  21155. },
  21156. set: function (value) {
  21157. if (this._receiveShadows === value) {
  21158. return;
  21159. }
  21160. this._receiveShadows = value;
  21161. this._markSubMeshesAsLightDirty();
  21162. },
  21163. enumerable: true,
  21164. configurable: true
  21165. });
  21166. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  21167. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  21168. get: function () {
  21169. return this._hasVertexAlpha;
  21170. },
  21171. set: function (value) {
  21172. if (this._hasVertexAlpha === value) {
  21173. return;
  21174. }
  21175. this._hasVertexAlpha = value;
  21176. this._markSubMeshesAsAttributesDirty();
  21177. this._markSubMeshesAsMiscDirty();
  21178. },
  21179. enumerable: true,
  21180. configurable: true
  21181. });
  21182. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  21183. /** 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) */
  21184. get: function () {
  21185. return this._useVertexColors;
  21186. },
  21187. set: function (value) {
  21188. if (this._useVertexColors === value) {
  21189. return;
  21190. }
  21191. this._useVertexColors = value;
  21192. this._markSubMeshesAsAttributesDirty();
  21193. },
  21194. enumerable: true,
  21195. configurable: true
  21196. });
  21197. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  21198. /**
  21199. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  21200. */
  21201. get: function () {
  21202. return this._computeBonesUsingShaders;
  21203. },
  21204. set: function (value) {
  21205. if (this._computeBonesUsingShaders === value) {
  21206. return;
  21207. }
  21208. this._computeBonesUsingShaders = value;
  21209. this._markSubMeshesAsAttributesDirty();
  21210. },
  21211. enumerable: true,
  21212. configurable: true
  21213. });
  21214. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  21215. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  21216. get: function () {
  21217. return this._numBoneInfluencers;
  21218. },
  21219. set: function (value) {
  21220. if (this._numBoneInfluencers === value) {
  21221. return;
  21222. }
  21223. this._numBoneInfluencers = value;
  21224. this._markSubMeshesAsAttributesDirty();
  21225. },
  21226. enumerable: true,
  21227. configurable: true
  21228. });
  21229. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  21230. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  21231. get: function () {
  21232. return this._applyFog;
  21233. },
  21234. set: function (value) {
  21235. if (this._applyFog === value) {
  21236. return;
  21237. }
  21238. this._applyFog = value;
  21239. this._markSubMeshesAsMiscDirty();
  21240. },
  21241. enumerable: true,
  21242. configurable: true
  21243. });
  21244. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  21245. /**
  21246. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  21247. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  21248. */
  21249. get: function () {
  21250. return this._layerMask;
  21251. },
  21252. set: function (value) {
  21253. if (value === this._layerMask) {
  21254. return;
  21255. }
  21256. this._layerMask = value;
  21257. this._resyncLightSources();
  21258. },
  21259. enumerable: true,
  21260. configurable: true
  21261. });
  21262. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  21263. /**
  21264. * Gets or sets a collision mask used to mask collisions (default is -1).
  21265. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21266. */
  21267. get: function () {
  21268. return this._collisionMask;
  21269. },
  21270. set: function (mask) {
  21271. this._collisionMask = !isNaN(mask) ? mask : -1;
  21272. },
  21273. enumerable: true,
  21274. configurable: true
  21275. });
  21276. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  21277. /**
  21278. * Gets or sets the current collision group mask (-1 by default).
  21279. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21280. */
  21281. get: function () {
  21282. return this._collisionGroup;
  21283. },
  21284. set: function (mask) {
  21285. this._collisionGroup = !isNaN(mask) ? mask : -1;
  21286. },
  21287. enumerable: true,
  21288. configurable: true
  21289. });
  21290. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  21291. /** @hidden */
  21292. get: function () {
  21293. return null;
  21294. },
  21295. enumerable: true,
  21296. configurable: true
  21297. });
  21298. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  21299. get: function () {
  21300. return this._skeleton;
  21301. },
  21302. /**
  21303. * Gets or sets a skeleton to apply skining transformations
  21304. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21305. */
  21306. set: function (value) {
  21307. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  21308. this._skeleton._unregisterMeshWithPoseMatrix(this);
  21309. }
  21310. if (value && value.needInitialSkinMatrix) {
  21311. value._registerMeshWithPoseMatrix(this);
  21312. }
  21313. this._skeleton = value;
  21314. if (!this._skeleton) {
  21315. this._bonesTransformMatrices = null;
  21316. }
  21317. this._markSubMeshesAsAttributesDirty();
  21318. },
  21319. enumerable: true,
  21320. configurable: true
  21321. });
  21322. /**
  21323. * Returns the string "AbstractMesh"
  21324. * @returns "AbstractMesh"
  21325. */
  21326. AbstractMesh.prototype.getClassName = function () {
  21327. return "AbstractMesh";
  21328. };
  21329. /**
  21330. * Gets a string representation of the current mesh
  21331. * @param fullDetails defines a boolean indicating if full details must be included
  21332. * @returns a string representation of the current mesh
  21333. */
  21334. AbstractMesh.prototype.toString = function (fullDetails) {
  21335. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  21336. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  21337. if (this._skeleton) {
  21338. ret += ", skeleton: " + this._skeleton.name;
  21339. }
  21340. if (fullDetails) {
  21341. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  21342. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  21343. }
  21344. return ret;
  21345. };
  21346. /** @hidden */
  21347. AbstractMesh.prototype._rebuild = function () {
  21348. this.onRebuildObservable.notifyObservers(this);
  21349. if (this._occlusionQuery) {
  21350. this._occlusionQuery = null;
  21351. }
  21352. if (!this.subMeshes) {
  21353. return;
  21354. }
  21355. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21356. var subMesh = _a[_i];
  21357. subMesh._rebuild();
  21358. }
  21359. };
  21360. /** @hidden */
  21361. AbstractMesh.prototype._resyncLightSources = function () {
  21362. this._lightSources.length = 0;
  21363. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21364. var light = _a[_i];
  21365. if (!light.isEnabled()) {
  21366. continue;
  21367. }
  21368. if (light.canAffectMesh(this)) {
  21369. this._lightSources.push(light);
  21370. }
  21371. }
  21372. this._markSubMeshesAsLightDirty();
  21373. };
  21374. /** @hidden */
  21375. AbstractMesh.prototype._resyncLighSource = function (light) {
  21376. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21377. var index = this._lightSources.indexOf(light);
  21378. if (index === -1) {
  21379. if (!isIn) {
  21380. return;
  21381. }
  21382. this._lightSources.push(light);
  21383. }
  21384. else {
  21385. if (isIn) {
  21386. return;
  21387. }
  21388. this._lightSources.splice(index, 1);
  21389. }
  21390. this._markSubMeshesAsLightDirty();
  21391. };
  21392. /** @hidden */
  21393. AbstractMesh.prototype._unBindEffect = function () {
  21394. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21395. var subMesh = _a[_i];
  21396. subMesh.setEffect(null);
  21397. }
  21398. };
  21399. /** @hidden */
  21400. AbstractMesh.prototype._removeLightSource = function (light) {
  21401. var index = this._lightSources.indexOf(light);
  21402. if (index === -1) {
  21403. return;
  21404. }
  21405. this._lightSources.splice(index, 1);
  21406. this._markSubMeshesAsLightDirty();
  21407. };
  21408. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21409. if (!this.subMeshes) {
  21410. return;
  21411. }
  21412. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21413. var subMesh = _a[_i];
  21414. if (subMesh._materialDefines) {
  21415. func(subMesh._materialDefines);
  21416. }
  21417. }
  21418. };
  21419. /** @hidden */
  21420. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21421. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21422. };
  21423. /** @hidden */
  21424. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21425. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21426. };
  21427. /** @hidden */
  21428. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21429. if (!this.subMeshes) {
  21430. return;
  21431. }
  21432. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21433. var subMesh = _a[_i];
  21434. var material = subMesh.getMaterial();
  21435. if (material) {
  21436. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21437. }
  21438. }
  21439. };
  21440. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21441. /**
  21442. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21443. */
  21444. get: function () {
  21445. return this._scaling;
  21446. },
  21447. set: function (newScaling) {
  21448. this._scaling = newScaling;
  21449. if (this.physicsImpostor) {
  21450. this.physicsImpostor.forceUpdate();
  21451. }
  21452. },
  21453. enumerable: true,
  21454. configurable: true
  21455. });
  21456. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21457. // Methods
  21458. /**
  21459. * Returns true if the mesh is blocked. Implemented by child classes
  21460. */
  21461. get: function () {
  21462. return false;
  21463. },
  21464. enumerable: true,
  21465. configurable: true
  21466. });
  21467. /**
  21468. * Returns the mesh itself by default. Implemented by child classes
  21469. * @param camera defines the camera to use to pick the right LOD level
  21470. * @returns the currentAbstractMesh
  21471. */
  21472. AbstractMesh.prototype.getLOD = function (camera) {
  21473. return this;
  21474. };
  21475. /**
  21476. * Returns 0 by default. Implemented by child classes
  21477. * @returns an integer
  21478. */
  21479. AbstractMesh.prototype.getTotalVertices = function () {
  21480. return 0;
  21481. };
  21482. /**
  21483. * Returns null by default. Implemented by child classes
  21484. * @returns null
  21485. */
  21486. AbstractMesh.prototype.getIndices = function () {
  21487. return null;
  21488. };
  21489. /**
  21490. * Returns the array of the requested vertex data kind. Implemented by child classes
  21491. * @param kind defines the vertex data kind to use
  21492. * @returns null
  21493. */
  21494. AbstractMesh.prototype.getVerticesData = function (kind) {
  21495. return null;
  21496. };
  21497. /**
  21498. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21499. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21500. * Note that a new underlying VertexBuffer object is created each call.
  21501. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21502. * @param kind defines vertex data kind:
  21503. * * BABYLON.VertexBuffer.PositionKind
  21504. * * BABYLON.VertexBuffer.UVKind
  21505. * * BABYLON.VertexBuffer.UV2Kind
  21506. * * BABYLON.VertexBuffer.UV3Kind
  21507. * * BABYLON.VertexBuffer.UV4Kind
  21508. * * BABYLON.VertexBuffer.UV5Kind
  21509. * * BABYLON.VertexBuffer.UV6Kind
  21510. * * BABYLON.VertexBuffer.ColorKind
  21511. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21512. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21513. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21514. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21515. * @param data defines the data source
  21516. * @param updatable defines if the data must be flagged as updatable (or static)
  21517. * @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
  21518. * @returns the current mesh
  21519. */
  21520. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21521. return this;
  21522. };
  21523. /**
  21524. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21525. * If the mesh has no geometry, it is simply returned as it is.
  21526. * @param kind defines vertex data kind:
  21527. * * BABYLON.VertexBuffer.PositionKind
  21528. * * BABYLON.VertexBuffer.UVKind
  21529. * * BABYLON.VertexBuffer.UV2Kind
  21530. * * BABYLON.VertexBuffer.UV3Kind
  21531. * * BABYLON.VertexBuffer.UV4Kind
  21532. * * BABYLON.VertexBuffer.UV5Kind
  21533. * * BABYLON.VertexBuffer.UV6Kind
  21534. * * BABYLON.VertexBuffer.ColorKind
  21535. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21536. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21537. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21538. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21539. * @param data defines the data source
  21540. * @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
  21541. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21542. * @returns the current mesh
  21543. */
  21544. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21545. return this;
  21546. };
  21547. /**
  21548. * Sets the mesh indices,
  21549. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21550. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21551. * @param totalVertices Defines the total number of vertices
  21552. * @returns the current mesh
  21553. */
  21554. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21555. return this;
  21556. };
  21557. /**
  21558. * Gets a boolean indicating if specific vertex data is present
  21559. * @param kind defines the vertex data kind to use
  21560. * @returns true is data kind is present
  21561. */
  21562. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21563. return false;
  21564. };
  21565. /**
  21566. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21567. * @returns a BoundingInfo
  21568. */
  21569. AbstractMesh.prototype.getBoundingInfo = function () {
  21570. if (this._masterMesh) {
  21571. return this._masterMesh.getBoundingInfo();
  21572. }
  21573. if (!this._boundingInfo) {
  21574. // this._boundingInfo is being created here
  21575. this._updateBoundingInfo();
  21576. }
  21577. // cannot be null.
  21578. return this._boundingInfo;
  21579. };
  21580. /**
  21581. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21582. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21583. * @returns the current mesh
  21584. */
  21585. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21586. if (includeDescendants === void 0) { includeDescendants = true; }
  21587. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21588. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21589. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21590. if (maxDimension === 0) {
  21591. return this;
  21592. }
  21593. var scale = 1 / maxDimension;
  21594. this.scaling.scaleInPlace(scale);
  21595. return this;
  21596. };
  21597. /**
  21598. * Overwrite the current bounding info
  21599. * @param boundingInfo defines the new bounding info
  21600. * @returns the current mesh
  21601. */
  21602. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21603. this._boundingInfo = boundingInfo;
  21604. return this;
  21605. };
  21606. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21607. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21608. get: function () {
  21609. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21610. },
  21611. enumerable: true,
  21612. configurable: true
  21613. });
  21614. /** @hidden */
  21615. AbstractMesh.prototype._preActivate = function () {
  21616. };
  21617. /** @hidden */
  21618. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21619. };
  21620. /** @hidden */
  21621. AbstractMesh.prototype._activate = function (renderId) {
  21622. this._renderId = renderId;
  21623. };
  21624. /**
  21625. * Gets the current world matrix
  21626. * @returns a Matrix
  21627. */
  21628. AbstractMesh.prototype.getWorldMatrix = function () {
  21629. if (this._masterMesh) {
  21630. return this._masterMesh.getWorldMatrix();
  21631. }
  21632. return _super.prototype.getWorldMatrix.call(this);
  21633. };
  21634. /** @hidden */
  21635. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21636. if (this._masterMesh) {
  21637. return this._masterMesh._getWorldMatrixDeterminant();
  21638. }
  21639. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21640. };
  21641. // ================================== Point of View Movement =================================
  21642. /**
  21643. * Perform relative position change from the point of view of behind the front of the mesh.
  21644. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21645. * Supports definition of mesh facing forward or backward
  21646. * @param amountRight defines the distance on the right axis
  21647. * @param amountUp defines the distance on the up axis
  21648. * @param amountForward defines the distance on the forward axis
  21649. * @returns the current mesh
  21650. */
  21651. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21652. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21653. return this;
  21654. };
  21655. /**
  21656. * Calculate relative position change from the point of view of behind the front of the mesh.
  21657. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21658. * Supports definition of mesh facing forward or backward
  21659. * @param amountRight defines the distance on the right axis
  21660. * @param amountUp defines the distance on the up axis
  21661. * @param amountForward defines the distance on the forward axis
  21662. * @returns the new displacement vector
  21663. */
  21664. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21665. var rotMatrix = new BABYLON.Matrix();
  21666. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21667. rotQuaternion.toRotationMatrix(rotMatrix);
  21668. var translationDelta = BABYLON.Vector3.Zero();
  21669. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21670. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21671. return translationDelta;
  21672. };
  21673. // ================================== Point of View Rotation =================================
  21674. /**
  21675. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21676. * Supports definition of mesh facing forward or backward
  21677. * @param flipBack defines the flip
  21678. * @param twirlClockwise defines the twirl
  21679. * @param tiltRight defines the tilt
  21680. * @returns the current mesh
  21681. */
  21682. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21683. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21684. return this;
  21685. };
  21686. /**
  21687. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21688. * Supports definition of mesh facing forward or backward.
  21689. * @param flipBack defines the flip
  21690. * @param twirlClockwise defines the twirl
  21691. * @param tiltRight defines the tilt
  21692. * @returns the new rotation vector
  21693. */
  21694. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21695. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21696. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21697. };
  21698. /**
  21699. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21700. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21701. * @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
  21702. * @returns the new bounding vectors
  21703. */
  21704. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21705. if (includeDescendants === void 0) { includeDescendants = true; }
  21706. if (predicate === void 0) { predicate = null; }
  21707. // Ensures that all world matrix will be recomputed.
  21708. this.getScene().incrementRenderId();
  21709. this.computeWorldMatrix(true);
  21710. var min;
  21711. var max;
  21712. var boundingInfo = this.getBoundingInfo();
  21713. if (!this.subMeshes) {
  21714. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21715. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21716. }
  21717. else {
  21718. min = boundingInfo.boundingBox.minimumWorld;
  21719. max = boundingInfo.boundingBox.maximumWorld;
  21720. }
  21721. if (includeDescendants) {
  21722. var descendants = this.getDescendants(false);
  21723. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21724. var descendant = descendants_1[_i];
  21725. var childMesh = descendant;
  21726. childMesh.computeWorldMatrix(true);
  21727. // Filters meshes based on custom predicate function.
  21728. if (predicate && !predicate(childMesh)) {
  21729. continue;
  21730. }
  21731. //make sure we have the needed params to get mix and max
  21732. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21733. continue;
  21734. }
  21735. var childBoundingInfo = childMesh.getBoundingInfo();
  21736. var boundingBox = childBoundingInfo.boundingBox;
  21737. var minBox = boundingBox.minimumWorld;
  21738. var maxBox = boundingBox.maximumWorld;
  21739. BABYLON.Tools.CheckExtends(minBox, min, max);
  21740. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21741. }
  21742. }
  21743. return {
  21744. min: min,
  21745. max: max
  21746. };
  21747. };
  21748. /** @hidden */
  21749. AbstractMesh.prototype._updateBoundingInfo = function () {
  21750. if (this._boundingInfo) {
  21751. this._boundingInfo.update(this.worldMatrixFromCache);
  21752. }
  21753. else {
  21754. this._boundingInfo = new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition, this.worldMatrixFromCache);
  21755. }
  21756. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21757. return this;
  21758. };
  21759. /** @hidden */
  21760. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21761. if (!this.subMeshes) {
  21762. return this;
  21763. }
  21764. var count = this.subMeshes.length;
  21765. for (var subIndex = 0; subIndex < count; subIndex++) {
  21766. var subMesh = this.subMeshes[subIndex];
  21767. if (count > 1 || !subMesh.IsGlobal) {
  21768. subMesh.updateBoundingInfo(matrix);
  21769. }
  21770. }
  21771. return this;
  21772. };
  21773. /** @hidden */
  21774. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21775. // Bounding info
  21776. this._updateBoundingInfo();
  21777. };
  21778. /**
  21779. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21780. * A mesh is in the frustum if its bounding box intersects the frustum
  21781. * @param frustumPlanes defines the frustum to test
  21782. * @returns true if the mesh is in the frustum planes
  21783. */
  21784. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21785. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21786. };
  21787. /**
  21788. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21789. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21790. * @param frustumPlanes defines the frustum to test
  21791. * @returns true if the mesh is completely in the frustum planes
  21792. */
  21793. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21794. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21795. };
  21796. /**
  21797. * True if the mesh intersects another mesh or a SolidParticle object
  21798. * @param mesh defines a target mesh or SolidParticle to test
  21799. * @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)
  21800. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21801. * @returns true if there is an intersection
  21802. */
  21803. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21804. if (precise === void 0) { precise = false; }
  21805. if (!this._boundingInfo || !mesh._boundingInfo) {
  21806. return false;
  21807. }
  21808. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21809. return true;
  21810. }
  21811. if (includeDescendants) {
  21812. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21813. var child = _a[_i];
  21814. if (child.intersectsMesh(mesh, precise, true)) {
  21815. return true;
  21816. }
  21817. }
  21818. }
  21819. return false;
  21820. };
  21821. /**
  21822. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21823. * @param point defines the point to test
  21824. * @returns true if there is an intersection
  21825. */
  21826. AbstractMesh.prototype.intersectsPoint = function (point) {
  21827. if (!this._boundingInfo) {
  21828. return false;
  21829. }
  21830. return this._boundingInfo.intersectsPoint(point);
  21831. };
  21832. /**
  21833. * Gets the position of the current mesh in camera space
  21834. * @param camera defines the camera to use
  21835. * @returns a position
  21836. */
  21837. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21838. if (camera === void 0) { camera = null; }
  21839. if (!camera) {
  21840. camera = this.getScene().activeCamera;
  21841. }
  21842. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21843. };
  21844. /**
  21845. * Returns the distance from the mesh to the active camera
  21846. * @param camera defines the camera to use
  21847. * @returns the distance
  21848. */
  21849. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21850. if (camera === void 0) { camera = null; }
  21851. if (!camera) {
  21852. camera = this.getScene().activeCamera;
  21853. }
  21854. return this.absolutePosition.subtract(camera.position).length();
  21855. };
  21856. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21857. // Collisions
  21858. /**
  21859. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21860. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21861. */
  21862. get: function () {
  21863. return this._checkCollisions;
  21864. },
  21865. set: function (collisionEnabled) {
  21866. this._checkCollisions = collisionEnabled;
  21867. if (this.getScene().workerCollisions) {
  21868. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21869. }
  21870. },
  21871. enumerable: true,
  21872. configurable: true
  21873. });
  21874. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21875. /**
  21876. * Gets Collider object used to compute collisions (not physics)
  21877. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21878. */
  21879. get: function () {
  21880. return this._collider;
  21881. },
  21882. enumerable: true,
  21883. configurable: true
  21884. });
  21885. /**
  21886. * Move the mesh using collision engine
  21887. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21888. * @param displacement defines the requested displacement vector
  21889. * @returns the current mesh
  21890. */
  21891. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21892. var globalPosition = this.getAbsolutePosition();
  21893. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21894. if (!this._collider) {
  21895. this._collider = new BABYLON.Collider();
  21896. }
  21897. this._collider._radius = this.ellipsoid;
  21898. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21899. return this;
  21900. };
  21901. // Collisions
  21902. /** @hidden */
  21903. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21904. this._generatePointsArray();
  21905. if (!this._positions) {
  21906. return this;
  21907. }
  21908. // Transformation
  21909. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21910. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21911. subMesh._lastColliderWorldVertices = [];
  21912. subMesh._trianglePlanes = [];
  21913. var start = subMesh.verticesStart;
  21914. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21915. for (var i = start; i < end; i++) {
  21916. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21917. }
  21918. }
  21919. // Collide
  21920. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21921. if (collider.collisionFound) {
  21922. collider.collidedMesh = this;
  21923. }
  21924. return this;
  21925. };
  21926. /** @hidden */
  21927. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21928. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21929. var len = subMeshes.length;
  21930. for (var index = 0; index < len; index++) {
  21931. var subMesh = subMeshes.data[index];
  21932. // Bounding test
  21933. if (len > 1 && !subMesh._checkCollision(collider)) {
  21934. continue;
  21935. }
  21936. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21937. }
  21938. return this;
  21939. };
  21940. /** @hidden */
  21941. AbstractMesh.prototype._checkCollision = function (collider) {
  21942. // Bounding box test
  21943. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) {
  21944. return this;
  21945. }
  21946. // Transformation matrix
  21947. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  21948. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  21949. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  21950. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  21951. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  21952. return this;
  21953. };
  21954. // Picking
  21955. /** @hidden */
  21956. AbstractMesh.prototype._generatePointsArray = function () {
  21957. return false;
  21958. };
  21959. /**
  21960. * Checks if the passed Ray intersects with the mesh
  21961. * @param ray defines the ray to use
  21962. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21963. * @returns the picking info
  21964. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21965. */
  21966. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21967. var pickingInfo = new BABYLON.PickingInfo();
  21968. var intersectionTreshold = this.getClassName() === "LinesMesh" ? this.intersectionThreshold : 0;
  21969. var boundingInfo = this._boundingInfo;
  21970. if (!this.subMeshes || !boundingInfo || !ray.intersectsSphere(boundingInfo.boundingSphere, intersectionTreshold) || !ray.intersectsBox(boundingInfo.boundingBox, intersectionTreshold)) {
  21971. return pickingInfo;
  21972. }
  21973. if (!this._generatePointsArray()) {
  21974. return pickingInfo;
  21975. }
  21976. var intersectInfo = null;
  21977. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21978. var len = subMeshes.length;
  21979. for (var index = 0; index < len; index++) {
  21980. var subMesh = subMeshes.data[index];
  21981. // Bounding test
  21982. if (len > 1 && !subMesh.canIntersects(ray)) {
  21983. continue;
  21984. }
  21985. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21986. if (currentIntersectInfo) {
  21987. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21988. intersectInfo = currentIntersectInfo;
  21989. intersectInfo.subMeshId = index;
  21990. if (fastCheck) {
  21991. break;
  21992. }
  21993. }
  21994. }
  21995. }
  21996. if (intersectInfo) {
  21997. // Get picked point
  21998. var world = this.getWorldMatrix();
  21999. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  22000. var direction = ray.direction.scaleToRef(intersectInfo.distance, BABYLON.Tmp.Vector3[0]);
  22001. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  22002. var pickedPoint = worldDirection.addInPlace(worldOrigin);
  22003. // Return result
  22004. pickingInfo.hit = true;
  22005. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  22006. pickingInfo.pickedPoint = pickedPoint;
  22007. pickingInfo.pickedMesh = this;
  22008. pickingInfo.bu = intersectInfo.bu || 0;
  22009. pickingInfo.bv = intersectInfo.bv || 0;
  22010. pickingInfo.faceId = intersectInfo.faceId;
  22011. pickingInfo.subMeshId = intersectInfo.subMeshId;
  22012. return pickingInfo;
  22013. }
  22014. return pickingInfo;
  22015. };
  22016. /**
  22017. * Clones the current mesh
  22018. * @param name defines the mesh name
  22019. * @param newParent defines the new mesh parent
  22020. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  22021. * @returns the new mesh
  22022. */
  22023. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22024. return null;
  22025. };
  22026. /**
  22027. * Disposes all the submeshes of the current meshnp
  22028. * @returns the current mesh
  22029. */
  22030. AbstractMesh.prototype.releaseSubMeshes = function () {
  22031. if (this.subMeshes) {
  22032. while (this.subMeshes.length) {
  22033. this.subMeshes[0].dispose();
  22034. }
  22035. }
  22036. else {
  22037. this.subMeshes = new Array();
  22038. }
  22039. return this;
  22040. };
  22041. /**
  22042. * Releases resources associated with this abstract mesh.
  22043. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22044. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22045. */
  22046. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22047. var _this = this;
  22048. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22049. var index;
  22050. // Smart Array Retainers.
  22051. this.getScene().freeActiveMeshes();
  22052. this.getScene().freeRenderingGroups();
  22053. // Action manager
  22054. if (this.actionManager !== undefined && this.actionManager !== null) {
  22055. this.actionManager.dispose();
  22056. this.actionManager = null;
  22057. }
  22058. // Skeleton
  22059. this._skeleton = null;
  22060. // Intersections in progress
  22061. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  22062. var other = this._intersectionsInProgress[index];
  22063. var pos = other._intersectionsInProgress.indexOf(this);
  22064. other._intersectionsInProgress.splice(pos, 1);
  22065. }
  22066. this._intersectionsInProgress = [];
  22067. // Lights
  22068. var lights = this.getScene().lights;
  22069. lights.forEach(function (light) {
  22070. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  22071. if (meshIndex !== -1) {
  22072. light.includedOnlyMeshes.splice(meshIndex, 1);
  22073. }
  22074. meshIndex = light.excludedMeshes.indexOf(_this);
  22075. if (meshIndex !== -1) {
  22076. light.excludedMeshes.splice(meshIndex, 1);
  22077. }
  22078. // Shadow generators
  22079. var generator = light.getShadowGenerator();
  22080. if (generator) {
  22081. var shadowMap = generator.getShadowMap();
  22082. if (shadowMap && shadowMap.renderList) {
  22083. meshIndex = shadowMap.renderList.indexOf(_this);
  22084. if (meshIndex !== -1) {
  22085. shadowMap.renderList.splice(meshIndex, 1);
  22086. }
  22087. }
  22088. }
  22089. });
  22090. // SubMeshes
  22091. if (this.getClassName() !== "InstancedMesh") {
  22092. this.releaseSubMeshes();
  22093. }
  22094. // Query
  22095. var engine = this.getScene().getEngine();
  22096. if (this._occlusionQuery) {
  22097. this.isOcclusionQueryInProgress = false;
  22098. engine.deleteQuery(this._occlusionQuery);
  22099. this._occlusionQuery = null;
  22100. }
  22101. // Engine
  22102. engine.wipeCaches();
  22103. // Remove from scene
  22104. this.getScene().removeMesh(this);
  22105. if (disposeMaterialAndTextures) {
  22106. if (this.material) {
  22107. this.material.dispose(false, true);
  22108. }
  22109. }
  22110. if (!doNotRecurse) {
  22111. // Particles
  22112. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  22113. if (this.getScene().particleSystems[index].emitter === this) {
  22114. this.getScene().particleSystems[index].dispose();
  22115. index--;
  22116. }
  22117. }
  22118. }
  22119. // facet data
  22120. if (this._facetData.facetDataEnabled) {
  22121. this.disableFacetData();
  22122. }
  22123. this.onAfterWorldMatrixUpdateObservable.clear();
  22124. this.onCollideObservable.clear();
  22125. this.onCollisionPositionChangeObservable.clear();
  22126. this.onRebuildObservable.clear();
  22127. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22128. };
  22129. /**
  22130. * Adds the passed mesh as a child to the current mesh
  22131. * @param mesh defines the child mesh
  22132. * @returns the current mesh
  22133. */
  22134. AbstractMesh.prototype.addChild = function (mesh) {
  22135. mesh.setParent(this);
  22136. return this;
  22137. };
  22138. /**
  22139. * Removes the passed mesh from the current mesh children list
  22140. * @param mesh defines the child mesh
  22141. * @returns the current mesh
  22142. */
  22143. AbstractMesh.prototype.removeChild = function (mesh) {
  22144. mesh.setParent(null);
  22145. return this;
  22146. };
  22147. // Facet data
  22148. /** @hidden */
  22149. AbstractMesh.prototype._initFacetData = function () {
  22150. var data = this._facetData;
  22151. if (!data.facetNormals) {
  22152. data.facetNormals = new Array();
  22153. }
  22154. if (!data.facetPositions) {
  22155. data.facetPositions = new Array();
  22156. }
  22157. if (!data.facetPartitioning) {
  22158. data.facetPartitioning = new Array();
  22159. }
  22160. data.facetNb = (this.getIndices().length / 3) | 0;
  22161. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  22162. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  22163. for (var f = 0; f < data.facetNb; f++) {
  22164. data.facetNormals[f] = BABYLON.Vector3.Zero();
  22165. data.facetPositions[f] = BABYLON.Vector3.Zero();
  22166. }
  22167. data.facetDataEnabled = true;
  22168. return this;
  22169. };
  22170. /**
  22171. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  22172. * This method can be called within the render loop.
  22173. * 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
  22174. * @returns the current mesh
  22175. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22176. */
  22177. AbstractMesh.prototype.updateFacetData = function () {
  22178. var data = this._facetData;
  22179. if (!data.facetDataEnabled) {
  22180. this._initFacetData();
  22181. }
  22182. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22183. var indices = this.getIndices();
  22184. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22185. var bInfo = this.getBoundingInfo();
  22186. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  22187. // init arrays, matrix and sort function on first call
  22188. data.facetDepthSortEnabled = true;
  22189. if (indices instanceof Uint16Array) {
  22190. data.depthSortedIndices = new Uint16Array(indices);
  22191. }
  22192. else if (indices instanceof Uint32Array) {
  22193. data.depthSortedIndices = new Uint32Array(indices);
  22194. }
  22195. else {
  22196. var needs32bits = false;
  22197. for (var i = 0; i < indices.length; i++) {
  22198. if (indices[i] > 65535) {
  22199. needs32bits = true;
  22200. break;
  22201. }
  22202. }
  22203. if (needs32bits) {
  22204. data.depthSortedIndices = new Uint32Array(indices);
  22205. }
  22206. else {
  22207. data.depthSortedIndices = new Uint16Array(indices);
  22208. }
  22209. }
  22210. data.facetDepthSortFunction = function (f1, f2) {
  22211. return (f2.sqDistance - f1.sqDistance);
  22212. };
  22213. if (!data.facetDepthSortFrom) {
  22214. var camera = this.getScene().activeCamera;
  22215. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  22216. }
  22217. data.depthSortedFacets = [];
  22218. for (var f = 0; f < data.facetNb; f++) {
  22219. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  22220. data.depthSortedFacets.push(depthSortedFacet);
  22221. }
  22222. data.invertedMatrix = BABYLON.Matrix.Identity();
  22223. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  22224. }
  22225. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  22226. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  22227. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  22228. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  22229. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  22230. data.subDiv.max = data.partitioningSubdivisions;
  22231. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  22232. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  22233. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  22234. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  22235. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  22236. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  22237. // set the parameters for ComputeNormals()
  22238. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  22239. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  22240. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  22241. data.facetParameters.bInfo = bInfo;
  22242. data.facetParameters.bbSize = data.bbSize;
  22243. data.facetParameters.subDiv = data.subDiv;
  22244. data.facetParameters.ratio = this.partitioningBBoxRatio;
  22245. data.facetParameters.depthSort = data.facetDepthSort;
  22246. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22247. this.computeWorldMatrix(true);
  22248. this._worldMatrix.invertToRef(data.invertedMatrix);
  22249. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  22250. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  22251. }
  22252. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  22253. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  22254. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22255. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  22256. var l = (data.depthSortedIndices.length / 3) | 0;
  22257. for (var f = 0; f < l; f++) {
  22258. var sind = data.depthSortedFacets[f].ind;
  22259. data.depthSortedIndices[f * 3] = indices[sind];
  22260. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  22261. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  22262. }
  22263. this.updateIndices(data.depthSortedIndices);
  22264. }
  22265. return this;
  22266. };
  22267. /**
  22268. * Returns the facetLocalNormals array.
  22269. * The normals are expressed in the mesh local spac
  22270. * @returns an array of Vector3
  22271. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22272. */
  22273. AbstractMesh.prototype.getFacetLocalNormals = function () {
  22274. if (!this._facetData.facetNormals) {
  22275. this.updateFacetData();
  22276. }
  22277. return this._facetData.facetNormals;
  22278. };
  22279. /**
  22280. * Returns the facetLocalPositions array.
  22281. * The facet positions are expressed in the mesh local space
  22282. * @returns an array of Vector3
  22283. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22284. */
  22285. AbstractMesh.prototype.getFacetLocalPositions = function () {
  22286. if (!this._facetData.facetPositions) {
  22287. this.updateFacetData();
  22288. }
  22289. return this._facetData.facetPositions;
  22290. };
  22291. /**
  22292. * Returns the facetLocalPartioning array
  22293. * @returns an array of array of numbers
  22294. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22295. */
  22296. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  22297. if (!this._facetData.facetPartitioning) {
  22298. this.updateFacetData();
  22299. }
  22300. return this._facetData.facetPartitioning;
  22301. };
  22302. /**
  22303. * Returns the i-th facet position in the world system.
  22304. * This method allocates a new Vector3 per call
  22305. * @param i defines the facet index
  22306. * @returns a new Vector3
  22307. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22308. */
  22309. AbstractMesh.prototype.getFacetPosition = function (i) {
  22310. var pos = BABYLON.Vector3.Zero();
  22311. this.getFacetPositionToRef(i, pos);
  22312. return pos;
  22313. };
  22314. /**
  22315. * Sets the reference Vector3 with the i-th facet position in the world system
  22316. * @param i defines the facet index
  22317. * @param ref defines the target vector
  22318. * @returns the current mesh
  22319. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22320. */
  22321. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  22322. var localPos = (this.getFacetLocalPositions())[i];
  22323. var world = this.getWorldMatrix();
  22324. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  22325. return this;
  22326. };
  22327. /**
  22328. * Returns the i-th facet normal in the world system.
  22329. * This method allocates a new Vector3 per call
  22330. * @param i defines the facet index
  22331. * @returns a new Vector3
  22332. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22333. */
  22334. AbstractMesh.prototype.getFacetNormal = function (i) {
  22335. var norm = BABYLON.Vector3.Zero();
  22336. this.getFacetNormalToRef(i, norm);
  22337. return norm;
  22338. };
  22339. /**
  22340. * Sets the reference Vector3 with the i-th facet normal in the world system
  22341. * @param i defines the facet index
  22342. * @param ref defines the target vector
  22343. * @returns the current mesh
  22344. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22345. */
  22346. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  22347. var localNorm = (this.getFacetLocalNormals())[i];
  22348. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  22349. return this;
  22350. };
  22351. /**
  22352. * 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)
  22353. * @param x defines x coordinate
  22354. * @param y defines y coordinate
  22355. * @param z defines z coordinate
  22356. * @returns the array of facet indexes
  22357. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22358. */
  22359. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22360. var bInfo = this.getBoundingInfo();
  22361. var data = this._facetData;
  22362. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22363. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22364. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22365. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22366. return null;
  22367. }
  22368. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22369. };
  22370. /**
  22371. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22372. * @param projected sets as the (x,y,z) world projection on the facet
  22373. * @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
  22374. * @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
  22375. * @param x defines x coordinate
  22376. * @param y defines y coordinate
  22377. * @param z defines z coordinate
  22378. * @returns the face index if found (or null instead)
  22379. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22380. */
  22381. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22382. if (checkFace === void 0) { checkFace = false; }
  22383. if (facing === void 0) { facing = true; }
  22384. var world = this.getWorldMatrix();
  22385. var invMat = BABYLON.Tmp.Matrix[5];
  22386. world.invertToRef(invMat);
  22387. var invVect = BABYLON.Tmp.Vector3[8];
  22388. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22389. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22390. if (projected) {
  22391. // tranform the local computed projected vector to world coordinates
  22392. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22393. }
  22394. return closest;
  22395. };
  22396. /**
  22397. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22398. * @param projected sets as the (x,y,z) local projection on the facet
  22399. * @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
  22400. * @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
  22401. * @param x defines x coordinate
  22402. * @param y defines y coordinate
  22403. * @param z defines z coordinate
  22404. * @returns the face index if found (or null instead)
  22405. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22406. */
  22407. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22408. if (checkFace === void 0) { checkFace = false; }
  22409. if (facing === void 0) { facing = true; }
  22410. var closest = null;
  22411. var tmpx = 0.0;
  22412. var tmpy = 0.0;
  22413. var tmpz = 0.0;
  22414. var d = 0.0; // tmp dot facet normal * facet position
  22415. var t0 = 0.0;
  22416. var projx = 0.0;
  22417. var projy = 0.0;
  22418. var projz = 0.0;
  22419. // Get all the facets in the same partitioning block than (x, y, z)
  22420. var facetPositions = this.getFacetLocalPositions();
  22421. var facetNormals = this.getFacetLocalNormals();
  22422. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22423. if (!facetsInBlock) {
  22424. return null;
  22425. }
  22426. // Get the closest facet to (x, y, z)
  22427. var shortest = Number.MAX_VALUE; // init distance vars
  22428. var tmpDistance = shortest;
  22429. var fib; // current facet in the block
  22430. var norm; // current facet normal
  22431. var p0; // current facet barycenter position
  22432. // loop on all the facets in the current partitioning block
  22433. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22434. fib = facetsInBlock[idx];
  22435. norm = facetNormals[fib];
  22436. p0 = facetPositions[fib];
  22437. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22438. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22439. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22440. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22441. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22442. projx = x + norm.x * t0;
  22443. projy = y + norm.y * t0;
  22444. projz = z + norm.z * t0;
  22445. tmpx = projx - x;
  22446. tmpy = projy - y;
  22447. tmpz = projz - z;
  22448. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22449. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22450. shortest = tmpDistance;
  22451. closest = fib;
  22452. if (projected) {
  22453. projected.x = projx;
  22454. projected.y = projy;
  22455. projected.z = projz;
  22456. }
  22457. }
  22458. }
  22459. }
  22460. return closest;
  22461. };
  22462. /**
  22463. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22464. * @returns the parameters
  22465. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22466. */
  22467. AbstractMesh.prototype.getFacetDataParameters = function () {
  22468. return this._facetData.facetParameters;
  22469. };
  22470. /**
  22471. * Disables the feature FacetData and frees the related memory
  22472. * @returns the current mesh
  22473. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22474. */
  22475. AbstractMesh.prototype.disableFacetData = function () {
  22476. if (this._facetData.facetDataEnabled) {
  22477. this._facetData.facetDataEnabled = false;
  22478. this._facetData.facetPositions = new Array();
  22479. this._facetData.facetNormals = new Array();
  22480. this._facetData.facetPartitioning = new Array();
  22481. this._facetData.facetParameters = null;
  22482. this._facetData.depthSortedIndices = new Uint32Array(0);
  22483. }
  22484. return this;
  22485. };
  22486. /**
  22487. * Updates the AbstractMesh indices array
  22488. * @param indices defines the data source
  22489. * @returns the current mesh
  22490. */
  22491. AbstractMesh.prototype.updateIndices = function (indices) {
  22492. return this;
  22493. };
  22494. /**
  22495. * Creates new normals data for the mesh
  22496. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22497. * @returns the current mesh
  22498. */
  22499. AbstractMesh.prototype.createNormals = function (updatable) {
  22500. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22501. var indices = this.getIndices();
  22502. var normals;
  22503. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22504. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22505. }
  22506. else {
  22507. normals = [];
  22508. }
  22509. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22510. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22511. return this;
  22512. };
  22513. /**
  22514. * Align the mesh with a normal
  22515. * @param normal defines the normal to use
  22516. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22517. * @returns the current mesh
  22518. */
  22519. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22520. if (!upDirection) {
  22521. upDirection = BABYLON.Axis.Y;
  22522. }
  22523. var axisX = BABYLON.Tmp.Vector3[0];
  22524. var axisZ = BABYLON.Tmp.Vector3[1];
  22525. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22526. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22527. if (this.rotationQuaternion) {
  22528. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22529. }
  22530. else {
  22531. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22532. }
  22533. return this;
  22534. };
  22535. /** @hidden */
  22536. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22537. return false;
  22538. };
  22539. /** No occlusion */
  22540. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22541. /** Occlusion set to optimisitic */
  22542. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22543. /** Occlusion set to strict */
  22544. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22545. /** Use an accurante occlusion algorithm */
  22546. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22547. /** Use a conservative occlusion algorithm */
  22548. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22549. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22550. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22551. /** Culling strategy with bounding sphere only and then frustum culling */
  22552. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22553. return AbstractMesh;
  22554. }(BABYLON.TransformNode));
  22555. BABYLON.AbstractMesh = AbstractMesh;
  22556. })(BABYLON || (BABYLON = {}));
  22557. //# sourceMappingURL=babylon.abstractMesh.js.map
  22558. var BABYLON;
  22559. (function (BABYLON) {
  22560. /**
  22561. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22562. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22563. * 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.
  22564. */
  22565. var Light = /** @class */ (function (_super) {
  22566. __extends(Light, _super);
  22567. /**
  22568. * Creates a Light object in the scene.
  22569. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22570. * @param name The firendly name of the light
  22571. * @param scene The scene the light belongs too
  22572. */
  22573. function Light(name, scene) {
  22574. var _this = _super.call(this, name, scene) || this;
  22575. /**
  22576. * Diffuse gives the basic color to an object.
  22577. */
  22578. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22579. /**
  22580. * Specular produces a highlight color on an object.
  22581. * Note: This is note affecting PBR materials.
  22582. */
  22583. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22584. /**
  22585. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22586. * falling off base on range or angle.
  22587. * This can be set to any values in Light.FALLOFF_x.
  22588. *
  22589. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22590. * other types of materials.
  22591. */
  22592. _this.falloffType = Light.FALLOFF_DEFAULT;
  22593. /**
  22594. * Strength of the light.
  22595. * Note: By default it is define in the framework own unit.
  22596. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22597. */
  22598. _this.intensity = 1.0;
  22599. _this._range = Number.MAX_VALUE;
  22600. _this._inverseSquaredRange = 0;
  22601. /**
  22602. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22603. * of light.
  22604. */
  22605. _this._photometricScale = 1.0;
  22606. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22607. _this._radius = 0.00001;
  22608. /**
  22609. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22610. * exceeding the number allowed of the materials.
  22611. */
  22612. _this.renderPriority = 0;
  22613. _this._shadowEnabled = true;
  22614. _this._excludeWithLayerMask = 0;
  22615. _this._includeOnlyWithLayerMask = 0;
  22616. _this._lightmapMode = 0;
  22617. /**
  22618. * @hidden Internal use only.
  22619. */
  22620. _this._excludedMeshesIds = new Array();
  22621. /**
  22622. * @hidden Internal use only.
  22623. */
  22624. _this._includedOnlyMeshesIds = new Array();
  22625. _this.getScene().addLight(_this);
  22626. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22627. _this._buildUniformLayout();
  22628. _this.includedOnlyMeshes = new Array();
  22629. _this.excludedMeshes = new Array();
  22630. _this._resyncMeshes();
  22631. return _this;
  22632. }
  22633. Object.defineProperty(Light.prototype, "range", {
  22634. /**
  22635. * Defines how far from the source the light is impacting in scene units.
  22636. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22637. */
  22638. get: function () {
  22639. return this._range;
  22640. },
  22641. /**
  22642. * Defines how far from the source the light is impacting in scene units.
  22643. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22644. */
  22645. set: function (value) {
  22646. this._range = value;
  22647. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22648. },
  22649. enumerable: true,
  22650. configurable: true
  22651. });
  22652. Object.defineProperty(Light.prototype, "intensityMode", {
  22653. /**
  22654. * Gets the photometric scale used to interpret the intensity.
  22655. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22656. */
  22657. get: function () {
  22658. return this._intensityMode;
  22659. },
  22660. /**
  22661. * Sets the photometric scale used to interpret the intensity.
  22662. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22663. */
  22664. set: function (value) {
  22665. this._intensityMode = value;
  22666. this._computePhotometricScale();
  22667. },
  22668. enumerable: true,
  22669. configurable: true
  22670. });
  22671. Object.defineProperty(Light.prototype, "radius", {
  22672. /**
  22673. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22674. */
  22675. get: function () {
  22676. return this._radius;
  22677. },
  22678. /**
  22679. * sets the light radius used by PBR Materials to simulate soft area lights.
  22680. */
  22681. set: function (value) {
  22682. this._radius = value;
  22683. this._computePhotometricScale();
  22684. },
  22685. enumerable: true,
  22686. configurable: true
  22687. });
  22688. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22689. /**
  22690. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22691. * the current shadow generator.
  22692. */
  22693. get: function () {
  22694. return this._shadowEnabled;
  22695. },
  22696. /**
  22697. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22698. * the current shadow generator.
  22699. */
  22700. set: function (value) {
  22701. if (this._shadowEnabled === value) {
  22702. return;
  22703. }
  22704. this._shadowEnabled = value;
  22705. this._markMeshesAsLightDirty();
  22706. },
  22707. enumerable: true,
  22708. configurable: true
  22709. });
  22710. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22711. /**
  22712. * Gets the only meshes impacted by this light.
  22713. */
  22714. get: function () {
  22715. return this._includedOnlyMeshes;
  22716. },
  22717. /**
  22718. * Sets the only meshes impacted by this light.
  22719. */
  22720. set: function (value) {
  22721. this._includedOnlyMeshes = value;
  22722. this._hookArrayForIncludedOnly(value);
  22723. },
  22724. enumerable: true,
  22725. configurable: true
  22726. });
  22727. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22728. /**
  22729. * Gets the meshes not impacted by this light.
  22730. */
  22731. get: function () {
  22732. return this._excludedMeshes;
  22733. },
  22734. /**
  22735. * Sets the meshes not impacted by this light.
  22736. */
  22737. set: function (value) {
  22738. this._excludedMeshes = value;
  22739. this._hookArrayForExcluded(value);
  22740. },
  22741. enumerable: true,
  22742. configurable: true
  22743. });
  22744. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22745. /**
  22746. * Gets the layer id use to find what meshes are not impacted by the light.
  22747. * Inactive if 0
  22748. */
  22749. get: function () {
  22750. return this._excludeWithLayerMask;
  22751. },
  22752. /**
  22753. * Sets the layer id use to find what meshes are not impacted by the light.
  22754. * Inactive if 0
  22755. */
  22756. set: function (value) {
  22757. this._excludeWithLayerMask = value;
  22758. this._resyncMeshes();
  22759. },
  22760. enumerable: true,
  22761. configurable: true
  22762. });
  22763. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22764. /**
  22765. * Gets the layer id use to find what meshes are impacted by the light.
  22766. * Inactive if 0
  22767. */
  22768. get: function () {
  22769. return this._includeOnlyWithLayerMask;
  22770. },
  22771. /**
  22772. * Sets the layer id use to find what meshes are impacted by the light.
  22773. * Inactive if 0
  22774. */
  22775. set: function (value) {
  22776. this._includeOnlyWithLayerMask = value;
  22777. this._resyncMeshes();
  22778. },
  22779. enumerable: true,
  22780. configurable: true
  22781. });
  22782. Object.defineProperty(Light.prototype, "lightmapMode", {
  22783. /**
  22784. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22785. */
  22786. get: function () {
  22787. return this._lightmapMode;
  22788. },
  22789. /**
  22790. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22791. */
  22792. set: function (value) {
  22793. if (this._lightmapMode === value) {
  22794. return;
  22795. }
  22796. this._lightmapMode = value;
  22797. this._markMeshesAsLightDirty();
  22798. },
  22799. enumerable: true,
  22800. configurable: true
  22801. });
  22802. /**
  22803. * Returns the string "Light".
  22804. * @returns the class name
  22805. */
  22806. Light.prototype.getClassName = function () {
  22807. return "Light";
  22808. };
  22809. /**
  22810. * Converts the light information to a readable string for debug purpose.
  22811. * @param fullDetails Supports for multiple levels of logging within scene loading
  22812. * @returns the human readable light info
  22813. */
  22814. Light.prototype.toString = function (fullDetails) {
  22815. var ret = "Name: " + this.name;
  22816. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22817. if (this.animations) {
  22818. for (var i = 0; i < this.animations.length; i++) {
  22819. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22820. }
  22821. }
  22822. if (fullDetails) {
  22823. }
  22824. return ret;
  22825. };
  22826. /** @hidden */
  22827. Light.prototype._syncParentEnabledState = function () {
  22828. _super.prototype._syncParentEnabledState.call(this);
  22829. this._resyncMeshes();
  22830. };
  22831. /**
  22832. * Set the enabled state of this node.
  22833. * @param value - the new enabled state
  22834. */
  22835. Light.prototype.setEnabled = function (value) {
  22836. _super.prototype.setEnabled.call(this, value);
  22837. this._resyncMeshes();
  22838. };
  22839. /**
  22840. * Returns the Light associated shadow generator if any.
  22841. * @return the associated shadow generator.
  22842. */
  22843. Light.prototype.getShadowGenerator = function () {
  22844. return this._shadowGenerator;
  22845. };
  22846. /**
  22847. * Returns a Vector3, the absolute light position in the World.
  22848. * @returns the world space position of the light
  22849. */
  22850. Light.prototype.getAbsolutePosition = function () {
  22851. return BABYLON.Vector3.Zero();
  22852. };
  22853. /**
  22854. * Specifies if the light will affect the passed mesh.
  22855. * @param mesh The mesh to test against the light
  22856. * @return true the mesh is affected otherwise, false.
  22857. */
  22858. Light.prototype.canAffectMesh = function (mesh) {
  22859. if (!mesh) {
  22860. return true;
  22861. }
  22862. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22863. return false;
  22864. }
  22865. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22866. return false;
  22867. }
  22868. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22869. return false;
  22870. }
  22871. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22872. return false;
  22873. }
  22874. return true;
  22875. };
  22876. /**
  22877. * Sort function to order lights for rendering.
  22878. * @param a First Light object to compare to second.
  22879. * @param b Second Light object to compare first.
  22880. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22881. */
  22882. Light.CompareLightsPriority = function (a, b) {
  22883. //shadow-casting lights have priority over non-shadow-casting lights
  22884. //the renderPrioirty is a secondary sort criterion
  22885. if (a.shadowEnabled !== b.shadowEnabled) {
  22886. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22887. }
  22888. return b.renderPriority - a.renderPriority;
  22889. };
  22890. /**
  22891. * Releases resources associated with this node.
  22892. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22893. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22894. */
  22895. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22896. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22897. if (this._shadowGenerator) {
  22898. this._shadowGenerator.dispose();
  22899. this._shadowGenerator = null;
  22900. }
  22901. // Animations
  22902. this.getScene().stopAnimation(this);
  22903. // Remove from meshes
  22904. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22905. var mesh = _a[_i];
  22906. mesh._removeLightSource(this);
  22907. }
  22908. this._uniformBuffer.dispose();
  22909. // Remove from scene
  22910. this.getScene().removeLight(this);
  22911. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22912. };
  22913. /**
  22914. * Returns the light type ID (integer).
  22915. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22916. */
  22917. Light.prototype.getTypeID = function () {
  22918. return 0;
  22919. };
  22920. /**
  22921. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22922. * @returns the scaled intensity in intensity mode unit
  22923. */
  22924. Light.prototype.getScaledIntensity = function () {
  22925. return this._photometricScale * this.intensity;
  22926. };
  22927. /**
  22928. * Returns a new Light object, named "name", from the current one.
  22929. * @param name The name of the cloned light
  22930. * @returns the new created light
  22931. */
  22932. Light.prototype.clone = function (name) {
  22933. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22934. if (!constructor) {
  22935. return null;
  22936. }
  22937. return BABYLON.SerializationHelper.Clone(constructor, this);
  22938. };
  22939. /**
  22940. * Serializes the current light into a Serialization object.
  22941. * @returns the serialized object.
  22942. */
  22943. Light.prototype.serialize = function () {
  22944. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22945. // Type
  22946. serializationObject.type = this.getTypeID();
  22947. // Parent
  22948. if (this.parent) {
  22949. serializationObject.parentId = this.parent.id;
  22950. }
  22951. // Inclusion / exclusions
  22952. if (this.excludedMeshes.length > 0) {
  22953. serializationObject.excludedMeshesIds = [];
  22954. this.excludedMeshes.forEach(function (mesh) {
  22955. serializationObject.excludedMeshesIds.push(mesh.id);
  22956. });
  22957. }
  22958. if (this.includedOnlyMeshes.length > 0) {
  22959. serializationObject.includedOnlyMeshesIds = [];
  22960. this.includedOnlyMeshes.forEach(function (mesh) {
  22961. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22962. });
  22963. }
  22964. // Animations
  22965. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22966. serializationObject.ranges = this.serializeAnimationRanges();
  22967. return serializationObject;
  22968. };
  22969. /**
  22970. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22971. * This new light is named "name" and added to the passed scene.
  22972. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22973. * @param name The friendly name of the light
  22974. * @param scene The scene the new light will belong to
  22975. * @returns the constructor function
  22976. */
  22977. Light.GetConstructorFromName = function (type, name, scene) {
  22978. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22979. if (constructorFunc) {
  22980. return constructorFunc;
  22981. }
  22982. // Default to no light for none present once.
  22983. return null;
  22984. };
  22985. /**
  22986. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22987. * @param parsedLight The JSON representation of the light
  22988. * @param scene The scene to create the parsed light in
  22989. * @returns the created light after parsing
  22990. */
  22991. Light.Parse = function (parsedLight, scene) {
  22992. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22993. if (!constructor) {
  22994. return null;
  22995. }
  22996. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22997. // Inclusion / exclusions
  22998. if (parsedLight.excludedMeshesIds) {
  22999. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  23000. }
  23001. if (parsedLight.includedOnlyMeshesIds) {
  23002. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  23003. }
  23004. // Parent
  23005. if (parsedLight.parentId) {
  23006. light._waitingParentId = parsedLight.parentId;
  23007. }
  23008. // Animations
  23009. if (parsedLight.animations) {
  23010. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  23011. var parsedAnimation = parsedLight.animations[animationIndex];
  23012. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23013. }
  23014. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  23015. }
  23016. if (parsedLight.autoAnimate) {
  23017. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  23018. }
  23019. return light;
  23020. };
  23021. Light.prototype._hookArrayForExcluded = function (array) {
  23022. var _this = this;
  23023. var oldPush = array.push;
  23024. array.push = function () {
  23025. var items = [];
  23026. for (var _i = 0; _i < arguments.length; _i++) {
  23027. items[_i] = arguments[_i];
  23028. }
  23029. var result = oldPush.apply(array, items);
  23030. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  23031. var item = items_1[_a];
  23032. item._resyncLighSource(_this);
  23033. }
  23034. return result;
  23035. };
  23036. var oldSplice = array.splice;
  23037. array.splice = function (index, deleteCount) {
  23038. var deleted = oldSplice.apply(array, [index, deleteCount]);
  23039. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  23040. var item = deleted_1[_i];
  23041. item._resyncLighSource(_this);
  23042. }
  23043. return deleted;
  23044. };
  23045. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  23046. var item = array_1[_i];
  23047. item._resyncLighSource(this);
  23048. }
  23049. };
  23050. Light.prototype._hookArrayForIncludedOnly = 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. _this._resyncMeshes();
  23060. return result;
  23061. };
  23062. var oldSplice = array.splice;
  23063. array.splice = function (index, deleteCount) {
  23064. var deleted = oldSplice.apply(array, [index, deleteCount]);
  23065. _this._resyncMeshes();
  23066. return deleted;
  23067. };
  23068. this._resyncMeshes();
  23069. };
  23070. Light.prototype._resyncMeshes = function () {
  23071. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23072. var mesh = _a[_i];
  23073. mesh._resyncLighSource(this);
  23074. }
  23075. };
  23076. /**
  23077. * Forces the meshes to update their light related information in their rendering used effects
  23078. * @hidden Internal Use Only
  23079. */
  23080. Light.prototype._markMeshesAsLightDirty = function () {
  23081. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23082. var mesh = _a[_i];
  23083. if (mesh._lightSources.indexOf(this) !== -1) {
  23084. mesh._markSubMeshesAsLightDirty();
  23085. }
  23086. }
  23087. };
  23088. /**
  23089. * Recomputes the cached photometric scale if needed.
  23090. */
  23091. Light.prototype._computePhotometricScale = function () {
  23092. this._photometricScale = this._getPhotometricScale();
  23093. this.getScene().resetCachedMaterial();
  23094. };
  23095. /**
  23096. * Returns the Photometric Scale according to the light type and intensity mode.
  23097. */
  23098. Light.prototype._getPhotometricScale = function () {
  23099. var photometricScale = 0.0;
  23100. var lightTypeID = this.getTypeID();
  23101. //get photometric mode
  23102. var photometricMode = this.intensityMode;
  23103. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  23104. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  23105. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  23106. }
  23107. else {
  23108. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  23109. }
  23110. }
  23111. //compute photometric scale
  23112. switch (lightTypeID) {
  23113. case Light.LIGHTTYPEID_POINTLIGHT:
  23114. case Light.LIGHTTYPEID_SPOTLIGHT:
  23115. switch (photometricMode) {
  23116. case Light.INTENSITYMODE_LUMINOUSPOWER:
  23117. photometricScale = 1.0 / (4.0 * Math.PI);
  23118. break;
  23119. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  23120. photometricScale = 1.0;
  23121. break;
  23122. case Light.INTENSITYMODE_LUMINANCE:
  23123. photometricScale = this.radius * this.radius;
  23124. break;
  23125. }
  23126. break;
  23127. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  23128. switch (photometricMode) {
  23129. case Light.INTENSITYMODE_ILLUMINANCE:
  23130. photometricScale = 1.0;
  23131. break;
  23132. case Light.INTENSITYMODE_LUMINANCE:
  23133. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  23134. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  23135. var apexAngleRadians = this.radius;
  23136. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  23137. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  23138. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  23139. photometricScale = solidAngle;
  23140. break;
  23141. }
  23142. break;
  23143. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  23144. // No fall off in hemisperic light.
  23145. photometricScale = 1.0;
  23146. break;
  23147. }
  23148. return photometricScale;
  23149. };
  23150. /**
  23151. * Reorder the light in the scene according to their defined priority.
  23152. * @hidden Internal Use Only
  23153. */
  23154. Light.prototype._reorderLightsInScene = function () {
  23155. var scene = this.getScene();
  23156. if (this._renderPriority != 0) {
  23157. scene.requireLightSorting = true;
  23158. }
  23159. this.getScene().sortLightsByPriority();
  23160. };
  23161. /**
  23162. * Falloff Default: light is falling off following the material specification:
  23163. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  23164. */
  23165. Light.FALLOFF_DEFAULT = 0;
  23166. /**
  23167. * Falloff Physical: light is falling off following the inverse squared distance law.
  23168. */
  23169. Light.FALLOFF_PHYSICAL = 1;
  23170. /**
  23171. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  23172. * to enhance interoperability with other engines.
  23173. */
  23174. Light.FALLOFF_GLTF = 2;
  23175. /**
  23176. * Falloff Standard: light is falling off like in the standard material
  23177. * to enhance interoperability with other materials.
  23178. */
  23179. Light.FALLOFF_STANDARD = 3;
  23180. //lightmapMode Consts
  23181. /**
  23182. * If every light affecting the material is in this lightmapMode,
  23183. * material.lightmapTexture adds or multiplies
  23184. * (depends on material.useLightmapAsShadowmap)
  23185. * after every other light calculations.
  23186. */
  23187. Light.LIGHTMAP_DEFAULT = 0;
  23188. /**
  23189. * material.lightmapTexture as only diffuse lighting from this light
  23190. * adds only specular lighting from this light
  23191. * adds dynamic shadows
  23192. */
  23193. Light.LIGHTMAP_SPECULAR = 1;
  23194. /**
  23195. * material.lightmapTexture as only lighting
  23196. * no light calculation from this light
  23197. * only adds dynamic shadows from this light
  23198. */
  23199. Light.LIGHTMAP_SHADOWSONLY = 2;
  23200. // Intensity Mode Consts
  23201. /**
  23202. * Each light type uses the default quantity according to its type:
  23203. * point/spot lights use luminous intensity
  23204. * directional lights use illuminance
  23205. */
  23206. Light.INTENSITYMODE_AUTOMATIC = 0;
  23207. /**
  23208. * lumen (lm)
  23209. */
  23210. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  23211. /**
  23212. * candela (lm/sr)
  23213. */
  23214. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  23215. /**
  23216. * lux (lm/m^2)
  23217. */
  23218. Light.INTENSITYMODE_ILLUMINANCE = 3;
  23219. /**
  23220. * nit (cd/m^2)
  23221. */
  23222. Light.INTENSITYMODE_LUMINANCE = 4;
  23223. // Light types ids const.
  23224. /**
  23225. * Light type const id of the point light.
  23226. */
  23227. Light.LIGHTTYPEID_POINTLIGHT = 0;
  23228. /**
  23229. * Light type const id of the directional light.
  23230. */
  23231. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  23232. /**
  23233. * Light type const id of the spot light.
  23234. */
  23235. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  23236. /**
  23237. * Light type const id of the hemispheric light.
  23238. */
  23239. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  23240. __decorate([
  23241. BABYLON.serializeAsColor3()
  23242. ], Light.prototype, "diffuse", void 0);
  23243. __decorate([
  23244. BABYLON.serializeAsColor3()
  23245. ], Light.prototype, "specular", void 0);
  23246. __decorate([
  23247. BABYLON.serialize()
  23248. ], Light.prototype, "falloffType", void 0);
  23249. __decorate([
  23250. BABYLON.serialize()
  23251. ], Light.prototype, "intensity", void 0);
  23252. __decorate([
  23253. BABYLON.serialize()
  23254. ], Light.prototype, "range", null);
  23255. __decorate([
  23256. BABYLON.serialize()
  23257. ], Light.prototype, "intensityMode", null);
  23258. __decorate([
  23259. BABYLON.serialize()
  23260. ], Light.prototype, "radius", null);
  23261. __decorate([
  23262. BABYLON.serialize()
  23263. ], Light.prototype, "_renderPriority", void 0);
  23264. __decorate([
  23265. BABYLON.expandToProperty("_reorderLightsInScene")
  23266. ], Light.prototype, "renderPriority", void 0);
  23267. __decorate([
  23268. BABYLON.serialize("shadowEnabled")
  23269. ], Light.prototype, "_shadowEnabled", void 0);
  23270. __decorate([
  23271. BABYLON.serialize("excludeWithLayerMask")
  23272. ], Light.prototype, "_excludeWithLayerMask", void 0);
  23273. __decorate([
  23274. BABYLON.serialize("includeOnlyWithLayerMask")
  23275. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  23276. __decorate([
  23277. BABYLON.serialize("lightmapMode")
  23278. ], Light.prototype, "_lightmapMode", void 0);
  23279. return Light;
  23280. }(BABYLON.Node));
  23281. BABYLON.Light = Light;
  23282. })(BABYLON || (BABYLON = {}));
  23283. //# sourceMappingURL=babylon.light.js.map
  23284. var BABYLON;
  23285. (function (BABYLON) {
  23286. /**
  23287. * This is the base class of all the camera used in the application.
  23288. * @see http://doc.babylonjs.com/features/cameras
  23289. */
  23290. var Camera = /** @class */ (function (_super) {
  23291. __extends(Camera, _super);
  23292. /**
  23293. * Instantiates a new camera object.
  23294. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  23295. * @see http://doc.babylonjs.com/features/cameras
  23296. * @param name Defines the name of the camera in the scene
  23297. * @param position Defines the position of the camera
  23298. * @param scene Defines the scene the camera belongs too
  23299. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  23300. */
  23301. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  23302. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  23303. var _this = _super.call(this, name, scene) || this;
  23304. /**
  23305. * The vector the camera should consider as up.
  23306. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  23307. */
  23308. _this.upVector = BABYLON.Vector3.Up();
  23309. /**
  23310. * Define the current limit on the left side for an orthographic camera
  23311. * In scene unit
  23312. */
  23313. _this.orthoLeft = null;
  23314. /**
  23315. * Define the current limit on the right side for an orthographic camera
  23316. * In scene unit
  23317. */
  23318. _this.orthoRight = null;
  23319. /**
  23320. * Define the current limit on the bottom side for an orthographic camera
  23321. * In scene unit
  23322. */
  23323. _this.orthoBottom = null;
  23324. /**
  23325. * Define the current limit on the top side for an orthographic camera
  23326. * In scene unit
  23327. */
  23328. _this.orthoTop = null;
  23329. /**
  23330. * Field Of View is set in Radians. (default is 0.8)
  23331. */
  23332. _this.fov = 0.8;
  23333. /**
  23334. * Define the minimum distance the camera can see from.
  23335. * This is important to note that the depth buffer are not infinite and the closer it starts
  23336. * the more your scene might encounter depth fighting issue.
  23337. */
  23338. _this.minZ = 1;
  23339. /**
  23340. * Define the maximum distance the camera can see to.
  23341. * This is important to note that the depth buffer are not infinite and the further it end
  23342. * the more your scene might encounter depth fighting issue.
  23343. */
  23344. _this.maxZ = 10000.0;
  23345. /**
  23346. * Define the default inertia of the camera.
  23347. * This helps giving a smooth feeling to the camera movement.
  23348. */
  23349. _this.inertia = 0.9;
  23350. /**
  23351. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23352. */
  23353. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23354. /**
  23355. * Define wether the camera is intermediate.
  23356. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  23357. */
  23358. _this.isIntermediate = false;
  23359. /**
  23360. * Define the viewport of the camera.
  23361. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23362. */
  23363. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23364. /**
  23365. * Restricts the camera to viewing objects with the same layerMask.
  23366. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23367. */
  23368. _this.layerMask = 0x0FFFFFFF;
  23369. /**
  23370. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23371. */
  23372. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23373. /**
  23374. * Rig mode of the camera.
  23375. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23376. * This is normally controlled byt the camera themselves as internal use.
  23377. */
  23378. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23379. /**
  23380. * 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
  23381. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23382. * else in the scene.
  23383. */
  23384. _this.customRenderTargets = new Array();
  23385. /**
  23386. * When set, the camera will render to this render target instead of the default canvas
  23387. */
  23388. _this.outputRenderTarget = null;
  23389. /**
  23390. * Observable triggered when the camera view matrix has changed.
  23391. */
  23392. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23393. /**
  23394. * Observable triggered when the camera Projection matrix has changed.
  23395. */
  23396. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23397. /**
  23398. * Observable triggered when the inputs have been processed.
  23399. */
  23400. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23401. /**
  23402. * Observable triggered when reset has been called and applied to the camera.
  23403. */
  23404. _this.onRestoreStateObservable = new BABYLON.Observable();
  23405. /** @hidden */
  23406. _this._rigCameras = new Array();
  23407. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23408. /** @hidden */
  23409. _this._skipRendering = false;
  23410. /** @hidden */
  23411. _this._projectionMatrix = new BABYLON.Matrix();
  23412. /** @hidden */
  23413. _this._postProcesses = new Array();
  23414. /** @hidden */
  23415. _this._activeMeshes = new BABYLON.SmartArray(256);
  23416. _this._globalPosition = BABYLON.Vector3.Zero();
  23417. /** hidden */
  23418. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23419. _this._doNotComputeProjectionMatrix = false;
  23420. _this._transformMatrix = BABYLON.Matrix.Zero();
  23421. _this._refreshFrustumPlanes = true;
  23422. _this.getScene().addCamera(_this);
  23423. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23424. _this.getScene().activeCamera = _this;
  23425. }
  23426. _this.position = position;
  23427. return _this;
  23428. }
  23429. /**
  23430. * Store current camera state (fov, position, etc..)
  23431. * @returns the camera
  23432. */
  23433. Camera.prototype.storeState = function () {
  23434. this._stateStored = true;
  23435. this._storedFov = this.fov;
  23436. return this;
  23437. };
  23438. /**
  23439. * Restores the camera state values if it has been stored. You must call storeState() first
  23440. */
  23441. Camera.prototype._restoreStateValues = function () {
  23442. if (!this._stateStored) {
  23443. return false;
  23444. }
  23445. this.fov = this._storedFov;
  23446. return true;
  23447. };
  23448. /**
  23449. * Restored camera state. You must call storeState() first.
  23450. * @returns true if restored and false otherwise
  23451. */
  23452. Camera.prototype.restoreState = function () {
  23453. if (this._restoreStateValues()) {
  23454. this.onRestoreStateObservable.notifyObservers(this);
  23455. return true;
  23456. }
  23457. return false;
  23458. };
  23459. /**
  23460. * Gets the class name of the camera.
  23461. * @returns the class name
  23462. */
  23463. Camera.prototype.getClassName = function () {
  23464. return "Camera";
  23465. };
  23466. /**
  23467. * Gets a string representation of the camera usefull for debug purpose.
  23468. * @param fullDetails Defines that a more verboe level of logging is required
  23469. * @returns the string representation
  23470. */
  23471. Camera.prototype.toString = function (fullDetails) {
  23472. var ret = "Name: " + this.name;
  23473. ret += ", type: " + this.getClassName();
  23474. if (this.animations) {
  23475. for (var i = 0; i < this.animations.length; i++) {
  23476. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23477. }
  23478. }
  23479. if (fullDetails) {
  23480. }
  23481. return ret;
  23482. };
  23483. Object.defineProperty(Camera.prototype, "globalPosition", {
  23484. /**
  23485. * Gets the current world space position of the camera.
  23486. */
  23487. get: function () {
  23488. return this._globalPosition;
  23489. },
  23490. enumerable: true,
  23491. configurable: true
  23492. });
  23493. /**
  23494. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23495. * @returns the active meshe list
  23496. */
  23497. Camera.prototype.getActiveMeshes = function () {
  23498. return this._activeMeshes;
  23499. };
  23500. /**
  23501. * Check wether a mesh is part of the current active mesh list of the camera
  23502. * @param mesh Defines the mesh to check
  23503. * @returns true if active, false otherwise
  23504. */
  23505. Camera.prototype.isActiveMesh = function (mesh) {
  23506. return (this._activeMeshes.indexOf(mesh) !== -1);
  23507. };
  23508. /**
  23509. * Is this camera ready to be used/rendered
  23510. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23511. * @return true if the camera is ready
  23512. */
  23513. Camera.prototype.isReady = function (completeCheck) {
  23514. if (completeCheck === void 0) { completeCheck = false; }
  23515. if (completeCheck) {
  23516. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23517. var pp = _a[_i];
  23518. if (pp && !pp.isReady()) {
  23519. return false;
  23520. }
  23521. }
  23522. }
  23523. return _super.prototype.isReady.call(this, completeCheck);
  23524. };
  23525. /** @hidden */
  23526. Camera.prototype._initCache = function () {
  23527. _super.prototype._initCache.call(this);
  23528. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23529. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23530. this._cache.mode = undefined;
  23531. this._cache.minZ = undefined;
  23532. this._cache.maxZ = undefined;
  23533. this._cache.fov = undefined;
  23534. this._cache.fovMode = undefined;
  23535. this._cache.aspectRatio = undefined;
  23536. this._cache.orthoLeft = undefined;
  23537. this._cache.orthoRight = undefined;
  23538. this._cache.orthoBottom = undefined;
  23539. this._cache.orthoTop = undefined;
  23540. this._cache.renderWidth = undefined;
  23541. this._cache.renderHeight = undefined;
  23542. };
  23543. /** @hidden */
  23544. Camera.prototype._updateCache = function (ignoreParentClass) {
  23545. if (!ignoreParentClass) {
  23546. _super.prototype._updateCache.call(this);
  23547. }
  23548. this._cache.position.copyFrom(this.position);
  23549. this._cache.upVector.copyFrom(this.upVector);
  23550. };
  23551. /** @hidden */
  23552. Camera.prototype._isSynchronized = function () {
  23553. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23554. };
  23555. /** @hidden */
  23556. Camera.prototype._isSynchronizedViewMatrix = function () {
  23557. if (!_super.prototype._isSynchronized.call(this)) {
  23558. return false;
  23559. }
  23560. return this._cache.position.equals(this.position)
  23561. && this._cache.upVector.equals(this.upVector)
  23562. && this.isSynchronizedWithParent();
  23563. };
  23564. /** @hidden */
  23565. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23566. var check = this._cache.mode === this.mode
  23567. && this._cache.minZ === this.minZ
  23568. && this._cache.maxZ === this.maxZ;
  23569. if (!check) {
  23570. return false;
  23571. }
  23572. var engine = this.getEngine();
  23573. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23574. check = this._cache.fov === this.fov
  23575. && this._cache.fovMode === this.fovMode
  23576. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23577. }
  23578. else {
  23579. check = this._cache.orthoLeft === this.orthoLeft
  23580. && this._cache.orthoRight === this.orthoRight
  23581. && this._cache.orthoBottom === this.orthoBottom
  23582. && this._cache.orthoTop === this.orthoTop
  23583. && this._cache.renderWidth === engine.getRenderWidth()
  23584. && this._cache.renderHeight === engine.getRenderHeight();
  23585. }
  23586. return check;
  23587. };
  23588. /**
  23589. * Attach the input controls to a specific dom element to get the input from.
  23590. * @param element Defines the element the controls should be listened from
  23591. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23592. */
  23593. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23594. };
  23595. /**
  23596. * Detach the current controls from the specified dom element.
  23597. * @param element Defines the element to stop listening the inputs from
  23598. */
  23599. Camera.prototype.detachControl = function (element) {
  23600. };
  23601. /**
  23602. * Update the camera state according to the different inputs gathered during the frame.
  23603. */
  23604. Camera.prototype.update = function () {
  23605. this._checkInputs();
  23606. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23607. this._updateRigCameras();
  23608. }
  23609. };
  23610. /** @hidden */
  23611. Camera.prototype._checkInputs = function () {
  23612. this.onAfterCheckInputsObservable.notifyObservers(this);
  23613. };
  23614. Object.defineProperty(Camera.prototype, "rigCameras", {
  23615. /** @hidden */
  23616. get: function () {
  23617. return this._rigCameras;
  23618. },
  23619. enumerable: true,
  23620. configurable: true
  23621. });
  23622. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23623. /**
  23624. * Gets the post process used by the rig cameras
  23625. */
  23626. get: function () {
  23627. return this._rigPostProcess;
  23628. },
  23629. enumerable: true,
  23630. configurable: true
  23631. });
  23632. /**
  23633. * Internal, gets the first post proces.
  23634. * @returns the first post process to be run on this camera.
  23635. */
  23636. Camera.prototype._getFirstPostProcess = function () {
  23637. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23638. if (this._postProcesses[ppIndex] !== null) {
  23639. return this._postProcesses[ppIndex];
  23640. }
  23641. }
  23642. return null;
  23643. };
  23644. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23645. // invalidate framebuffer
  23646. var firstPostProcess = this._getFirstPostProcess();
  23647. if (firstPostProcess) {
  23648. firstPostProcess.markTextureDirty();
  23649. }
  23650. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23651. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23652. var cam = this._rigCameras[i];
  23653. var rigPostProcess = cam._rigPostProcess;
  23654. // for VR rig, there does not have to be a post process
  23655. if (rigPostProcess) {
  23656. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23657. if (isPass) {
  23658. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23659. cam.isIntermediate = this._postProcesses.length === 0;
  23660. }
  23661. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23662. rigPostProcess.markTextureDirty();
  23663. }
  23664. else {
  23665. cam._postProcesses = this._postProcesses.slice(0);
  23666. }
  23667. }
  23668. };
  23669. /**
  23670. * Attach a post process to the camera.
  23671. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23672. * @param postProcess The post process to attach to the camera
  23673. * @param insertAt The position of the post process in case several of them are in use in the scene
  23674. * @returns the position the post process has been inserted at
  23675. */
  23676. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23677. if (insertAt === void 0) { insertAt = null; }
  23678. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23679. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23680. return 0;
  23681. }
  23682. if (insertAt == null || insertAt < 0) {
  23683. this._postProcesses.push(postProcess);
  23684. }
  23685. else if (this._postProcesses[insertAt] === null) {
  23686. this._postProcesses[insertAt] = postProcess;
  23687. }
  23688. else {
  23689. this._postProcesses.splice(insertAt, 0, postProcess);
  23690. }
  23691. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23692. return this._postProcesses.indexOf(postProcess);
  23693. };
  23694. /**
  23695. * Detach a post process to the camera.
  23696. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23697. * @param postProcess The post process to detach from the camera
  23698. */
  23699. Camera.prototype.detachPostProcess = function (postProcess) {
  23700. var idx = this._postProcesses.indexOf(postProcess);
  23701. if (idx !== -1) {
  23702. this._postProcesses[idx] = null;
  23703. }
  23704. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23705. };
  23706. /**
  23707. * Gets the current world matrix of the camera
  23708. */
  23709. Camera.prototype.getWorldMatrix = function () {
  23710. if (this._isSynchronizedViewMatrix()) {
  23711. return this._worldMatrix;
  23712. }
  23713. // Getting the the view matrix will also compute the world matrix.
  23714. this.getViewMatrix();
  23715. return this._worldMatrix;
  23716. };
  23717. /** @hidden */
  23718. Camera.prototype._getViewMatrix = function () {
  23719. return BABYLON.Matrix.Identity();
  23720. };
  23721. /**
  23722. * Gets the current view matrix of the camera.
  23723. * @param force forces the camera to recompute the matrix without looking at the cached state
  23724. * @returns the view matrix
  23725. */
  23726. Camera.prototype.getViewMatrix = function (force) {
  23727. if (!force && this._isSynchronizedViewMatrix()) {
  23728. return this._computedViewMatrix;
  23729. }
  23730. this.updateCache();
  23731. this._computedViewMatrix = this._getViewMatrix();
  23732. this._currentRenderId = this.getScene().getRenderId();
  23733. this._childRenderId = this._currentRenderId;
  23734. this._refreshFrustumPlanes = true;
  23735. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23736. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23737. }
  23738. this.onViewMatrixChangedObservable.notifyObservers(this);
  23739. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23740. return this._computedViewMatrix;
  23741. };
  23742. /**
  23743. * Freeze the projection matrix.
  23744. * It will prevent the cache check of the camera projection compute and can speed up perf
  23745. * if no parameter of the camera are meant to change
  23746. * @param projection Defines manually a projection if necessary
  23747. */
  23748. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23749. this._doNotComputeProjectionMatrix = true;
  23750. if (projection !== undefined) {
  23751. this._projectionMatrix = projection;
  23752. }
  23753. };
  23754. /**
  23755. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23756. */
  23757. Camera.prototype.unfreezeProjectionMatrix = function () {
  23758. this._doNotComputeProjectionMatrix = false;
  23759. };
  23760. /**
  23761. * Gets the current projection matrix of the camera.
  23762. * @param force forces the camera to recompute the matrix without looking at the cached state
  23763. * @returns the projection matrix
  23764. */
  23765. Camera.prototype.getProjectionMatrix = function (force) {
  23766. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23767. return this._projectionMatrix;
  23768. }
  23769. // Cache
  23770. this._cache.mode = this.mode;
  23771. this._cache.minZ = this.minZ;
  23772. this._cache.maxZ = this.maxZ;
  23773. // Matrix
  23774. this._refreshFrustumPlanes = true;
  23775. var engine = this.getEngine();
  23776. var scene = this.getScene();
  23777. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23778. this._cache.fov = this.fov;
  23779. this._cache.fovMode = this.fovMode;
  23780. this._cache.aspectRatio = engine.getAspectRatio(this);
  23781. if (this.minZ <= 0) {
  23782. this.minZ = 0.1;
  23783. }
  23784. if (scene.useRightHandedSystem) {
  23785. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23786. }
  23787. else {
  23788. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23789. }
  23790. }
  23791. else {
  23792. var halfWidth = engine.getRenderWidth() / 2.0;
  23793. var halfHeight = engine.getRenderHeight() / 2.0;
  23794. if (scene.useRightHandedSystem) {
  23795. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23796. }
  23797. else {
  23798. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23799. }
  23800. this._cache.orthoLeft = this.orthoLeft;
  23801. this._cache.orthoRight = this.orthoRight;
  23802. this._cache.orthoBottom = this.orthoBottom;
  23803. this._cache.orthoTop = this.orthoTop;
  23804. this._cache.renderWidth = engine.getRenderWidth();
  23805. this._cache.renderHeight = engine.getRenderHeight();
  23806. }
  23807. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23808. return this._projectionMatrix;
  23809. };
  23810. /**
  23811. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23812. * @returns a Matrix
  23813. */
  23814. Camera.prototype.getTransformationMatrix = function () {
  23815. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23816. return this._transformMatrix;
  23817. };
  23818. Camera.prototype._updateFrustumPlanes = function () {
  23819. if (!this._refreshFrustumPlanes) {
  23820. return;
  23821. }
  23822. this.getTransformationMatrix();
  23823. if (!this._frustumPlanes) {
  23824. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23825. }
  23826. else {
  23827. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23828. }
  23829. this._refreshFrustumPlanes = false;
  23830. };
  23831. /**
  23832. * Checks if a cullable object (mesh...) is in the camera frustum
  23833. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23834. * @param target The object to check
  23835. * @returns true if the object is in frustum otherwise false
  23836. */
  23837. Camera.prototype.isInFrustum = function (target) {
  23838. this._updateFrustumPlanes();
  23839. return target.isInFrustum(this._frustumPlanes);
  23840. };
  23841. /**
  23842. * Checks if a cullable object (mesh...) is in the camera frustum
  23843. * Unlike isInFrustum this cheks the full bounding box
  23844. * @param target The object to check
  23845. * @returns true if the object is in frustum otherwise false
  23846. */
  23847. Camera.prototype.isCompletelyInFrustum = function (target) {
  23848. this._updateFrustumPlanes();
  23849. return target.isCompletelyInFrustum(this._frustumPlanes);
  23850. };
  23851. /**
  23852. * Gets a ray in the forward direction from the camera.
  23853. * @param length Defines the length of the ray to create
  23854. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23855. * @param origin Defines the start point of the ray which defaults to the camera position
  23856. * @returns the forward ray
  23857. */
  23858. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23859. if (length === void 0) { length = 100; }
  23860. if (!transform) {
  23861. transform = this.getWorldMatrix();
  23862. }
  23863. if (!origin) {
  23864. origin = this.position;
  23865. }
  23866. var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
  23867. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23868. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23869. return new BABYLON.Ray(origin, direction, length);
  23870. };
  23871. /**
  23872. * Releases resources associated with this node.
  23873. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23874. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23875. */
  23876. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23877. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23878. // Observables
  23879. this.onViewMatrixChangedObservable.clear();
  23880. this.onProjectionMatrixChangedObservable.clear();
  23881. this.onAfterCheckInputsObservable.clear();
  23882. this.onRestoreStateObservable.clear();
  23883. // Inputs
  23884. if (this.inputs) {
  23885. this.inputs.clear();
  23886. }
  23887. // Animations
  23888. this.getScene().stopAnimation(this);
  23889. // Remove from scene
  23890. this.getScene().removeCamera(this);
  23891. while (this._rigCameras.length > 0) {
  23892. var camera = this._rigCameras.pop();
  23893. if (camera) {
  23894. camera.dispose();
  23895. }
  23896. }
  23897. // Postprocesses
  23898. if (this._rigPostProcess) {
  23899. this._rigPostProcess.dispose(this);
  23900. this._rigPostProcess = null;
  23901. this._postProcesses = [];
  23902. }
  23903. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23904. this._rigPostProcess = null;
  23905. this._postProcesses = [];
  23906. }
  23907. else {
  23908. var i = this._postProcesses.length;
  23909. while (--i >= 0) {
  23910. var postProcess = this._postProcesses[i];
  23911. if (postProcess) {
  23912. postProcess.dispose(this);
  23913. }
  23914. }
  23915. }
  23916. // Render targets
  23917. var i = this.customRenderTargets.length;
  23918. while (--i >= 0) {
  23919. this.customRenderTargets[i].dispose();
  23920. }
  23921. this.customRenderTargets = [];
  23922. // Active Meshes
  23923. this._activeMeshes.dispose();
  23924. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23925. };
  23926. Object.defineProperty(Camera.prototype, "leftCamera", {
  23927. /**
  23928. * Gets the left camera of a rig setup in case of Rigged Camera
  23929. */
  23930. get: function () {
  23931. if (this._rigCameras.length < 1) {
  23932. return null;
  23933. }
  23934. return this._rigCameras[0];
  23935. },
  23936. enumerable: true,
  23937. configurable: true
  23938. });
  23939. Object.defineProperty(Camera.prototype, "rightCamera", {
  23940. /**
  23941. * Gets the right camera of a rig setup in case of Rigged Camera
  23942. */
  23943. get: function () {
  23944. if (this._rigCameras.length < 2) {
  23945. return null;
  23946. }
  23947. return this._rigCameras[1];
  23948. },
  23949. enumerable: true,
  23950. configurable: true
  23951. });
  23952. /**
  23953. * Gets the left camera target of a rig setup in case of Rigged Camera
  23954. * @returns the target position
  23955. */
  23956. Camera.prototype.getLeftTarget = function () {
  23957. if (this._rigCameras.length < 1) {
  23958. return null;
  23959. }
  23960. return this._rigCameras[0].getTarget();
  23961. };
  23962. /**
  23963. * Gets the right camera target of a rig setup in case of Rigged Camera
  23964. * @returns the target position
  23965. */
  23966. Camera.prototype.getRightTarget = function () {
  23967. if (this._rigCameras.length < 2) {
  23968. return null;
  23969. }
  23970. return this._rigCameras[1].getTarget();
  23971. };
  23972. /**
  23973. * @hidden
  23974. */
  23975. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23976. if (this.cameraRigMode === mode) {
  23977. return;
  23978. }
  23979. while (this._rigCameras.length > 0) {
  23980. var camera = this._rigCameras.pop();
  23981. if (camera) {
  23982. camera.dispose();
  23983. }
  23984. }
  23985. this.cameraRigMode = mode;
  23986. this._cameraRigParams = {};
  23987. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23988. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23989. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23990. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23991. // create the rig cameras, unless none
  23992. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23993. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23994. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23995. if (leftCamera && rightCamera) {
  23996. this._rigCameras.push(leftCamera);
  23997. this._rigCameras.push(rightCamera);
  23998. }
  23999. }
  24000. switch (this.cameraRigMode) {
  24001. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  24002. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  24003. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  24004. break;
  24005. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  24006. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  24007. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  24008. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  24009. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  24010. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  24011. break;
  24012. case Camera.RIG_MODE_VR:
  24013. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  24014. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  24015. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  24016. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24017. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  24018. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  24019. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  24020. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  24021. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  24022. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24023. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  24024. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  24025. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  24026. if (metrics.compensateDistortion) {
  24027. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  24028. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  24029. }
  24030. break;
  24031. case Camera.RIG_MODE_WEBVR:
  24032. if (rigParams.vrDisplay) {
  24033. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  24034. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  24035. //Left eye
  24036. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  24037. this._rigCameras[0].setCameraRigParameter("left", true);
  24038. //leaving this for future reference
  24039. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  24040. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  24041. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  24042. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  24043. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24044. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  24045. this._rigCameras[0].parent = this;
  24046. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  24047. //Right eye
  24048. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  24049. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  24050. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  24051. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  24052. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  24053. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24054. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  24055. this._rigCameras[1].parent = this;
  24056. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  24057. if (Camera.UseAlternateWebVRRendering) {
  24058. this._rigCameras[1]._skipRendering = true;
  24059. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  24060. }
  24061. }
  24062. break;
  24063. }
  24064. this._cascadePostProcessesToRigCams();
  24065. this.update();
  24066. };
  24067. Camera.prototype._getVRProjectionMatrix = function () {
  24068. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  24069. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  24070. return this._projectionMatrix;
  24071. };
  24072. Camera.prototype._updateCameraRotationMatrix = function () {
  24073. //Here for WebVR
  24074. };
  24075. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  24076. //Here for WebVR
  24077. };
  24078. /**
  24079. * This function MUST be overwritten by the different WebVR cameras available.
  24080. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24081. */
  24082. Camera.prototype._getWebVRProjectionMatrix = function () {
  24083. return BABYLON.Matrix.Identity();
  24084. };
  24085. /**
  24086. * This function MUST be overwritten by the different WebVR cameras available.
  24087. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24088. */
  24089. Camera.prototype._getWebVRViewMatrix = function () {
  24090. return BABYLON.Matrix.Identity();
  24091. };
  24092. /** @hidden */
  24093. Camera.prototype.setCameraRigParameter = function (name, value) {
  24094. if (!this._cameraRigParams) {
  24095. this._cameraRigParams = {};
  24096. }
  24097. this._cameraRigParams[name] = value;
  24098. //provisionnally:
  24099. if (name === "interaxialDistance") {
  24100. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  24101. }
  24102. };
  24103. /**
  24104. * needs to be overridden by children so sub has required properties to be copied
  24105. * @hidden
  24106. */
  24107. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  24108. return null;
  24109. };
  24110. /**
  24111. * May need to be overridden by children
  24112. * @hidden
  24113. */
  24114. Camera.prototype._updateRigCameras = function () {
  24115. for (var i = 0; i < this._rigCameras.length; i++) {
  24116. this._rigCameras[i].minZ = this.minZ;
  24117. this._rigCameras[i].maxZ = this.maxZ;
  24118. this._rigCameras[i].fov = this.fov;
  24119. }
  24120. // only update viewport when ANAGLYPH
  24121. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  24122. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  24123. }
  24124. };
  24125. /** @hidden */
  24126. Camera.prototype._setupInputs = function () {
  24127. };
  24128. /**
  24129. * Serialiaze the camera setup to a json represention
  24130. * @returns the JSON representation
  24131. */
  24132. Camera.prototype.serialize = function () {
  24133. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24134. // Type
  24135. serializationObject.type = this.getClassName();
  24136. // Parent
  24137. if (this.parent) {
  24138. serializationObject.parentId = this.parent.id;
  24139. }
  24140. if (this.inputs) {
  24141. this.inputs.serialize(serializationObject);
  24142. }
  24143. // Animations
  24144. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24145. serializationObject.ranges = this.serializeAnimationRanges();
  24146. return serializationObject;
  24147. };
  24148. /**
  24149. * Clones the current camera.
  24150. * @param name The cloned camera name
  24151. * @returns the cloned camera
  24152. */
  24153. Camera.prototype.clone = function (name) {
  24154. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  24155. };
  24156. /**
  24157. * Gets the direction of the camera relative to a given local axis.
  24158. * @param localAxis Defines the reference axis to provide a relative direction.
  24159. * @return the direction
  24160. */
  24161. Camera.prototype.getDirection = function (localAxis) {
  24162. var result = BABYLON.Vector3.Zero();
  24163. this.getDirectionToRef(localAxis, result);
  24164. return result;
  24165. };
  24166. /**
  24167. * Gets the direction of the camera relative to a given local axis into a passed vector.
  24168. * @param localAxis Defines the reference axis to provide a relative direction.
  24169. * @param result Defines the vector to store the result in
  24170. */
  24171. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  24172. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  24173. };
  24174. /**
  24175. * Gets a camera constructor for a given camera type
  24176. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  24177. * @param name The name of the camera the result will be able to instantiate
  24178. * @param scene The scene the result will construct the camera in
  24179. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  24180. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  24181. * @returns a factory method to construc the camera
  24182. */
  24183. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  24184. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  24185. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  24186. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  24187. interaxial_distance: interaxial_distance,
  24188. isStereoscopicSideBySide: isStereoscopicSideBySide
  24189. });
  24190. if (constructorFunc) {
  24191. return constructorFunc;
  24192. }
  24193. // Default to universal camera
  24194. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  24195. };
  24196. /**
  24197. * Compute the world matrix of the camera.
  24198. * @returns the camera workd matrix
  24199. */
  24200. Camera.prototype.computeWorldMatrix = function () {
  24201. return this.getWorldMatrix();
  24202. };
  24203. /**
  24204. * Parse a JSON and creates the camera from the parsed information
  24205. * @param parsedCamera The JSON to parse
  24206. * @param scene The scene to instantiate the camera in
  24207. * @returns the newly constructed camera
  24208. */
  24209. Camera.Parse = function (parsedCamera, scene) {
  24210. var type = parsedCamera.type;
  24211. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  24212. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  24213. // Parent
  24214. if (parsedCamera.parentId) {
  24215. camera._waitingParentId = parsedCamera.parentId;
  24216. }
  24217. //If camera has an input manager, let it parse inputs settings
  24218. if (camera.inputs) {
  24219. camera.inputs.parse(parsedCamera);
  24220. camera._setupInputs();
  24221. }
  24222. if (camera.setPosition) { // need to force position
  24223. camera.position.copyFromFloats(0, 0, 0);
  24224. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  24225. }
  24226. // Target
  24227. if (parsedCamera.target) {
  24228. if (camera.setTarget) {
  24229. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  24230. }
  24231. }
  24232. // Apply 3d rig, when found
  24233. if (parsedCamera.cameraRigMode) {
  24234. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  24235. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  24236. }
  24237. // Animations
  24238. if (parsedCamera.animations) {
  24239. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  24240. var parsedAnimation = parsedCamera.animations[animationIndex];
  24241. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24242. }
  24243. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  24244. }
  24245. if (parsedCamera.autoAnimate) {
  24246. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  24247. }
  24248. return camera;
  24249. };
  24250. /**
  24251. * This is the default projection mode used by the cameras.
  24252. * It helps recreating a feeling of perspective and better appreciate depth.
  24253. * This is the best way to simulate real life cameras.
  24254. */
  24255. Camera.PERSPECTIVE_CAMERA = 0;
  24256. /**
  24257. * This helps creating camera with an orthographic mode.
  24258. * 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.
  24259. */
  24260. Camera.ORTHOGRAPHIC_CAMERA = 1;
  24261. /**
  24262. * This is the default FOV mode for perspective cameras.
  24263. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  24264. */
  24265. Camera.FOVMODE_VERTICAL_FIXED = 0;
  24266. /**
  24267. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  24268. */
  24269. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  24270. /**
  24271. * This specifies ther is no need for a camera rig.
  24272. * Basically only one eye is rendered corresponding to the camera.
  24273. */
  24274. Camera.RIG_MODE_NONE = 0;
  24275. /**
  24276. * Simulates a camera Rig with one blue eye and one red eye.
  24277. * This can be use with 3d blue and red glasses.
  24278. */
  24279. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  24280. /**
  24281. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  24282. */
  24283. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  24284. /**
  24285. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  24286. */
  24287. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  24288. /**
  24289. * Defines that both eyes of the camera will be rendered over under each other.
  24290. */
  24291. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  24292. /**
  24293. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  24294. */
  24295. Camera.RIG_MODE_VR = 20;
  24296. /**
  24297. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  24298. */
  24299. Camera.RIG_MODE_WEBVR = 21;
  24300. /**
  24301. * Custom rig mode allowing rig cameras to be populated manually with any number of cameras
  24302. */
  24303. Camera.RIG_MODE_CUSTOM = 22;
  24304. /**
  24305. * Defines if by default attaching controls should prevent the default javascript event to continue.
  24306. */
  24307. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  24308. /**
  24309. * @hidden
  24310. * Might be removed once multiview will be a thing
  24311. */
  24312. Camera.UseAlternateWebVRRendering = false;
  24313. __decorate([
  24314. BABYLON.serializeAsVector3()
  24315. ], Camera.prototype, "position", void 0);
  24316. __decorate([
  24317. BABYLON.serializeAsVector3()
  24318. ], Camera.prototype, "upVector", void 0);
  24319. __decorate([
  24320. BABYLON.serialize()
  24321. ], Camera.prototype, "orthoLeft", void 0);
  24322. __decorate([
  24323. BABYLON.serialize()
  24324. ], Camera.prototype, "orthoRight", void 0);
  24325. __decorate([
  24326. BABYLON.serialize()
  24327. ], Camera.prototype, "orthoBottom", void 0);
  24328. __decorate([
  24329. BABYLON.serialize()
  24330. ], Camera.prototype, "orthoTop", void 0);
  24331. __decorate([
  24332. BABYLON.serialize()
  24333. ], Camera.prototype, "fov", void 0);
  24334. __decorate([
  24335. BABYLON.serialize()
  24336. ], Camera.prototype, "minZ", void 0);
  24337. __decorate([
  24338. BABYLON.serialize()
  24339. ], Camera.prototype, "maxZ", void 0);
  24340. __decorate([
  24341. BABYLON.serialize()
  24342. ], Camera.prototype, "inertia", void 0);
  24343. __decorate([
  24344. BABYLON.serialize()
  24345. ], Camera.prototype, "mode", void 0);
  24346. __decorate([
  24347. BABYLON.serialize()
  24348. ], Camera.prototype, "layerMask", void 0);
  24349. __decorate([
  24350. BABYLON.serialize()
  24351. ], Camera.prototype, "fovMode", void 0);
  24352. __decorate([
  24353. BABYLON.serialize()
  24354. ], Camera.prototype, "cameraRigMode", void 0);
  24355. __decorate([
  24356. BABYLON.serialize()
  24357. ], Camera.prototype, "interaxialDistance", void 0);
  24358. __decorate([
  24359. BABYLON.serialize()
  24360. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24361. return Camera;
  24362. }(BABYLON.Node));
  24363. BABYLON.Camera = Camera;
  24364. })(BABYLON || (BABYLON = {}));
  24365. //# sourceMappingURL=babylon.camera.js.map
  24366. var BABYLON;
  24367. (function (BABYLON) {
  24368. /**
  24369. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24370. * It is enable to manage the different groups as well as the different necessary sort functions.
  24371. * This should not be used directly aside of the few static configurations
  24372. */
  24373. var RenderingManager = /** @class */ (function () {
  24374. /**
  24375. * Instantiates a new rendering group for a particular scene
  24376. * @param scene Defines the scene the groups belongs to
  24377. */
  24378. function RenderingManager(scene) {
  24379. /**
  24380. * @hidden
  24381. */
  24382. this._useSceneAutoClearSetup = false;
  24383. this._renderingGroups = new Array();
  24384. this._autoClearDepthStencil = {};
  24385. this._customOpaqueSortCompareFn = {};
  24386. this._customAlphaTestSortCompareFn = {};
  24387. this._customTransparentSortCompareFn = {};
  24388. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24389. this._scene = scene;
  24390. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24391. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24392. }
  24393. }
  24394. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24395. if (depth === void 0) { depth = true; }
  24396. if (stencil === void 0) { stencil = true; }
  24397. if (this._depthStencilBufferAlreadyCleaned) {
  24398. return;
  24399. }
  24400. this._scene.getEngine().clear(null, false, depth, stencil);
  24401. this._depthStencilBufferAlreadyCleaned = true;
  24402. };
  24403. /**
  24404. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24405. * @hidden
  24406. */
  24407. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24408. // Update the observable context (not null as it only goes away on dispose)
  24409. var info = this._renderingGroupInfo;
  24410. info.scene = this._scene;
  24411. info.camera = this._scene.activeCamera;
  24412. // Dispatch sprites
  24413. if (this._scene.spriteManagers && renderSprites) {
  24414. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24415. var manager = this._scene.spriteManagers[index];
  24416. this.dispatchSprites(manager);
  24417. }
  24418. }
  24419. // Render
  24420. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24421. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24422. var renderingGroup = this._renderingGroups[index];
  24423. if (!renderingGroup) {
  24424. continue;
  24425. }
  24426. var renderingGroupMask = Math.pow(2, index);
  24427. info.renderingGroupId = index;
  24428. // Before Observable
  24429. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24430. // Clear depth/stencil if needed
  24431. if (RenderingManager.AUTOCLEAR) {
  24432. var autoClear = this._useSceneAutoClearSetup ?
  24433. this._scene.getAutoClearDepthStencilSetup(index) :
  24434. this._autoClearDepthStencil[index];
  24435. if (autoClear && autoClear.autoClear) {
  24436. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24437. }
  24438. }
  24439. // Render
  24440. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24441. var step = _a[_i];
  24442. step.action(index);
  24443. }
  24444. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24445. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24446. var step = _c[_b];
  24447. step.action(index);
  24448. }
  24449. // After Observable
  24450. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24451. }
  24452. };
  24453. /**
  24454. * Resets the different information of the group to prepare a new frame
  24455. * @hidden
  24456. */
  24457. RenderingManager.prototype.reset = function () {
  24458. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24459. var renderingGroup = this._renderingGroups[index];
  24460. if (renderingGroup) {
  24461. renderingGroup.prepare();
  24462. }
  24463. }
  24464. };
  24465. /**
  24466. * Dispose and release the group and its associated resources.
  24467. * @hidden
  24468. */
  24469. RenderingManager.prototype.dispose = function () {
  24470. this.freeRenderingGroups();
  24471. this._renderingGroups.length = 0;
  24472. this._renderingGroupInfo = null;
  24473. };
  24474. /**
  24475. * Clear the info related to rendering groups preventing retention points during dispose.
  24476. */
  24477. RenderingManager.prototype.freeRenderingGroups = function () {
  24478. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24479. var renderingGroup = this._renderingGroups[index];
  24480. if (renderingGroup) {
  24481. renderingGroup.dispose();
  24482. }
  24483. }
  24484. };
  24485. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24486. if (this._renderingGroups[renderingGroupId] === undefined) {
  24487. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24488. }
  24489. };
  24490. /**
  24491. * Add a sprite manager to the rendering manager in order to render it this frame.
  24492. * @param spriteManager Define the sprite manager to render
  24493. */
  24494. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24495. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24496. this._prepareRenderingGroup(renderingGroupId);
  24497. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24498. };
  24499. /**
  24500. * Add a particle system to the rendering manager in order to render it this frame.
  24501. * @param particleSystem Define the particle system to render
  24502. */
  24503. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24504. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24505. this._prepareRenderingGroup(renderingGroupId);
  24506. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24507. };
  24508. /**
  24509. * Add a submesh to the manager in order to render it this frame
  24510. * @param subMesh The submesh to dispatch
  24511. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24512. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24513. */
  24514. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24515. if (mesh === undefined) {
  24516. mesh = subMesh.getMesh();
  24517. }
  24518. var renderingGroupId = mesh.renderingGroupId || 0;
  24519. this._prepareRenderingGroup(renderingGroupId);
  24520. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24521. };
  24522. /**
  24523. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24524. * This allowed control for front to back rendering or reversly depending of the special needs.
  24525. *
  24526. * @param renderingGroupId The rendering group id corresponding to its index
  24527. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24528. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24529. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24530. */
  24531. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24532. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24533. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24534. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24535. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24536. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24537. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24538. if (this._renderingGroups[renderingGroupId]) {
  24539. var group = this._renderingGroups[renderingGroupId];
  24540. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24541. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24542. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24543. }
  24544. };
  24545. /**
  24546. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24547. *
  24548. * @param renderingGroupId The rendering group id corresponding to its index
  24549. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24550. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24551. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24552. */
  24553. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24554. if (depth === void 0) { depth = true; }
  24555. if (stencil === void 0) { stencil = true; }
  24556. this._autoClearDepthStencil[renderingGroupId] = {
  24557. autoClear: autoClearDepthStencil,
  24558. depth: depth,
  24559. stencil: stencil
  24560. };
  24561. };
  24562. /**
  24563. * Gets the current auto clear configuration for one rendering group of the rendering
  24564. * manager.
  24565. * @param index the rendering group index to get the information for
  24566. * @returns The auto clear setup for the requested rendering group
  24567. */
  24568. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24569. return this._autoClearDepthStencil[index];
  24570. };
  24571. /**
  24572. * The max id used for rendering groups (not included)
  24573. */
  24574. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24575. /**
  24576. * The min id used for rendering groups (included)
  24577. */
  24578. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24579. /**
  24580. * Used to globally prevent autoclearing scenes.
  24581. */
  24582. RenderingManager.AUTOCLEAR = true;
  24583. return RenderingManager;
  24584. }());
  24585. BABYLON.RenderingManager = RenderingManager;
  24586. })(BABYLON || (BABYLON = {}));
  24587. //# sourceMappingURL=babylon.renderingManager.js.map
  24588. var BABYLON;
  24589. (function (BABYLON) {
  24590. /**
  24591. * This represents the object necessary to create a rendering group.
  24592. * This is exclusively used and created by the rendering manager.
  24593. * To modify the behavior, you use the available helpers in your scene or meshes.
  24594. * @hidden
  24595. */
  24596. var RenderingGroup = /** @class */ (function () {
  24597. /**
  24598. * Creates a new rendering group.
  24599. * @param index The rendering group index
  24600. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24601. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24602. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24603. */
  24604. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24605. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24606. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24607. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24608. this.index = index;
  24609. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24610. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24611. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24612. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24613. this._particleSystems = new BABYLON.SmartArray(256);
  24614. this._spriteManagers = new BABYLON.SmartArray(256);
  24615. this._edgesRenderers = new BABYLON.SmartArray(16);
  24616. this._scene = scene;
  24617. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24618. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24619. this.transparentSortCompareFn = transparentSortCompareFn;
  24620. }
  24621. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24622. /**
  24623. * Set the opaque sort comparison function.
  24624. * If null the sub meshes will be render in the order they were created
  24625. */
  24626. set: function (value) {
  24627. this._opaqueSortCompareFn = value;
  24628. if (value) {
  24629. this._renderOpaque = this.renderOpaqueSorted;
  24630. }
  24631. else {
  24632. this._renderOpaque = RenderingGroup.renderUnsorted;
  24633. }
  24634. },
  24635. enumerable: true,
  24636. configurable: true
  24637. });
  24638. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24639. /**
  24640. * Set the alpha test sort comparison function.
  24641. * If null the sub meshes will be render in the order they were created
  24642. */
  24643. set: function (value) {
  24644. this._alphaTestSortCompareFn = value;
  24645. if (value) {
  24646. this._renderAlphaTest = this.renderAlphaTestSorted;
  24647. }
  24648. else {
  24649. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24650. }
  24651. },
  24652. enumerable: true,
  24653. configurable: true
  24654. });
  24655. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24656. /**
  24657. * Set the transparent sort comparison function.
  24658. * If null the sub meshes will be render in the order they were created
  24659. */
  24660. set: function (value) {
  24661. if (value) {
  24662. this._transparentSortCompareFn = value;
  24663. }
  24664. else {
  24665. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24666. }
  24667. this._renderTransparent = this.renderTransparentSorted;
  24668. },
  24669. enumerable: true,
  24670. configurable: true
  24671. });
  24672. /**
  24673. * Render all the sub meshes contained in the group.
  24674. * @param customRenderFunction Used to override the default render behaviour of the group.
  24675. * @returns true if rendered some submeshes.
  24676. */
  24677. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24678. if (customRenderFunction) {
  24679. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24680. return;
  24681. }
  24682. var engine = this._scene.getEngine();
  24683. // Depth only
  24684. if (this._depthOnlySubMeshes.length !== 0) {
  24685. engine.setColorWrite(false);
  24686. this._renderAlphaTest(this._depthOnlySubMeshes);
  24687. engine.setColorWrite(true);
  24688. }
  24689. // Opaque
  24690. if (this._opaqueSubMeshes.length !== 0) {
  24691. this._renderOpaque(this._opaqueSubMeshes);
  24692. }
  24693. // Alpha test
  24694. if (this._alphaTestSubMeshes.length !== 0) {
  24695. this._renderAlphaTest(this._alphaTestSubMeshes);
  24696. }
  24697. var stencilState = engine.getStencilBuffer();
  24698. engine.setStencilBuffer(false);
  24699. // Sprites
  24700. if (renderSprites) {
  24701. this._renderSprites();
  24702. }
  24703. // Particles
  24704. if (renderParticles) {
  24705. this._renderParticles(activeMeshes);
  24706. }
  24707. if (this.onBeforeTransparentRendering) {
  24708. this.onBeforeTransparentRendering();
  24709. }
  24710. // Transparent
  24711. if (this._transparentSubMeshes.length !== 0) {
  24712. this._renderTransparent(this._transparentSubMeshes);
  24713. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24714. }
  24715. // Set back stencil to false in case it changes before the edge renderer.
  24716. engine.setStencilBuffer(false);
  24717. // Edges
  24718. if (this._edgesRenderers.length) {
  24719. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24720. this._edgesRenderers.data[edgesRendererIndex].render();
  24721. }
  24722. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24723. }
  24724. // Restore Stencil state.
  24725. engine.setStencilBuffer(stencilState);
  24726. };
  24727. /**
  24728. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24729. * @param subMeshes The submeshes to render
  24730. */
  24731. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24732. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24733. };
  24734. /**
  24735. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24736. * @param subMeshes The submeshes to render
  24737. */
  24738. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24739. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24740. };
  24741. /**
  24742. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24743. * @param subMeshes The submeshes to render
  24744. */
  24745. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24746. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24747. };
  24748. /**
  24749. * Renders the submeshes in a specified order.
  24750. * @param subMeshes The submeshes to sort before render
  24751. * @param sortCompareFn The comparison function use to sort
  24752. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24753. * @param transparent Specifies to activate blending if true
  24754. */
  24755. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24756. var subIndex = 0;
  24757. var subMesh;
  24758. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24759. for (; subIndex < subMeshes.length; subIndex++) {
  24760. subMesh = subMeshes.data[subIndex];
  24761. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24762. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24763. }
  24764. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24765. if (sortCompareFn) {
  24766. sortedArray.sort(sortCompareFn);
  24767. }
  24768. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24769. subMesh = sortedArray[subIndex];
  24770. if (transparent) {
  24771. var material = subMesh.getMaterial();
  24772. if (material && material.needDepthPrePass) {
  24773. var engine = material.getScene().getEngine();
  24774. engine.setColorWrite(false);
  24775. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24776. subMesh.render(false);
  24777. engine.setColorWrite(true);
  24778. }
  24779. }
  24780. subMesh.render(transparent);
  24781. }
  24782. };
  24783. /**
  24784. * Renders the submeshes in the order they were dispatched (no sort applied).
  24785. * @param subMeshes The submeshes to render
  24786. */
  24787. RenderingGroup.renderUnsorted = function (subMeshes) {
  24788. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24789. var submesh = subMeshes.data[subIndex];
  24790. submesh.render(false);
  24791. }
  24792. };
  24793. /**
  24794. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24795. * are rendered back to front if in the same alpha index.
  24796. *
  24797. * @param a The first submesh
  24798. * @param b The second submesh
  24799. * @returns The result of the comparison
  24800. */
  24801. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24802. // Alpha index first
  24803. if (a._alphaIndex > b._alphaIndex) {
  24804. return 1;
  24805. }
  24806. if (a._alphaIndex < b._alphaIndex) {
  24807. return -1;
  24808. }
  24809. // Then distance to camera
  24810. return RenderingGroup.backToFrontSortCompare(a, b);
  24811. };
  24812. /**
  24813. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24814. * are rendered back to front.
  24815. *
  24816. * @param a The first submesh
  24817. * @param b The second submesh
  24818. * @returns The result of the comparison
  24819. */
  24820. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24821. // Then distance to camera
  24822. if (a._distanceToCamera < b._distanceToCamera) {
  24823. return 1;
  24824. }
  24825. if (a._distanceToCamera > b._distanceToCamera) {
  24826. return -1;
  24827. }
  24828. return 0;
  24829. };
  24830. /**
  24831. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24832. * are rendered front to back (prevent overdraw).
  24833. *
  24834. * @param a The first submesh
  24835. * @param b The second submesh
  24836. * @returns The result of the comparison
  24837. */
  24838. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24839. // Then distance to camera
  24840. if (a._distanceToCamera < b._distanceToCamera) {
  24841. return -1;
  24842. }
  24843. if (a._distanceToCamera > b._distanceToCamera) {
  24844. return 1;
  24845. }
  24846. return 0;
  24847. };
  24848. /**
  24849. * Resets the different lists of submeshes to prepare a new frame.
  24850. */
  24851. RenderingGroup.prototype.prepare = function () {
  24852. this._opaqueSubMeshes.reset();
  24853. this._transparentSubMeshes.reset();
  24854. this._alphaTestSubMeshes.reset();
  24855. this._depthOnlySubMeshes.reset();
  24856. this._particleSystems.reset();
  24857. this._spriteManagers.reset();
  24858. this._edgesRenderers.reset();
  24859. };
  24860. RenderingGroup.prototype.dispose = function () {
  24861. this._opaqueSubMeshes.dispose();
  24862. this._transparentSubMeshes.dispose();
  24863. this._alphaTestSubMeshes.dispose();
  24864. this._depthOnlySubMeshes.dispose();
  24865. this._particleSystems.dispose();
  24866. this._spriteManagers.dispose();
  24867. this._edgesRenderers.dispose();
  24868. };
  24869. /**
  24870. * Inserts the submesh in its correct queue depending on its material.
  24871. * @param subMesh The submesh to dispatch
  24872. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24873. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24874. */
  24875. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24876. // Get mesh and materials if not provided
  24877. if (mesh === undefined) {
  24878. mesh = subMesh.getMesh();
  24879. }
  24880. if (material === undefined) {
  24881. material = subMesh.getMaterial();
  24882. }
  24883. if (material === null || material === undefined) {
  24884. return;
  24885. }
  24886. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24887. this._transparentSubMeshes.push(subMesh);
  24888. }
  24889. else if (material.needAlphaTesting()) { // Alpha test
  24890. if (material.needDepthPrePass) {
  24891. this._depthOnlySubMeshes.push(subMesh);
  24892. }
  24893. this._alphaTestSubMeshes.push(subMesh);
  24894. }
  24895. else {
  24896. if (material.needDepthPrePass) {
  24897. this._depthOnlySubMeshes.push(subMesh);
  24898. }
  24899. this._opaqueSubMeshes.push(subMesh); // Opaque
  24900. }
  24901. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24902. this._edgesRenderers.push(mesh._edgesRenderer);
  24903. }
  24904. };
  24905. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24906. this._spriteManagers.push(spriteManager);
  24907. };
  24908. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24909. this._particleSystems.push(particleSystem);
  24910. };
  24911. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24912. if (this._particleSystems.length === 0) {
  24913. return;
  24914. }
  24915. // Particles
  24916. var activeCamera = this._scene.activeCamera;
  24917. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24918. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24919. var particleSystem = this._particleSystems.data[particleIndex];
  24920. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24921. continue;
  24922. }
  24923. var emitter = particleSystem.emitter;
  24924. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24925. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24926. }
  24927. }
  24928. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24929. };
  24930. RenderingGroup.prototype._renderSprites = function () {
  24931. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24932. return;
  24933. }
  24934. // Sprites
  24935. var activeCamera = this._scene.activeCamera;
  24936. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24937. for (var id = 0; id < this._spriteManagers.length; id++) {
  24938. var spriteManager = this._spriteManagers.data[id];
  24939. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24940. spriteManager.render();
  24941. }
  24942. }
  24943. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24944. };
  24945. return RenderingGroup;
  24946. }());
  24947. BABYLON.RenderingGroup = RenderingGroup;
  24948. })(BABYLON || (BABYLON = {}));
  24949. //# sourceMappingURL=babylon.renderingGroup.js.map
  24950. var BABYLON;
  24951. (function (BABYLON) {
  24952. /**
  24953. * Groups all the scene component constants in one place to ease maintenance.
  24954. * @hidden
  24955. */
  24956. var SceneComponentConstants = /** @class */ (function () {
  24957. function SceneComponentConstants() {
  24958. }
  24959. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24960. SceneComponentConstants.NAME_LAYER = "Layer";
  24961. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24962. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24963. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24964. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24965. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24966. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24967. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24968. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24969. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24970. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24971. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24972. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24973. SceneComponentConstants.NAME_OCTREE = "Octree";
  24974. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24975. SceneComponentConstants.NAME_AUDIO = "Audio";
  24976. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24977. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24978. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24979. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24980. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24981. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24982. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24983. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24984. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24985. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24986. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24987. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24988. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24989. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24990. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24991. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24992. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24993. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24994. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24995. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24996. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24997. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24998. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24999. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  25000. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  25001. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  25002. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  25003. return SceneComponentConstants;
  25004. }());
  25005. BABYLON.SceneComponentConstants = SceneComponentConstants;
  25006. /**
  25007. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  25008. * @hidden
  25009. */
  25010. var Stage = /** @class */ (function (_super) {
  25011. __extends(Stage, _super);
  25012. /**
  25013. * Hide ctor from the rest of the world.
  25014. * @param items The items to add.
  25015. */
  25016. function Stage(items) {
  25017. return _super.apply(this, items) || this;
  25018. }
  25019. /**
  25020. * Creates a new Stage.
  25021. * @returns A new instance of a Stage
  25022. */
  25023. Stage.Create = function () {
  25024. return Object.create(Stage.prototype);
  25025. };
  25026. /**
  25027. * Registers a step in an ordered way in the targeted stage.
  25028. * @param index Defines the position to register the step in
  25029. * @param component Defines the component attached to the step
  25030. * @param action Defines the action to launch during the step
  25031. */
  25032. Stage.prototype.registerStep = function (index, component, action) {
  25033. var i = 0;
  25034. var maxIndex = Number.MAX_VALUE;
  25035. for (; i < this.length; i++) {
  25036. var step = this[i];
  25037. maxIndex = step.index;
  25038. if (index < maxIndex) {
  25039. break;
  25040. }
  25041. }
  25042. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  25043. };
  25044. /**
  25045. * Clears all the steps from the stage.
  25046. */
  25047. Stage.prototype.clear = function () {
  25048. this.length = 0;
  25049. };
  25050. return Stage;
  25051. }(Array));
  25052. BABYLON.Stage = Stage;
  25053. })(BABYLON || (BABYLON = {}));
  25054. //# sourceMappingURL=babylon.sceneComponent.js.map
  25055. var BABYLON;
  25056. (function (BABYLON) {
  25057. /**
  25058. * Base class of the scene acting as a container for the different elements composing a scene.
  25059. * This class is dynamically extended by the different components of the scene increasing
  25060. * flexibility and reducing coupling
  25061. */
  25062. var AbstractScene = /** @class */ (function () {
  25063. function AbstractScene() {
  25064. /**
  25065. * Gets the list of root nodes (ie. nodes with no parent)
  25066. */
  25067. this.rootNodes = new Array();
  25068. /** All of the cameras added to this scene
  25069. * @see http://doc.babylonjs.com/babylon101/cameras
  25070. */
  25071. this.cameras = new Array();
  25072. /**
  25073. * All of the lights added to this scene
  25074. * @see http://doc.babylonjs.com/babylon101/lights
  25075. */
  25076. this.lights = new Array();
  25077. /**
  25078. * All of the (abstract) meshes added to this scene
  25079. */
  25080. this.meshes = new Array();
  25081. /**
  25082. * The list of skeletons added to the scene
  25083. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  25084. */
  25085. this.skeletons = new Array();
  25086. /**
  25087. * All of the particle systems added to this scene
  25088. * @see http://doc.babylonjs.com/babylon101/particles
  25089. */
  25090. this.particleSystems = new Array();
  25091. /**
  25092. * Gets a list of Animations associated with the scene
  25093. */
  25094. this.animations = [];
  25095. /**
  25096. * All of the animation groups added to this scene
  25097. * @see http://doc.babylonjs.com/how_to/group
  25098. */
  25099. this.animationGroups = new Array();
  25100. /**
  25101. * All of the multi-materials added to this scene
  25102. * @see http://doc.babylonjs.com/how_to/multi_materials
  25103. */
  25104. this.multiMaterials = new Array();
  25105. /**
  25106. * All of the materials added to this scene
  25107. * In the context of a Scene, it is not supposed to be modified manually.
  25108. * Any addition or removal should be done using the addMaterial and removeMAterial Scene methods.
  25109. * Note also that the order of the Material wihin the array is not significant and might change.
  25110. * @see http://doc.babylonjs.com/babylon101/materials
  25111. */
  25112. this.materials = new Array();
  25113. /**
  25114. * The list of morph target managers added to the scene
  25115. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  25116. */
  25117. this.morphTargetManagers = new Array();
  25118. /**
  25119. * The list of geometries used in the scene.
  25120. */
  25121. this.geometries = new Array();
  25122. /**
  25123. * All of the tranform nodes added to this scene
  25124. * In the context of a Scene, it is not supposed to be modified manually.
  25125. * Any addition or removal should be done using the addTransformNode and removeTransformNode Scene methods.
  25126. * Note also that the order of the TransformNode wihin the array is not significant and might change.
  25127. * @see http://doc.babylonjs.com/how_to/transformnode
  25128. */
  25129. this.transformNodes = new Array();
  25130. /**
  25131. * ActionManagers available on the scene.
  25132. */
  25133. this.actionManagers = new Array();
  25134. /**
  25135. * Textures to keep.
  25136. */
  25137. this.textures = new Array();
  25138. }
  25139. /**
  25140. * Adds a parser in the list of available ones
  25141. * @param name Defines the name of the parser
  25142. * @param parser Defines the parser to add
  25143. */
  25144. AbstractScene.AddParser = function (name, parser) {
  25145. this._BabylonFileParsers[name] = parser;
  25146. };
  25147. /**
  25148. * Gets a general parser from the list of avaialble ones
  25149. * @param name Defines the name of the parser
  25150. * @returns the requested parser or null
  25151. */
  25152. AbstractScene.GetParser = function (name) {
  25153. if (this._BabylonFileParsers[name]) {
  25154. return this._BabylonFileParsers[name];
  25155. }
  25156. return null;
  25157. };
  25158. /**
  25159. * Adds n individual parser in the list of available ones
  25160. * @param name Defines the name of the parser
  25161. * @param parser Defines the parser to add
  25162. */
  25163. AbstractScene.AddIndividualParser = function (name, parser) {
  25164. this._IndividualBabylonFileParsers[name] = parser;
  25165. };
  25166. /**
  25167. * Gets an individual parser from the list of avaialble ones
  25168. * @param name Defines the name of the parser
  25169. * @returns the requested parser or null
  25170. */
  25171. AbstractScene.GetIndividualParser = function (name) {
  25172. if (this._IndividualBabylonFileParsers[name]) {
  25173. return this._IndividualBabylonFileParsers[name];
  25174. }
  25175. return null;
  25176. };
  25177. /**
  25178. * Parser json data and populate both a scene and its associated container object
  25179. * @param jsonData Defines the data to parse
  25180. * @param scene Defines the scene to parse the data for
  25181. * @param container Defines the container attached to the parsing sequence
  25182. * @param rootUrl Defines the root url of the data
  25183. */
  25184. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  25185. for (var parserName in this._BabylonFileParsers) {
  25186. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  25187. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  25188. }
  25189. }
  25190. };
  25191. /**
  25192. * Stores the list of available parsers in the application.
  25193. */
  25194. AbstractScene._BabylonFileParsers = {};
  25195. /**
  25196. * Stores the list of available individual parsers in the application.
  25197. */
  25198. AbstractScene._IndividualBabylonFileParsers = {};
  25199. return AbstractScene;
  25200. }());
  25201. BABYLON.AbstractScene = AbstractScene;
  25202. })(BABYLON || (BABYLON = {}));
  25203. //# sourceMappingURL=babylon.abstractScene.js.map
  25204. var BABYLON;
  25205. (function (BABYLON) {
  25206. /** @hidden */
  25207. var ClickInfo = /** @class */ (function () {
  25208. function ClickInfo() {
  25209. this._singleClick = false;
  25210. this._doubleClick = false;
  25211. this._hasSwiped = false;
  25212. this._ignore = false;
  25213. }
  25214. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  25215. get: function () {
  25216. return this._singleClick;
  25217. },
  25218. set: function (b) {
  25219. this._singleClick = b;
  25220. },
  25221. enumerable: true,
  25222. configurable: true
  25223. });
  25224. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  25225. get: function () {
  25226. return this._doubleClick;
  25227. },
  25228. set: function (b) {
  25229. this._doubleClick = b;
  25230. },
  25231. enumerable: true,
  25232. configurable: true
  25233. });
  25234. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  25235. get: function () {
  25236. return this._hasSwiped;
  25237. },
  25238. set: function (b) {
  25239. this._hasSwiped = b;
  25240. },
  25241. enumerable: true,
  25242. configurable: true
  25243. });
  25244. Object.defineProperty(ClickInfo.prototype, "ignore", {
  25245. get: function () {
  25246. return this._ignore;
  25247. },
  25248. set: function (b) {
  25249. this._ignore = b;
  25250. },
  25251. enumerable: true,
  25252. configurable: true
  25253. });
  25254. return ClickInfo;
  25255. }());
  25256. /**
  25257. * This class is used by the onRenderingGroupObservable
  25258. */
  25259. var RenderingGroupInfo = /** @class */ (function () {
  25260. function RenderingGroupInfo() {
  25261. }
  25262. return RenderingGroupInfo;
  25263. }());
  25264. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  25265. /**
  25266. * Represents a scene to be rendered by the engine.
  25267. * @see http://doc.babylonjs.com/features/scene
  25268. */
  25269. var Scene = /** @class */ (function (_super) {
  25270. __extends(Scene, _super);
  25271. /**
  25272. * Creates a new Scene
  25273. * @param engine defines the engine to use to render this scene
  25274. */
  25275. function Scene(engine, options) {
  25276. var _this = _super.call(this) || this;
  25277. // Members
  25278. /**
  25279. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  25280. */
  25281. _this.autoClear = true;
  25282. /**
  25283. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  25284. */
  25285. _this.autoClearDepthAndStencil = true;
  25286. /**
  25287. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  25288. */
  25289. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  25290. /**
  25291. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  25292. */
  25293. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25294. _this._forceWireframe = false;
  25295. _this._forcePointsCloud = false;
  25296. /**
  25297. * Gets or sets a boolean indicating if animations are enabled
  25298. */
  25299. _this.animationsEnabled = true;
  25300. _this._animationPropertiesOverride = null;
  25301. /**
  25302. * Gets or sets a boolean indicating if a constant deltatime has to be used
  25303. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  25304. */
  25305. _this.useConstantAnimationDeltaTime = false;
  25306. /**
  25307. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  25308. * Please note that it requires to run a ray cast through the scene on every frame
  25309. */
  25310. _this.constantlyUpdateMeshUnderPointer = false;
  25311. /**
  25312. * Defines the HTML cursor to use when hovering over interactive elements
  25313. */
  25314. _this.hoverCursor = "pointer";
  25315. /**
  25316. * Defines the HTML default cursor to use (empty by default)
  25317. */
  25318. _this.defaultCursor = "";
  25319. /**
  25320. * This is used to call preventDefault() on pointer down
  25321. * in order to block unwanted artifacts like system double clicks
  25322. */
  25323. _this.preventDefaultOnPointerDown = true;
  25324. /**
  25325. * This is used to call preventDefault() on pointer up
  25326. * in order to block unwanted artifacts like system double clicks
  25327. */
  25328. _this.preventDefaultOnPointerUp = true;
  25329. // Metadata
  25330. /**
  25331. * Gets or sets user defined metadata
  25332. */
  25333. _this.metadata = null;
  25334. /**
  25335. * Use this array to add regular expressions used to disable offline support for specific urls
  25336. */
  25337. _this.disableOfflineSupportExceptionRules = new Array();
  25338. /**
  25339. * An event triggered when the scene is disposed.
  25340. */
  25341. _this.onDisposeObservable = new BABYLON.Observable();
  25342. _this._onDisposeObserver = null;
  25343. /**
  25344. * An event triggered before rendering the scene (right after animations and physics)
  25345. */
  25346. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25347. _this._onBeforeRenderObserver = null;
  25348. /**
  25349. * An event triggered after rendering the scene
  25350. */
  25351. _this.onAfterRenderObservable = new BABYLON.Observable();
  25352. _this._onAfterRenderObserver = null;
  25353. /**
  25354. * An event triggered before animating the scene
  25355. */
  25356. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  25357. /**
  25358. * An event triggered after animations processing
  25359. */
  25360. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  25361. /**
  25362. * An event triggered before draw calls are ready to be sent
  25363. */
  25364. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  25365. /**
  25366. * An event triggered after draw calls have been sent
  25367. */
  25368. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  25369. /**
  25370. * An event triggered when the scene is ready
  25371. */
  25372. _this.onReadyObservable = new BABYLON.Observable();
  25373. /**
  25374. * An event triggered before rendering a camera
  25375. */
  25376. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25377. _this._onBeforeCameraRenderObserver = null;
  25378. /**
  25379. * An event triggered after rendering a camera
  25380. */
  25381. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25382. _this._onAfterCameraRenderObserver = null;
  25383. /**
  25384. * An event triggered when active meshes evaluation is about to start
  25385. */
  25386. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25387. /**
  25388. * An event triggered when active meshes evaluation is done
  25389. */
  25390. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25391. /**
  25392. * An event triggered when particles rendering is about to start
  25393. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25394. */
  25395. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25396. /**
  25397. * An event triggered when particles rendering is done
  25398. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25399. */
  25400. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25401. /**
  25402. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25403. */
  25404. _this.onDataLoadedObservable = new BABYLON.Observable();
  25405. /**
  25406. * An event triggered when a camera is created
  25407. */
  25408. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25409. /**
  25410. * An event triggered when a camera is removed
  25411. */
  25412. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25413. /**
  25414. * An event triggered when a light is created
  25415. */
  25416. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25417. /**
  25418. * An event triggered when a light is removed
  25419. */
  25420. _this.onLightRemovedObservable = new BABYLON.Observable();
  25421. /**
  25422. * An event triggered when a geometry is created
  25423. */
  25424. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25425. /**
  25426. * An event triggered when a geometry is removed
  25427. */
  25428. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25429. /**
  25430. * An event triggered when a transform node is created
  25431. */
  25432. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25433. /**
  25434. * An event triggered when a transform node is removed
  25435. */
  25436. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25437. /**
  25438. * An event triggered when a mesh is created
  25439. */
  25440. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25441. /**
  25442. * An event triggered when a mesh is removed
  25443. */
  25444. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25445. /**
  25446. * An event triggered when a material is created
  25447. */
  25448. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25449. /**
  25450. * An event triggered when a material is removed
  25451. */
  25452. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25453. /**
  25454. * An event triggered when a texture is created
  25455. */
  25456. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25457. /**
  25458. * An event triggered when a texture is removed
  25459. */
  25460. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25461. /**
  25462. * An event triggered when render targets are about to be rendered
  25463. * Can happen multiple times per frame.
  25464. */
  25465. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25466. /**
  25467. * An event triggered when render targets were rendered.
  25468. * Can happen multiple times per frame.
  25469. */
  25470. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25471. /**
  25472. * An event triggered before calculating deterministic simulation step
  25473. */
  25474. _this.onBeforeStepObservable = new BABYLON.Observable();
  25475. /**
  25476. * An event triggered after calculating deterministic simulation step
  25477. */
  25478. _this.onAfterStepObservable = new BABYLON.Observable();
  25479. /**
  25480. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25481. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25482. * 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)
  25483. */
  25484. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25485. /**
  25486. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25487. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25488. * 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)
  25489. */
  25490. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25491. /**
  25492. * This Observable will when a mesh has been imported into the scene.
  25493. */
  25494. _this.onMeshImportedObservable = new BABYLON.Observable();
  25495. // Animations
  25496. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25497. /**
  25498. * 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).
  25499. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25500. */
  25501. _this.onPrePointerObservable = new BABYLON.Observable();
  25502. /**
  25503. * Observable event triggered each time an input event is received from the rendering canvas
  25504. */
  25505. _this.onPointerObservable = new BABYLON.Observable();
  25506. _this._meshPickProceed = false;
  25507. _this._currentPickResult = null;
  25508. _this._previousPickResult = null;
  25509. _this._totalPointersPressed = 0;
  25510. _this._doubleClickOccured = false;
  25511. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25512. _this.cameraToUseForPointers = null;
  25513. _this._pointerX = 0;
  25514. _this._pointerY = 0;
  25515. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25516. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25517. _this._startingPointerTime = 0;
  25518. _this._previousStartingPointerTime = 0;
  25519. _this._pointerCaptures = {};
  25520. // Deterministic lockstep
  25521. _this._timeAccumulator = 0;
  25522. _this._currentStepId = 0;
  25523. _this._currentInternalStep = 0;
  25524. // Keyboard
  25525. /**
  25526. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25527. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25528. */
  25529. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25530. /**
  25531. * Observable event triggered each time an keyboard event is received from the hosting window
  25532. */
  25533. _this.onKeyboardObservable = new BABYLON.Observable();
  25534. // Coordinates system
  25535. _this._useRightHandedSystem = false;
  25536. // Fog
  25537. _this._fogEnabled = true;
  25538. _this._fogMode = Scene.FOGMODE_NONE;
  25539. /**
  25540. * Gets or sets the fog color to use
  25541. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25542. * (Default is Color3(0.2, 0.2, 0.3))
  25543. */
  25544. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25545. /**
  25546. * Gets or sets the fog density to use
  25547. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25548. * (Default is 0.1)
  25549. */
  25550. _this.fogDensity = 0.1;
  25551. /**
  25552. * Gets or sets the fog start distance to use
  25553. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25554. * (Default is 0)
  25555. */
  25556. _this.fogStart = 0;
  25557. /**
  25558. * Gets or sets the fog end distance to use
  25559. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25560. * (Default is 1000)
  25561. */
  25562. _this.fogEnd = 1000.0;
  25563. // Lights
  25564. _this._shadowsEnabled = true;
  25565. _this._lightsEnabled = true;
  25566. /** All of the active cameras added to this scene. */
  25567. _this.activeCameras = new Array();
  25568. // Textures
  25569. _this._texturesEnabled = true;
  25570. // Particles
  25571. /**
  25572. * Gets or sets a boolean indicating if particles are enabled on this scene
  25573. */
  25574. _this.particlesEnabled = true;
  25575. // Sprites
  25576. /**
  25577. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25578. */
  25579. _this.spritesEnabled = true;
  25580. // Skeletons
  25581. _this._skeletonsEnabled = true;
  25582. // Lens flares
  25583. /**
  25584. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25585. */
  25586. _this.lensFlaresEnabled = true;
  25587. // Collisions
  25588. /**
  25589. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25590. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25591. */
  25592. _this.collisionsEnabled = true;
  25593. /**
  25594. * Defines the gravity applied to this scene (used only for collisions)
  25595. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25596. */
  25597. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25598. // Postprocesses
  25599. /**
  25600. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25601. */
  25602. _this.postProcessesEnabled = true;
  25603. /**
  25604. * The list of postprocesses added to the scene
  25605. */
  25606. _this.postProcesses = new Array();
  25607. // Customs render targets
  25608. /**
  25609. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25610. */
  25611. _this.renderTargetsEnabled = true;
  25612. /**
  25613. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25614. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25615. */
  25616. _this.dumpNextRenderTargets = false;
  25617. /**
  25618. * The list of user defined render targets added to the scene
  25619. */
  25620. _this.customRenderTargets = new Array();
  25621. /**
  25622. * Gets the list of meshes imported to the scene through SceneLoader
  25623. */
  25624. _this.importedMeshesFiles = new Array();
  25625. // Probes
  25626. /**
  25627. * Gets or sets a boolean indicating if probes are enabled on this scene
  25628. */
  25629. _this.probesEnabled = true;
  25630. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25631. // Procedural textures
  25632. /**
  25633. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25634. */
  25635. _this.proceduralTexturesEnabled = true;
  25636. // Performance counters
  25637. _this._totalVertices = new BABYLON.PerfCounter();
  25638. /** @hidden */
  25639. _this._activeIndices = new BABYLON.PerfCounter();
  25640. /** @hidden */
  25641. _this._activeParticles = new BABYLON.PerfCounter();
  25642. /** @hidden */
  25643. _this._activeBones = new BABYLON.PerfCounter();
  25644. _this._animationTime = 0;
  25645. /**
  25646. * Gets or sets a general scale for animation speed
  25647. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25648. */
  25649. _this.animationTimeScale = 1;
  25650. _this._renderId = 0;
  25651. _this._frameId = 0;
  25652. _this._executeWhenReadyTimeoutId = -1;
  25653. _this._intermediateRendering = false;
  25654. _this._viewUpdateFlag = -1;
  25655. _this._projectionUpdateFlag = -1;
  25656. _this._alternateViewUpdateFlag = -1;
  25657. _this._alternateProjectionUpdateFlag = -1;
  25658. /** @hidden */
  25659. _this._toBeDisposed = new Array(256);
  25660. _this._activeRequests = new Array();
  25661. _this._pendingData = new Array();
  25662. _this._isDisposed = false;
  25663. /**
  25664. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25665. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25666. */
  25667. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25668. _this._activeMeshes = new BABYLON.SmartArray(256);
  25669. _this._processedMaterials = new BABYLON.SmartArray(256);
  25670. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25671. /** @hidden */
  25672. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25673. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25674. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25675. /** @hidden */
  25676. _this._activeAnimatables = new Array();
  25677. _this._transformMatrix = BABYLON.Matrix.Zero();
  25678. _this._useAlternateCameraConfiguration = false;
  25679. _this._alternateRendering = false;
  25680. _this._wheelEventName = "";
  25681. /**
  25682. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25683. * This is useful if there are more lights that the maximum simulteanous authorized
  25684. */
  25685. _this.requireLightSorting = false;
  25686. /**
  25687. * @hidden
  25688. * Backing store of defined scene components.
  25689. */
  25690. _this._components = [];
  25691. /**
  25692. * @hidden
  25693. * Backing store of defined scene components.
  25694. */
  25695. _this._serializableComponents = [];
  25696. /**
  25697. * List of components to register on the next registration step.
  25698. */
  25699. _this._transientComponents = [];
  25700. /**
  25701. * @hidden
  25702. * Defines the actions happening before camera updates.
  25703. */
  25704. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25705. /**
  25706. * @hidden
  25707. * Defines the actions happening before clear the canvas.
  25708. */
  25709. _this._beforeClearStage = BABYLON.Stage.Create();
  25710. /**
  25711. * @hidden
  25712. * Defines the actions when collecting render targets for the frame.
  25713. */
  25714. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25715. /**
  25716. * @hidden
  25717. * Defines the actions happening for one camera in the frame.
  25718. */
  25719. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25720. /**
  25721. * @hidden
  25722. * Defines the actions happening during the per mesh ready checks.
  25723. */
  25724. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25725. /**
  25726. * @hidden
  25727. * Defines the actions happening before evaluate active mesh checks.
  25728. */
  25729. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25730. /**
  25731. * @hidden
  25732. * Defines the actions happening during the evaluate sub mesh checks.
  25733. */
  25734. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25735. /**
  25736. * @hidden
  25737. * Defines the actions happening during the active mesh stage.
  25738. */
  25739. _this._activeMeshStage = BABYLON.Stage.Create();
  25740. /**
  25741. * @hidden
  25742. * Defines the actions happening during the per camera render target step.
  25743. */
  25744. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25745. /**
  25746. * @hidden
  25747. * Defines the actions happening just before the active camera is drawing.
  25748. */
  25749. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25750. /**
  25751. * @hidden
  25752. * Defines the actions happening just before a rendering group is drawing.
  25753. */
  25754. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25755. /**
  25756. * @hidden
  25757. * Defines the actions happening just before a mesh is drawing.
  25758. */
  25759. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25760. /**
  25761. * @hidden
  25762. * Defines the actions happening just after a mesh has been drawn.
  25763. */
  25764. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25765. /**
  25766. * @hidden
  25767. * Defines the actions happening just after a rendering group has been drawn.
  25768. */
  25769. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25770. /**
  25771. * @hidden
  25772. * Defines the actions happening just after the active camera has been drawn.
  25773. */
  25774. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25775. /**
  25776. * @hidden
  25777. * Defines the actions happening just after rendering all cameras and computing intersections.
  25778. */
  25779. _this._afterRenderStage = BABYLON.Stage.Create();
  25780. /**
  25781. * @hidden
  25782. * Defines the actions happening when a pointer move event happens.
  25783. */
  25784. _this._pointerMoveStage = BABYLON.Stage.Create();
  25785. /**
  25786. * @hidden
  25787. * Defines the actions happening when a pointer down event happens.
  25788. */
  25789. _this._pointerDownStage = BABYLON.Stage.Create();
  25790. /**
  25791. * @hidden
  25792. * Defines the actions happening when a pointer up event happens.
  25793. */
  25794. _this._pointerUpStage = BABYLON.Stage.Create();
  25795. /**
  25796. * an optional map from Geometry Id to Geometry index in the 'geometries' array
  25797. */
  25798. _this.geometriesById = null;
  25799. _this._defaultMeshCandidates = {
  25800. data: [],
  25801. length: 0
  25802. };
  25803. _this._defaultSubMeshCandidates = {
  25804. data: [],
  25805. length: 0
  25806. };
  25807. _this._preventFreeActiveMeshesAndRenderingGroups = false;
  25808. _this._activeMeshesFrozen = false;
  25809. /** @hidden */
  25810. _this._allowPostProcessClearColor = true;
  25811. /**
  25812. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25813. */
  25814. _this.getDeterministicFrameTime = function () {
  25815. return 1000.0 / 60.0; // frame time in ms
  25816. };
  25817. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25818. _this._blockMaterialDirtyMechanism = false;
  25819. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25820. _this._engine.scenes.push(_this);
  25821. _this._uid = null;
  25822. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25823. if (BABYLON.PostProcessManager) {
  25824. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25825. }
  25826. if (BABYLON.Tools.IsWindowObjectExist()) {
  25827. _this.attachControl();
  25828. }
  25829. //collision coordinator initialization. For now legacy per default.
  25830. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25831. // Uniform Buffer
  25832. _this._createUbo();
  25833. // Default Image processing definition
  25834. if (BABYLON.ImageProcessingConfiguration) {
  25835. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25836. }
  25837. _this.setDefaultCandidateProviders();
  25838. if (options && options.useGeometryIdsMap === true) {
  25839. _this.geometriesById = {};
  25840. }
  25841. _this.useMaterialMeshMap = options && options.useGeometryIdsMap || false;
  25842. _this.useClonedMeshhMap = options && options.useClonedMeshhMap || false;
  25843. return _this;
  25844. }
  25845. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25846. /**
  25847. * Texture used in all pbr material as the reflection texture.
  25848. * As in the majority of the scene they are the same (exception for multi room and so on),
  25849. * this is easier to reference from here than from all the materials.
  25850. */
  25851. get: function () {
  25852. return this._environmentTexture;
  25853. },
  25854. /**
  25855. * Texture used in all pbr material as the reflection texture.
  25856. * As in the majority of the scene they are the same (exception for multi room and so on),
  25857. * this is easier to set here than in all the materials.
  25858. */
  25859. set: function (value) {
  25860. if (this._environmentTexture === value) {
  25861. return;
  25862. }
  25863. this._environmentTexture = value;
  25864. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25865. },
  25866. enumerable: true,
  25867. configurable: true
  25868. });
  25869. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25870. /**
  25871. * Default image processing configuration used either in the rendering
  25872. * Forward main pass or through the imageProcessingPostProcess if present.
  25873. * As in the majority of the scene they are the same (exception for multi camera),
  25874. * this is easier to reference from here than from all the materials and post process.
  25875. *
  25876. * No setter as we it is a shared configuration, you can set the values instead.
  25877. */
  25878. get: function () {
  25879. return this._imageProcessingConfiguration;
  25880. },
  25881. enumerable: true,
  25882. configurable: true
  25883. });
  25884. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25885. get: function () {
  25886. return this._forceWireframe;
  25887. },
  25888. /**
  25889. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25890. */
  25891. set: function (value) {
  25892. if (this._forceWireframe === value) {
  25893. return;
  25894. }
  25895. this._forceWireframe = value;
  25896. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25897. },
  25898. enumerable: true,
  25899. configurable: true
  25900. });
  25901. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25902. get: function () {
  25903. return this._forcePointsCloud;
  25904. },
  25905. /**
  25906. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25907. */
  25908. set: function (value) {
  25909. if (this._forcePointsCloud === value) {
  25910. return;
  25911. }
  25912. this._forcePointsCloud = value;
  25913. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25914. },
  25915. enumerable: true,
  25916. configurable: true
  25917. });
  25918. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25919. /**
  25920. * Gets or sets the animation properties override
  25921. */
  25922. get: function () {
  25923. return this._animationPropertiesOverride;
  25924. },
  25925. set: function (value) {
  25926. this._animationPropertiesOverride = value;
  25927. },
  25928. enumerable: true,
  25929. configurable: true
  25930. });
  25931. Object.defineProperty(Scene.prototype, "onDispose", {
  25932. /** Sets a function to be executed when this scene is disposed. */
  25933. set: function (callback) {
  25934. if (this._onDisposeObserver) {
  25935. this.onDisposeObservable.remove(this._onDisposeObserver);
  25936. }
  25937. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25938. },
  25939. enumerable: true,
  25940. configurable: true
  25941. });
  25942. Object.defineProperty(Scene.prototype, "beforeRender", {
  25943. /** Sets a function to be executed before rendering this scene */
  25944. set: function (callback) {
  25945. if (this._onBeforeRenderObserver) {
  25946. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25947. }
  25948. if (callback) {
  25949. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25950. }
  25951. },
  25952. enumerable: true,
  25953. configurable: true
  25954. });
  25955. Object.defineProperty(Scene.prototype, "afterRender", {
  25956. /** Sets a function to be executed after rendering this scene */
  25957. set: function (callback) {
  25958. if (this._onAfterRenderObserver) {
  25959. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25960. }
  25961. if (callback) {
  25962. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25963. }
  25964. },
  25965. enumerable: true,
  25966. configurable: true
  25967. });
  25968. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25969. /** Sets a function to be executed before rendering a camera*/
  25970. set: function (callback) {
  25971. if (this._onBeforeCameraRenderObserver) {
  25972. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25973. }
  25974. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25975. },
  25976. enumerable: true,
  25977. configurable: true
  25978. });
  25979. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25980. /** Sets a function to be executed after rendering a camera*/
  25981. set: function (callback) {
  25982. if (this._onAfterCameraRenderObserver) {
  25983. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25984. }
  25985. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25986. },
  25987. enumerable: true,
  25988. configurable: true
  25989. });
  25990. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25991. /**
  25992. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25993. */
  25994. get: function () {
  25995. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25996. },
  25997. enumerable: true,
  25998. configurable: true
  25999. });
  26000. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  26001. get: function () {
  26002. return this._useRightHandedSystem;
  26003. },
  26004. /**
  26005. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  26006. */
  26007. set: function (value) {
  26008. if (this._useRightHandedSystem === value) {
  26009. return;
  26010. }
  26011. this._useRightHandedSystem = value;
  26012. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26013. },
  26014. enumerable: true,
  26015. configurable: true
  26016. });
  26017. /**
  26018. * Sets the step Id used by deterministic lock step
  26019. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26020. * @param newStepId defines the step Id
  26021. */
  26022. Scene.prototype.setStepId = function (newStepId) {
  26023. this._currentStepId = newStepId;
  26024. };
  26025. /**
  26026. * Gets the step Id used by deterministic lock step
  26027. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26028. * @returns the step Id
  26029. */
  26030. Scene.prototype.getStepId = function () {
  26031. return this._currentStepId;
  26032. };
  26033. /**
  26034. * Gets the internal step used by deterministic lock step
  26035. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26036. * @returns the internal step
  26037. */
  26038. Scene.prototype.getInternalStep = function () {
  26039. return this._currentInternalStep;
  26040. };
  26041. Object.defineProperty(Scene.prototype, "fogEnabled", {
  26042. get: function () {
  26043. return this._fogEnabled;
  26044. },
  26045. /**
  26046. * Gets or sets a boolean indicating if fog is enabled on this scene
  26047. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26048. * (Default is true)
  26049. */
  26050. set: function (value) {
  26051. if (this._fogEnabled === value) {
  26052. return;
  26053. }
  26054. this._fogEnabled = value;
  26055. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26056. },
  26057. enumerable: true,
  26058. configurable: true
  26059. });
  26060. Object.defineProperty(Scene.prototype, "fogMode", {
  26061. get: function () {
  26062. return this._fogMode;
  26063. },
  26064. /**
  26065. * Gets or sets the fog mode to use
  26066. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26067. * | mode | value |
  26068. * | --- | --- |
  26069. * | FOGMODE_NONE | 0 |
  26070. * | FOGMODE_EXP | 1 |
  26071. * | FOGMODE_EXP2 | 2 |
  26072. * | FOGMODE_LINEAR | 3 |
  26073. */
  26074. set: function (value) {
  26075. if (this._fogMode === value) {
  26076. return;
  26077. }
  26078. this._fogMode = value;
  26079. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26080. },
  26081. enumerable: true,
  26082. configurable: true
  26083. });
  26084. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  26085. get: function () {
  26086. return this._shadowsEnabled;
  26087. },
  26088. /**
  26089. * Gets or sets a boolean indicating if shadows are enabled on this scene
  26090. */
  26091. set: function (value) {
  26092. if (this._shadowsEnabled === value) {
  26093. return;
  26094. }
  26095. this._shadowsEnabled = value;
  26096. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26097. },
  26098. enumerable: true,
  26099. configurable: true
  26100. });
  26101. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  26102. get: function () {
  26103. return this._lightsEnabled;
  26104. },
  26105. /**
  26106. * Gets or sets a boolean indicating if lights are enabled on this scene
  26107. */
  26108. set: function (value) {
  26109. if (this._lightsEnabled === value) {
  26110. return;
  26111. }
  26112. this._lightsEnabled = value;
  26113. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26114. },
  26115. enumerable: true,
  26116. configurable: true
  26117. });
  26118. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  26119. /** The default material used on meshes when no material is affected */
  26120. get: function () {
  26121. if (!this._defaultMaterial) {
  26122. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  26123. }
  26124. return this._defaultMaterial;
  26125. },
  26126. /** The default material used on meshes when no material is affected */
  26127. set: function (value) {
  26128. this._defaultMaterial = value;
  26129. },
  26130. enumerable: true,
  26131. configurable: true
  26132. });
  26133. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  26134. get: function () {
  26135. return this._texturesEnabled;
  26136. },
  26137. /**
  26138. * Gets or sets a boolean indicating if textures are enabled on this scene
  26139. */
  26140. set: function (value) {
  26141. if (this._texturesEnabled === value) {
  26142. return;
  26143. }
  26144. this._texturesEnabled = value;
  26145. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26146. },
  26147. enumerable: true,
  26148. configurable: true
  26149. });
  26150. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  26151. get: function () {
  26152. return this._skeletonsEnabled;
  26153. },
  26154. /**
  26155. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  26156. */
  26157. set: function (value) {
  26158. if (this._skeletonsEnabled === value) {
  26159. return;
  26160. }
  26161. this._skeletonsEnabled = value;
  26162. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  26163. },
  26164. enumerable: true,
  26165. configurable: true
  26166. });
  26167. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  26168. /** @hidden */
  26169. get: function () {
  26170. return this._alternateRendering;
  26171. },
  26172. enumerable: true,
  26173. configurable: true
  26174. });
  26175. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  26176. /**
  26177. * Gets the list of frustum planes (built from the active camera)
  26178. */
  26179. get: function () {
  26180. return this._frustumPlanes;
  26181. },
  26182. enumerable: true,
  26183. configurable: true
  26184. });
  26185. /**
  26186. * Registers the transient components if needed.
  26187. */
  26188. Scene.prototype._registerTransientComponents = function () {
  26189. // Register components that have been associated lately to the scene.
  26190. if (this._transientComponents.length > 0) {
  26191. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  26192. var component = _a[_i];
  26193. component.register();
  26194. }
  26195. this._transientComponents = [];
  26196. }
  26197. };
  26198. /**
  26199. * @hidden
  26200. * Add a component to the scene.
  26201. * Note that the ccomponent could be registered on th next frame if this is called after
  26202. * the register component stage.
  26203. * @param component Defines the component to add to the scene
  26204. */
  26205. Scene.prototype._addComponent = function (component) {
  26206. this._components.push(component);
  26207. this._transientComponents.push(component);
  26208. var serializableComponent = component;
  26209. if (serializableComponent.addFromContainer) {
  26210. this._serializableComponents.push(serializableComponent);
  26211. }
  26212. };
  26213. /**
  26214. * @hidden
  26215. * Gets a component from the scene.
  26216. * @param name defines the name of the component to retrieve
  26217. * @returns the component or null if not present
  26218. */
  26219. Scene.prototype._getComponent = function (name) {
  26220. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  26221. var component = _a[_i];
  26222. if (component.name === name) {
  26223. return component;
  26224. }
  26225. }
  26226. return null;
  26227. };
  26228. /**
  26229. * @hidden
  26230. */
  26231. Scene.prototype._getDefaultMeshCandidates = function () {
  26232. this._defaultMeshCandidates.data = this.meshes;
  26233. this._defaultMeshCandidates.length = this.meshes.length;
  26234. return this._defaultMeshCandidates;
  26235. };
  26236. /**
  26237. * @hidden
  26238. */
  26239. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  26240. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  26241. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  26242. return this._defaultSubMeshCandidates;
  26243. };
  26244. /**
  26245. * Sets the default candidate providers for the scene.
  26246. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  26247. * and getCollidingSubMeshCandidates to their default function
  26248. */
  26249. Scene.prototype.setDefaultCandidateProviders = function () {
  26250. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  26251. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26252. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26253. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26254. };
  26255. Object.defineProperty(Scene.prototype, "workerCollisions", {
  26256. /**
  26257. * Gets a boolean indicating if collisions are processed on a web worker
  26258. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  26259. */
  26260. get: function () {
  26261. return this._workerCollisions;
  26262. },
  26263. set: function (enabled) {
  26264. if (!BABYLON.CollisionCoordinatorLegacy) {
  26265. return;
  26266. }
  26267. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  26268. this._workerCollisions = enabled;
  26269. if (this.collisionCoordinator) {
  26270. this.collisionCoordinator.destroy();
  26271. }
  26272. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  26273. this.collisionCoordinator.init(this);
  26274. },
  26275. enumerable: true,
  26276. configurable: true
  26277. });
  26278. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  26279. /**
  26280. * Gets the mesh that is currently under the pointer
  26281. */
  26282. get: function () {
  26283. return this._pointerOverMesh;
  26284. },
  26285. enumerable: true,
  26286. configurable: true
  26287. });
  26288. Object.defineProperty(Scene.prototype, "pointerX", {
  26289. /**
  26290. * Gets the current on-screen X position of the pointer
  26291. */
  26292. get: function () {
  26293. return this._pointerX;
  26294. },
  26295. enumerable: true,
  26296. configurable: true
  26297. });
  26298. Object.defineProperty(Scene.prototype, "pointerY", {
  26299. /**
  26300. * Gets the current on-screen Y position of the pointer
  26301. */
  26302. get: function () {
  26303. return this._pointerY;
  26304. },
  26305. enumerable: true,
  26306. configurable: true
  26307. });
  26308. /**
  26309. * Gets the cached material (ie. the latest rendered one)
  26310. * @returns the cached material
  26311. */
  26312. Scene.prototype.getCachedMaterial = function () {
  26313. return this._cachedMaterial;
  26314. };
  26315. /**
  26316. * Gets the cached effect (ie. the latest rendered one)
  26317. * @returns the cached effect
  26318. */
  26319. Scene.prototype.getCachedEffect = function () {
  26320. return this._cachedEffect;
  26321. };
  26322. /**
  26323. * Gets the cached visibility state (ie. the latest rendered one)
  26324. * @returns the cached visibility state
  26325. */
  26326. Scene.prototype.getCachedVisibility = function () {
  26327. return this._cachedVisibility;
  26328. };
  26329. /**
  26330. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  26331. * @param material defines the current material
  26332. * @param effect defines the current effect
  26333. * @param visibility defines the current visibility state
  26334. * @returns true if one parameter is not cached
  26335. */
  26336. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  26337. if (visibility === void 0) { visibility = 1; }
  26338. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  26339. };
  26340. /**
  26341. * Gets the engine associated with the scene
  26342. * @returns an Engine
  26343. */
  26344. Scene.prototype.getEngine = function () {
  26345. return this._engine;
  26346. };
  26347. /**
  26348. * Gets the total number of vertices rendered per frame
  26349. * @returns the total number of vertices rendered per frame
  26350. */
  26351. Scene.prototype.getTotalVertices = function () {
  26352. return this._totalVertices.current;
  26353. };
  26354. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  26355. /**
  26356. * Gets the performance counter for total vertices
  26357. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26358. */
  26359. get: function () {
  26360. return this._totalVertices;
  26361. },
  26362. enumerable: true,
  26363. configurable: true
  26364. });
  26365. /**
  26366. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  26367. * @returns the total number of active indices rendered per frame
  26368. */
  26369. Scene.prototype.getActiveIndices = function () {
  26370. return this._activeIndices.current;
  26371. };
  26372. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  26373. /**
  26374. * Gets the performance counter for active indices
  26375. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26376. */
  26377. get: function () {
  26378. return this._activeIndices;
  26379. },
  26380. enumerable: true,
  26381. configurable: true
  26382. });
  26383. /**
  26384. * Gets the total number of active particles rendered per frame
  26385. * @returns the total number of active particles rendered per frame
  26386. */
  26387. Scene.prototype.getActiveParticles = function () {
  26388. return this._activeParticles.current;
  26389. };
  26390. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26391. /**
  26392. * Gets the performance counter for active particles
  26393. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26394. */
  26395. get: function () {
  26396. return this._activeParticles;
  26397. },
  26398. enumerable: true,
  26399. configurable: true
  26400. });
  26401. /**
  26402. * Gets the total number of active bones rendered per frame
  26403. * @returns the total number of active bones rendered per frame
  26404. */
  26405. Scene.prototype.getActiveBones = function () {
  26406. return this._activeBones.current;
  26407. };
  26408. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26409. /**
  26410. * Gets the performance counter for active bones
  26411. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26412. */
  26413. get: function () {
  26414. return this._activeBones;
  26415. },
  26416. enumerable: true,
  26417. configurable: true
  26418. });
  26419. /**
  26420. * Gets the array of active meshes
  26421. * @returns an array of AbstractMesh
  26422. */
  26423. Scene.prototype.getActiveMeshes = function () {
  26424. return this._activeMeshes;
  26425. };
  26426. /**
  26427. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26428. * @returns a number
  26429. */
  26430. Scene.prototype.getAnimationRatio = function () {
  26431. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26432. };
  26433. /**
  26434. * Gets an unique Id for the current render phase
  26435. * @returns a number
  26436. */
  26437. Scene.prototype.getRenderId = function () {
  26438. return this._renderId;
  26439. };
  26440. /**
  26441. * Gets an unique Id for the current frame
  26442. * @returns a number
  26443. */
  26444. Scene.prototype.getFrameId = function () {
  26445. return this._frameId;
  26446. };
  26447. /** Call this function if you want to manually increment the render Id*/
  26448. Scene.prototype.incrementRenderId = function () {
  26449. this._renderId++;
  26450. };
  26451. Scene.prototype._updatePointerPosition = function (evt) {
  26452. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26453. if (!canvasRect) {
  26454. return;
  26455. }
  26456. this._pointerX = evt.clientX - canvasRect.left;
  26457. this._pointerY = evt.clientY - canvasRect.top;
  26458. this._unTranslatedPointerX = this._pointerX;
  26459. this._unTranslatedPointerY = this._pointerY;
  26460. };
  26461. Scene.prototype._createUbo = function () {
  26462. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26463. this._sceneUbo.addUniform("viewProjection", 16);
  26464. this._sceneUbo.addUniform("view", 16);
  26465. };
  26466. Scene.prototype._createAlternateUbo = function () {
  26467. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26468. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26469. this._alternateSceneUbo.addUniform("view", 16);
  26470. };
  26471. // Pointers handling
  26472. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26473. if (pointerInfo.pickInfo) {
  26474. if (!pointerInfo.pickInfo.ray) {
  26475. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26476. }
  26477. }
  26478. };
  26479. /**
  26480. * Use this method to simulate a pointer move on a mesh
  26481. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26482. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26483. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26484. * @returns the current scene
  26485. */
  26486. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26487. var evt = new PointerEvent("pointermove", pointerEventInit);
  26488. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26489. return this;
  26490. }
  26491. return this._processPointerMove(pickResult, evt);
  26492. };
  26493. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26494. var canvas = this._engine.getRenderingCanvas();
  26495. if (!canvas) {
  26496. return this;
  26497. }
  26498. // Restore pointer
  26499. canvas.style.cursor = this.defaultCursor;
  26500. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26501. if (isMeshPicked) {
  26502. this.setPointerOverMesh(pickResult.pickedMesh);
  26503. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26504. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26505. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26506. }
  26507. else {
  26508. canvas.style.cursor = this.hoverCursor;
  26509. }
  26510. }
  26511. }
  26512. else {
  26513. this.setPointerOverMesh(null);
  26514. }
  26515. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26516. var step = _a[_i];
  26517. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26518. }
  26519. if (pickResult) {
  26520. var type = evt.type === this._wheelEventName ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26521. if (this.onPointerMove) {
  26522. this.onPointerMove(evt, pickResult, type);
  26523. }
  26524. if (this.onPointerObservable.hasObservers()) {
  26525. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26526. this._setRayOnPointerInfo(pi);
  26527. this.onPointerObservable.notifyObservers(pi, type);
  26528. }
  26529. }
  26530. return this;
  26531. };
  26532. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26533. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26534. if (pickResult) {
  26535. pi.ray = pickResult.ray;
  26536. }
  26537. this.onPrePointerObservable.notifyObservers(pi, type);
  26538. if (pi.skipOnPointerObservable) {
  26539. return true;
  26540. }
  26541. else {
  26542. return false;
  26543. }
  26544. };
  26545. /**
  26546. * Use this method to simulate a pointer down on a mesh
  26547. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26548. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26549. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26550. * @returns the current scene
  26551. */
  26552. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26553. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26554. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26555. return this;
  26556. }
  26557. return this._processPointerDown(pickResult, evt);
  26558. };
  26559. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26560. var _this = this;
  26561. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26562. this._pickedDownMesh = pickResult.pickedMesh;
  26563. var actionManager = pickResult.pickedMesh.actionManager;
  26564. if (actionManager) {
  26565. if (actionManager.hasPickTriggers) {
  26566. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26567. switch (evt.button) {
  26568. case 0:
  26569. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26570. break;
  26571. case 1:
  26572. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26573. break;
  26574. case 2:
  26575. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26576. break;
  26577. }
  26578. }
  26579. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26580. window.setTimeout(function () {
  26581. 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);
  26582. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26583. if (_this._totalPointersPressed !== 0 &&
  26584. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26585. !_this._isPointerSwiping()) {
  26586. _this._startingPointerTime = 0;
  26587. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26588. }
  26589. }
  26590. }, Scene.LongPressDelay);
  26591. }
  26592. }
  26593. }
  26594. else {
  26595. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26596. var step = _a[_i];
  26597. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26598. }
  26599. }
  26600. if (pickResult) {
  26601. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26602. if (this.onPointerDown) {
  26603. this.onPointerDown(evt, pickResult, type);
  26604. }
  26605. if (this.onPointerObservable.hasObservers()) {
  26606. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26607. this._setRayOnPointerInfo(pi);
  26608. this.onPointerObservable.notifyObservers(pi, type);
  26609. }
  26610. }
  26611. return this;
  26612. };
  26613. /**
  26614. * Use this method to simulate a pointer up on a mesh
  26615. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26616. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26617. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26618. * @param doubleTap indicates that the pointer up event should be considered as part of a double click (false by default)
  26619. * @returns the current scene
  26620. */
  26621. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit, doubleTap) {
  26622. var evt = new PointerEvent("pointerup", pointerEventInit);
  26623. var clickInfo = new ClickInfo();
  26624. if (doubleTap) {
  26625. clickInfo.doubleClick = true;
  26626. }
  26627. else {
  26628. clickInfo.singleClick = true;
  26629. }
  26630. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26631. return this;
  26632. }
  26633. return this._processPointerUp(pickResult, evt, clickInfo);
  26634. };
  26635. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26636. if (pickResult && pickResult && pickResult.pickedMesh) {
  26637. this._pickedUpMesh = pickResult.pickedMesh;
  26638. if (this._pickedDownMesh === this._pickedUpMesh) {
  26639. if (this.onPointerPick) {
  26640. this.onPointerPick(evt, pickResult);
  26641. }
  26642. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26643. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26644. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26645. this._setRayOnPointerInfo(pi);
  26646. this.onPointerObservable.notifyObservers(pi, type_1);
  26647. }
  26648. }
  26649. if (pickResult.pickedMesh.actionManager) {
  26650. if (clickInfo.ignore) {
  26651. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26652. }
  26653. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26654. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26655. }
  26656. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26657. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26658. }
  26659. }
  26660. }
  26661. else {
  26662. if (!clickInfo.ignore) {
  26663. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26664. var step = _a[_i];
  26665. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26666. }
  26667. }
  26668. }
  26669. if (this._pickedDownMesh &&
  26670. this._pickedDownMesh.actionManager &&
  26671. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26672. this._pickedDownMesh !== this._pickedUpMesh) {
  26673. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26674. }
  26675. var type = 0;
  26676. if (this.onPointerObservable.hasObservers()) {
  26677. if (!clickInfo.ignore && !clickInfo.hasSwiped) {
  26678. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26679. type = BABYLON.PointerEventTypes.POINTERTAP;
  26680. }
  26681. else if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26682. type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26683. }
  26684. if (type) {
  26685. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26686. this._setRayOnPointerInfo(pi);
  26687. this.onPointerObservable.notifyObservers(pi, type);
  26688. }
  26689. }
  26690. if (!clickInfo.ignore) {
  26691. type = BABYLON.PointerEventTypes.POINTERUP;
  26692. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26693. this._setRayOnPointerInfo(pi);
  26694. this.onPointerObservable.notifyObservers(pi, type);
  26695. }
  26696. }
  26697. if (this.onPointerUp && !clickInfo.ignore) {
  26698. this.onPointerUp(evt, pickResult, type);
  26699. }
  26700. return this;
  26701. };
  26702. /**
  26703. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26704. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26705. * @returns true if the pointer was captured
  26706. */
  26707. Scene.prototype.isPointerCaptured = function (pointerId) {
  26708. if (pointerId === void 0) { pointerId = 0; }
  26709. return this._pointerCaptures[pointerId];
  26710. };
  26711. /** @hidden */
  26712. Scene.prototype._isPointerSwiping = function () {
  26713. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26714. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26715. };
  26716. /**
  26717. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26718. * @param attachUp defines if you want to attach events to pointerup
  26719. * @param attachDown defines if you want to attach events to pointerdown
  26720. * @param attachMove defines if you want to attach events to pointermove
  26721. */
  26722. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26723. var _this = this;
  26724. if (attachUp === void 0) { attachUp = true; }
  26725. if (attachDown === void 0) { attachDown = true; }
  26726. if (attachMove === void 0) { attachMove = true; }
  26727. this._initActionManager = function (act, clickInfo) {
  26728. if (!_this._meshPickProceed) {
  26729. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26730. _this._currentPickResult = pickResult;
  26731. if (pickResult) {
  26732. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26733. }
  26734. _this._meshPickProceed = true;
  26735. }
  26736. return act;
  26737. };
  26738. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26739. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26740. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26741. btn !== _this._previousButtonPressed) {
  26742. _this._doubleClickOccured = false;
  26743. clickInfo.singleClick = true;
  26744. clickInfo.ignore = false;
  26745. cb(clickInfo, _this._currentPickResult);
  26746. }
  26747. };
  26748. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26749. var clickInfo = new ClickInfo();
  26750. _this._currentPickResult = null;
  26751. var act = null;
  26752. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26753. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26754. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26755. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26756. act = _this._initActionManager(act, clickInfo);
  26757. if (act) {
  26758. checkPicking = act.hasPickTriggers;
  26759. }
  26760. }
  26761. var needToIgnoreNext = false;
  26762. if (checkPicking) {
  26763. var btn = evt.button;
  26764. clickInfo.hasSwiped = _this._isPointerSwiping();
  26765. if (!clickInfo.hasSwiped) {
  26766. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26767. if (!checkSingleClickImmediately) {
  26768. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26769. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26770. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26771. act = _this._initActionManager(act, clickInfo);
  26772. if (act) {
  26773. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26774. }
  26775. }
  26776. }
  26777. if (checkSingleClickImmediately) {
  26778. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26779. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26780. btn !== _this._previousButtonPressed) {
  26781. clickInfo.singleClick = true;
  26782. cb(clickInfo, _this._currentPickResult);
  26783. needToIgnoreNext = true;
  26784. }
  26785. }
  26786. // at least one double click is required to be check and exclusive double click is enabled
  26787. else {
  26788. // wait that no double click has been raised during the double click delay
  26789. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26790. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26791. }
  26792. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26793. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26794. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26795. act = _this._initActionManager(act, clickInfo);
  26796. if (act) {
  26797. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26798. }
  26799. }
  26800. if (checkDoubleClick) {
  26801. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26802. if (btn === _this._previousButtonPressed &&
  26803. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26804. !_this._doubleClickOccured) {
  26805. // pointer has not moved for 2 clicks, it's a double click
  26806. if (!clickInfo.hasSwiped &&
  26807. !_this._isPointerSwiping()) {
  26808. _this._previousStartingPointerTime = 0;
  26809. _this._doubleClickOccured = true;
  26810. clickInfo.doubleClick = true;
  26811. clickInfo.ignore = false;
  26812. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26813. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26814. }
  26815. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26816. cb(clickInfo, _this._currentPickResult);
  26817. }
  26818. // if the two successive clicks are too far, it's just two simple clicks
  26819. else {
  26820. _this._doubleClickOccured = false;
  26821. _this._previousStartingPointerTime = _this._startingPointerTime;
  26822. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26823. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26824. _this._previousButtonPressed = btn;
  26825. if (Scene.ExclusiveDoubleClickMode) {
  26826. if (_this._previousDelayedSimpleClickTimeout) {
  26827. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26828. }
  26829. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26830. cb(clickInfo, _this._previousPickResult);
  26831. }
  26832. else {
  26833. cb(clickInfo, _this._currentPickResult);
  26834. }
  26835. }
  26836. needToIgnoreNext = true;
  26837. }
  26838. // just the first click of the double has been raised
  26839. else {
  26840. _this._doubleClickOccured = false;
  26841. _this._previousStartingPointerTime = _this._startingPointerTime;
  26842. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26843. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26844. _this._previousButtonPressed = btn;
  26845. }
  26846. }
  26847. }
  26848. }
  26849. if (!needToIgnoreNext) {
  26850. cb(clickInfo, _this._currentPickResult);
  26851. }
  26852. };
  26853. this._onPointerMove = function (evt) {
  26854. _this._updatePointerPosition(evt);
  26855. // PreObservable support
  26856. if (_this._checkPrePointerObservable(null, evt, evt.type === _this._wheelEventName ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26857. return;
  26858. }
  26859. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26860. return;
  26861. }
  26862. if (!_this.pointerMovePredicate) {
  26863. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26864. }
  26865. // Meshes
  26866. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26867. _this._processPointerMove(pickResult, evt);
  26868. };
  26869. this._onPointerDown = function (evt) {
  26870. _this._totalPointersPressed++;
  26871. _this._pickedDownMesh = null;
  26872. _this._meshPickProceed = false;
  26873. _this._updatePointerPosition(evt);
  26874. if (_this.preventDefaultOnPointerDown && canvas) {
  26875. evt.preventDefault();
  26876. canvas.focus();
  26877. }
  26878. _this._startingPointerPosition.x = _this._pointerX;
  26879. _this._startingPointerPosition.y = _this._pointerY;
  26880. _this._startingPointerTime = Date.now();
  26881. // PreObservable support
  26882. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26883. return;
  26884. }
  26885. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26886. return;
  26887. }
  26888. _this._pointerCaptures[evt.pointerId] = true;
  26889. if (!_this.pointerDownPredicate) {
  26890. _this.pointerDownPredicate = function (mesh) {
  26891. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26892. };
  26893. }
  26894. // Meshes
  26895. _this._pickedDownMesh = null;
  26896. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26897. _this._processPointerDown(pickResult, evt);
  26898. };
  26899. this._onPointerUp = function (evt) {
  26900. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26901. return; // So we need to test it the pointer down was pressed before.
  26902. }
  26903. _this._totalPointersPressed--;
  26904. _this._pickedUpMesh = null;
  26905. _this._meshPickProceed = false;
  26906. _this._updatePointerPosition(evt);
  26907. if (_this.preventDefaultOnPointerUp && canvas) {
  26908. evt.preventDefault();
  26909. canvas.focus();
  26910. }
  26911. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26912. // PreObservable support
  26913. if (_this.onPrePointerObservable.hasObservers()) {
  26914. if (!clickInfo.ignore) {
  26915. if (!clickInfo.hasSwiped) {
  26916. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26917. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26918. return;
  26919. }
  26920. }
  26921. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26922. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26923. return;
  26924. }
  26925. }
  26926. }
  26927. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26928. return;
  26929. }
  26930. }
  26931. }
  26932. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26933. return;
  26934. }
  26935. _this._pointerCaptures[evt.pointerId] = false;
  26936. if (!_this.pointerUpPredicate) {
  26937. _this.pointerUpPredicate = function (mesh) {
  26938. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26939. };
  26940. }
  26941. // Meshes
  26942. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26943. _this._initActionManager(null, clickInfo);
  26944. }
  26945. if (!pickResult) {
  26946. pickResult = _this._currentPickResult;
  26947. }
  26948. _this._processPointerUp(pickResult, evt, clickInfo);
  26949. _this._previousPickResult = _this._currentPickResult;
  26950. });
  26951. };
  26952. this._onKeyDown = function (evt) {
  26953. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26954. if (_this.onPreKeyboardObservable.hasObservers()) {
  26955. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26956. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26957. if (pi.skipOnPointerObservable) {
  26958. return;
  26959. }
  26960. }
  26961. if (_this.onKeyboardObservable.hasObservers()) {
  26962. var pi = new BABYLON.KeyboardInfo(type, evt);
  26963. _this.onKeyboardObservable.notifyObservers(pi, type);
  26964. }
  26965. if (_this.actionManager) {
  26966. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26967. }
  26968. };
  26969. this._onKeyUp = function (evt) {
  26970. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26971. if (_this.onPreKeyboardObservable.hasObservers()) {
  26972. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26973. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26974. if (pi.skipOnPointerObservable) {
  26975. return;
  26976. }
  26977. }
  26978. if (_this.onKeyboardObservable.hasObservers()) {
  26979. var pi = new BABYLON.KeyboardInfo(type, evt);
  26980. _this.onKeyboardObservable.notifyObservers(pi, type);
  26981. }
  26982. if (_this.actionManager) {
  26983. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26984. }
  26985. };
  26986. var engine = this.getEngine();
  26987. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26988. if (!canvas) {
  26989. return;
  26990. }
  26991. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26992. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26993. });
  26994. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26995. if (!canvas) {
  26996. return;
  26997. }
  26998. canvas.removeEventListener("keydown", _this._onKeyDown);
  26999. canvas.removeEventListener("keyup", _this._onKeyUp);
  27000. });
  27001. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27002. var canvas = this._engine.getRenderingCanvas();
  27003. if (!canvas) {
  27004. return;
  27005. }
  27006. if (attachMove) {
  27007. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  27008. // Wheel
  27009. this._wheelEventName = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
  27010. document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
  27011. "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox
  27012. canvas.addEventListener(this._wheelEventName, this._onPointerMove, false);
  27013. }
  27014. if (attachDown) {
  27015. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  27016. }
  27017. if (attachUp) {
  27018. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  27019. }
  27020. canvas.tabIndex = 1;
  27021. };
  27022. /** Detaches all event handlers*/
  27023. Scene.prototype.detachControl = function () {
  27024. var engine = this.getEngine();
  27025. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27026. var canvas = engine.getRenderingCanvas();
  27027. if (!canvas) {
  27028. return;
  27029. }
  27030. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  27031. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  27032. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  27033. if (this._onCanvasBlurObserver) {
  27034. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  27035. }
  27036. if (this._onCanvasFocusObserver) {
  27037. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  27038. }
  27039. // Wheel
  27040. canvas.removeEventListener(this._wheelEventName, this._onPointerMove);
  27041. // Keyboard
  27042. canvas.removeEventListener("keydown", this._onKeyDown);
  27043. canvas.removeEventListener("keyup", this._onKeyUp);
  27044. // Observables
  27045. this.onKeyboardObservable.clear();
  27046. this.onPreKeyboardObservable.clear();
  27047. this.onPointerObservable.clear();
  27048. this.onPrePointerObservable.clear();
  27049. };
  27050. /**
  27051. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  27052. * Delay loaded resources are not taking in account
  27053. * @return true if all required resources are ready
  27054. */
  27055. Scene.prototype.isReady = function () {
  27056. if (this._isDisposed) {
  27057. return false;
  27058. }
  27059. var index;
  27060. var engine = this.getEngine();
  27061. // Effects
  27062. if (!engine.areAllEffectsReady()) {
  27063. return false;
  27064. }
  27065. // Pending data
  27066. if (this._pendingData.length > 0) {
  27067. return false;
  27068. }
  27069. // Meshes
  27070. for (index = 0; index < this.meshes.length; index++) {
  27071. var mesh = this.meshes[index];
  27072. if (!mesh.isEnabled()) {
  27073. continue;
  27074. }
  27075. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27076. continue;
  27077. }
  27078. if (!mesh.isReady(true)) {
  27079. return false;
  27080. }
  27081. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  27082. // Is Ready For Mesh
  27083. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  27084. var step = _a[_i];
  27085. if (!step.action(mesh, hardwareInstancedRendering)) {
  27086. return false;
  27087. }
  27088. }
  27089. }
  27090. // Geometries
  27091. for (index = 0; index < this.geometries.length; index++) {
  27092. var geometry = this.geometries[index];
  27093. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27094. return false;
  27095. }
  27096. }
  27097. // Post-processes
  27098. if (this.activeCameras && this.activeCameras.length > 0) {
  27099. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  27100. var camera = _c[_b];
  27101. if (!camera.isReady(true)) {
  27102. return false;
  27103. }
  27104. }
  27105. }
  27106. else if (this.activeCamera) {
  27107. if (!this.activeCamera.isReady(true)) {
  27108. return false;
  27109. }
  27110. }
  27111. // Particles
  27112. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  27113. var particleSystem = _e[_d];
  27114. if (!particleSystem.isReady()) {
  27115. return false;
  27116. }
  27117. }
  27118. return true;
  27119. };
  27120. /** Resets all cached information relative to material (including effect and visibility) */
  27121. Scene.prototype.resetCachedMaterial = function () {
  27122. this._cachedMaterial = null;
  27123. this._cachedEffect = null;
  27124. this._cachedVisibility = null;
  27125. };
  27126. /**
  27127. * Registers a function to be called before every frame render
  27128. * @param func defines the function to register
  27129. */
  27130. Scene.prototype.registerBeforeRender = function (func) {
  27131. this.onBeforeRenderObservable.add(func);
  27132. };
  27133. /**
  27134. * Unregisters a function called before every frame render
  27135. * @param func defines the function to unregister
  27136. */
  27137. Scene.prototype.unregisterBeforeRender = function (func) {
  27138. this.onBeforeRenderObservable.removeCallback(func);
  27139. };
  27140. /**
  27141. * Registers a function to be called after every frame render
  27142. * @param func defines the function to register
  27143. */
  27144. Scene.prototype.registerAfterRender = function (func) {
  27145. this.onAfterRenderObservable.add(func);
  27146. };
  27147. /**
  27148. * Unregisters a function called after every frame render
  27149. * @param func defines the function to unregister
  27150. */
  27151. Scene.prototype.unregisterAfterRender = function (func) {
  27152. this.onAfterRenderObservable.removeCallback(func);
  27153. };
  27154. Scene.prototype._executeOnceBeforeRender = function (func) {
  27155. var _this = this;
  27156. var execFunc = function () {
  27157. func();
  27158. setTimeout(function () {
  27159. _this.unregisterBeforeRender(execFunc);
  27160. });
  27161. };
  27162. this.registerBeforeRender(execFunc);
  27163. };
  27164. /**
  27165. * The provided function will run before render once and will be disposed afterwards.
  27166. * A timeout delay can be provided so that the function will be executed in N ms.
  27167. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  27168. * @param func The function to be executed.
  27169. * @param timeout optional delay in ms
  27170. */
  27171. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  27172. var _this = this;
  27173. if (timeout !== undefined) {
  27174. setTimeout(function () {
  27175. _this._executeOnceBeforeRender(func);
  27176. }, timeout);
  27177. }
  27178. else {
  27179. this._executeOnceBeforeRender(func);
  27180. }
  27181. };
  27182. /** @hidden */
  27183. Scene.prototype._addPendingData = function (data) {
  27184. this._pendingData.push(data);
  27185. };
  27186. /** @hidden */
  27187. Scene.prototype._removePendingData = function (data) {
  27188. var wasLoading = this.isLoading;
  27189. var index = this._pendingData.indexOf(data);
  27190. if (index !== -1) {
  27191. this._pendingData.splice(index, 1);
  27192. }
  27193. if (wasLoading && !this.isLoading) {
  27194. this.onDataLoadedObservable.notifyObservers(this);
  27195. }
  27196. };
  27197. /**
  27198. * Returns the number of items waiting to be loaded
  27199. * @returns the number of items waiting to be loaded
  27200. */
  27201. Scene.prototype.getWaitingItemsCount = function () {
  27202. return this._pendingData.length;
  27203. };
  27204. Object.defineProperty(Scene.prototype, "isLoading", {
  27205. /**
  27206. * Returns a boolean indicating if the scene is still loading data
  27207. */
  27208. get: function () {
  27209. return this._pendingData.length > 0;
  27210. },
  27211. enumerable: true,
  27212. configurable: true
  27213. });
  27214. /**
  27215. * Registers a function to be executed when the scene is ready
  27216. * @param {Function} func - the function to be executed
  27217. */
  27218. Scene.prototype.executeWhenReady = function (func) {
  27219. var _this = this;
  27220. this.onReadyObservable.add(func);
  27221. if (this._executeWhenReadyTimeoutId !== -1) {
  27222. return;
  27223. }
  27224. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27225. _this._checkIsReady();
  27226. }, 150);
  27227. };
  27228. /**
  27229. * Returns a promise that resolves when the scene is ready
  27230. * @returns A promise that resolves when the scene is ready
  27231. */
  27232. Scene.prototype.whenReadyAsync = function () {
  27233. var _this = this;
  27234. return new Promise(function (resolve) {
  27235. _this.executeWhenReady(function () {
  27236. resolve();
  27237. });
  27238. });
  27239. };
  27240. /** @hidden */
  27241. Scene.prototype._checkIsReady = function () {
  27242. var _this = this;
  27243. this._registerTransientComponents();
  27244. if (this.isReady()) {
  27245. this.onReadyObservable.notifyObservers(this);
  27246. this.onReadyObservable.clear();
  27247. this._executeWhenReadyTimeoutId = -1;
  27248. return;
  27249. }
  27250. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27251. _this._checkIsReady();
  27252. }, 150);
  27253. };
  27254. // Animations
  27255. /**
  27256. * Will start the animation sequence of a given target
  27257. * @param target defines the target
  27258. * @param from defines from which frame should animation start
  27259. * @param to defines until which frame should animation run.
  27260. * @param weight defines the weight to apply to the animation (1.0 by default)
  27261. * @param loop defines if the animation loops
  27262. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27263. * @param onAnimationEnd defines the function to be executed when the animation ends
  27264. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27265. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27266. * @returns the animatable object created for this animation
  27267. */
  27268. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  27269. if (weight === void 0) { weight = 1.0; }
  27270. if (speedRatio === void 0) { speedRatio = 1.0; }
  27271. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  27272. returnedAnimatable.weight = weight;
  27273. return returnedAnimatable;
  27274. };
  27275. /**
  27276. * Will start the animation sequence of a given target
  27277. * @param target defines the target
  27278. * @param from defines from which frame should animation start
  27279. * @param to defines until which frame should animation run.
  27280. * @param loop defines if the animation loops
  27281. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27282. * @param onAnimationEnd defines the function to be executed when the animation ends
  27283. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27284. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27285. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27286. * @returns the animatable object created for this animation
  27287. */
  27288. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  27289. if (speedRatio === void 0) { speedRatio = 1.0; }
  27290. if (stopCurrent === void 0) { stopCurrent = true; }
  27291. if (from > to && speedRatio > 0) {
  27292. speedRatio *= -1;
  27293. }
  27294. if (stopCurrent) {
  27295. this.stopAnimation(target, undefined, targetMask);
  27296. }
  27297. if (!animatable) {
  27298. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  27299. }
  27300. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  27301. // Local animations
  27302. if (target.animations && shouldRunTargetAnimations) {
  27303. animatable.appendAnimations(target, target.animations);
  27304. }
  27305. // Children animations
  27306. if (target.getAnimatables) {
  27307. var animatables = target.getAnimatables();
  27308. for (var index = 0; index < animatables.length; index++) {
  27309. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  27310. }
  27311. }
  27312. animatable.reset();
  27313. return animatable;
  27314. };
  27315. /**
  27316. * Begin a new animation on a given node
  27317. * @param target defines the target where the animation will take place
  27318. * @param animations defines the list of animations to start
  27319. * @param from defines the initial value
  27320. * @param to defines the final value
  27321. * @param loop defines if you want animation to loop (off by default)
  27322. * @param speedRatio defines the speed ratio to apply to all animations
  27323. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27324. * @returns the list of created animatables
  27325. */
  27326. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27327. if (speedRatio === undefined) {
  27328. speedRatio = 1.0;
  27329. }
  27330. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  27331. return animatable;
  27332. };
  27333. /**
  27334. * Begin a new animation on a given node and its hierarchy
  27335. * @param target defines the root node where the animation will take place
  27336. * @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.
  27337. * @param animations defines the list of animations to start
  27338. * @param from defines the initial value
  27339. * @param to defines the final value
  27340. * @param loop defines if you want animation to loop (off by default)
  27341. * @param speedRatio defines the speed ratio to apply to all animations
  27342. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27343. * @returns the list of animatables created for all nodes
  27344. */
  27345. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27346. var children = target.getDescendants(directDescendantsOnly);
  27347. var result = [];
  27348. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27349. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27350. var child = children_1[_i];
  27351. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27352. }
  27353. return result;
  27354. };
  27355. /**
  27356. * Gets the animatable associated with a specific target
  27357. * @param target defines the target of the animatable
  27358. * @returns the required animatable if found
  27359. */
  27360. Scene.prototype.getAnimatableByTarget = function (target) {
  27361. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27362. if (this._activeAnimatables[index].target === target) {
  27363. return this._activeAnimatables[index];
  27364. }
  27365. }
  27366. return null;
  27367. };
  27368. /**
  27369. * Gets all animatables associated with a given target
  27370. * @param target defines the target to look animatables for
  27371. * @returns an array of Animatables
  27372. */
  27373. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27374. var result = [];
  27375. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27376. if (this._activeAnimatables[index].target === target) {
  27377. result.push(this._activeAnimatables[index]);
  27378. }
  27379. }
  27380. return result;
  27381. };
  27382. Object.defineProperty(Scene.prototype, "animatables", {
  27383. /**
  27384. * Gets all animatable attached to the scene
  27385. */
  27386. get: function () {
  27387. return this._activeAnimatables;
  27388. },
  27389. enumerable: true,
  27390. configurable: true
  27391. });
  27392. /**
  27393. * Will stop the animation of the given target
  27394. * @param target - the target
  27395. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27396. * @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)
  27397. */
  27398. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27399. var animatables = this.getAllAnimatablesByTarget(target);
  27400. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27401. var animatable = animatables_1[_i];
  27402. animatable.stop(animationName, targetMask);
  27403. }
  27404. };
  27405. /**
  27406. * Stops and removes all animations that have been applied to the scene
  27407. */
  27408. Scene.prototype.stopAllAnimations = function () {
  27409. if (this._activeAnimatables) {
  27410. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27411. this._activeAnimatables[i].stop();
  27412. }
  27413. this._activeAnimatables = [];
  27414. }
  27415. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27416. var group = _a[_i];
  27417. group.stop();
  27418. }
  27419. };
  27420. Scene.prototype._animate = function () {
  27421. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27422. return;
  27423. }
  27424. // Getting time
  27425. var now = BABYLON.Tools.Now;
  27426. if (!this._animationTimeLast) {
  27427. if (this._pendingData.length > 0) {
  27428. return;
  27429. }
  27430. this._animationTimeLast = now;
  27431. }
  27432. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27433. this._animationTime += deltaTime;
  27434. this._animationTimeLast = now;
  27435. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27436. this._activeAnimatables[index]._animate(this._animationTime);
  27437. }
  27438. // Late animation bindings
  27439. this._processLateAnimationBindings();
  27440. };
  27441. /** @hidden */
  27442. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27443. var target = runtimeAnimation.target;
  27444. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27445. if (!target._lateAnimationHolders) {
  27446. target._lateAnimationHolders = {};
  27447. }
  27448. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27449. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27450. totalWeight: 0,
  27451. animations: [],
  27452. originalValue: originalValue
  27453. };
  27454. }
  27455. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27456. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27457. };
  27458. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27459. var normalizer = 1.0;
  27460. var finalPosition = BABYLON.Tmp.Vector3[0];
  27461. var finalScaling = BABYLON.Tmp.Vector3[1];
  27462. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27463. var startIndex = 0;
  27464. var originalAnimation = holder.animations[0];
  27465. var originalValue = holder.originalValue;
  27466. var scale = 1;
  27467. if (holder.totalWeight < 1.0) {
  27468. // We need to mix the original value in
  27469. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27470. scale = 1.0 - holder.totalWeight;
  27471. }
  27472. else {
  27473. startIndex = 1;
  27474. // We need to normalize the weights
  27475. normalizer = holder.totalWeight;
  27476. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27477. scale = originalAnimation.weight / normalizer;
  27478. if (scale == 1) {
  27479. return originalAnimation.currentValue;
  27480. }
  27481. }
  27482. finalScaling.scaleInPlace(scale);
  27483. finalPosition.scaleInPlace(scale);
  27484. finalQuaternion.scaleInPlace(scale);
  27485. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27486. var runtimeAnimation = holder.animations[animIndex];
  27487. var scale = runtimeAnimation.weight / normalizer;
  27488. var currentPosition = BABYLON.Tmp.Vector3[2];
  27489. var currentScaling = BABYLON.Tmp.Vector3[3];
  27490. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27491. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27492. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27493. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27494. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27495. }
  27496. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27497. return originalAnimation._workValue;
  27498. };
  27499. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27500. var originalAnimation = holder.animations[0];
  27501. var originalValue = holder.originalValue;
  27502. if (holder.animations.length === 1) {
  27503. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27504. return refQuaternion;
  27505. }
  27506. var normalizer = 1.0;
  27507. var quaternions;
  27508. var weights;
  27509. if (holder.totalWeight < 1.0) {
  27510. var scale = 1.0 - holder.totalWeight;
  27511. quaternions = [];
  27512. weights = [];
  27513. quaternions.push(originalValue);
  27514. weights.push(scale);
  27515. }
  27516. else {
  27517. if (holder.animations.length === 2) { // Slerp as soon as we can
  27518. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27519. return refQuaternion;
  27520. }
  27521. quaternions = [];
  27522. weights = [];
  27523. normalizer = holder.totalWeight;
  27524. }
  27525. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27526. var runtimeAnimation = holder.animations[animIndex];
  27527. quaternions.push(runtimeAnimation.currentValue);
  27528. weights.push(runtimeAnimation.weight / normalizer);
  27529. }
  27530. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27531. var cumulativeAmount = 0;
  27532. var cumulativeQuaternion = null;
  27533. for (var index = 0; index < quaternions.length;) {
  27534. if (!cumulativeQuaternion) {
  27535. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27536. cumulativeQuaternion = refQuaternion;
  27537. cumulativeAmount = weights[index] + weights[index + 1];
  27538. index += 2;
  27539. continue;
  27540. }
  27541. cumulativeAmount += weights[index];
  27542. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27543. index++;
  27544. }
  27545. return cumulativeQuaternion;
  27546. };
  27547. Scene.prototype._processLateAnimationBindings = function () {
  27548. if (!this._registeredForLateAnimationBindings.length) {
  27549. return;
  27550. }
  27551. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27552. var target = this._registeredForLateAnimationBindings.data[index];
  27553. for (var path in target._lateAnimationHolders) {
  27554. var holder = target._lateAnimationHolders[path];
  27555. var originalAnimation = holder.animations[0];
  27556. var originalValue = holder.originalValue;
  27557. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27558. var finalValue = target[path];
  27559. if (matrixDecomposeMode) {
  27560. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27561. }
  27562. else {
  27563. var quaternionMode = originalValue.w !== undefined;
  27564. if (quaternionMode) {
  27565. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27566. }
  27567. else {
  27568. var startIndex = 0;
  27569. var normalizer = 1.0;
  27570. if (holder.totalWeight < 1.0) {
  27571. // We need to mix the original value in
  27572. if (originalValue.scale) {
  27573. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27574. }
  27575. else {
  27576. finalValue = originalValue * (1.0 - holder.totalWeight);
  27577. }
  27578. }
  27579. else {
  27580. // We need to normalize the weights
  27581. normalizer = holder.totalWeight;
  27582. var scale_1 = originalAnimation.weight / normalizer;
  27583. if (scale_1 !== 1) {
  27584. if (originalAnimation.currentValue.scale) {
  27585. finalValue = originalAnimation.currentValue.scale(scale_1);
  27586. }
  27587. else {
  27588. finalValue = originalAnimation.currentValue * scale_1;
  27589. }
  27590. }
  27591. else {
  27592. finalValue = originalAnimation.currentValue;
  27593. }
  27594. startIndex = 1;
  27595. }
  27596. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27597. var runtimeAnimation = holder.animations[animIndex];
  27598. var scale = runtimeAnimation.weight / normalizer;
  27599. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27600. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27601. }
  27602. else {
  27603. finalValue += runtimeAnimation.currentValue * scale;
  27604. }
  27605. }
  27606. }
  27607. }
  27608. target[path] = finalValue;
  27609. }
  27610. target._lateAnimationHolders = {};
  27611. }
  27612. this._registeredForLateAnimationBindings.reset();
  27613. };
  27614. // Matrix
  27615. /** @hidden */
  27616. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27617. this._useAlternateCameraConfiguration = active;
  27618. };
  27619. /**
  27620. * Gets the current view matrix
  27621. * @returns a Matrix
  27622. */
  27623. Scene.prototype.getViewMatrix = function () {
  27624. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27625. };
  27626. /**
  27627. * Gets the current projection matrix
  27628. * @returns a Matrix
  27629. */
  27630. Scene.prototype.getProjectionMatrix = function () {
  27631. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27632. };
  27633. /**
  27634. * Gets the current transform matrix
  27635. * @returns a Matrix made of View * Projection
  27636. */
  27637. Scene.prototype.getTransformMatrix = function () {
  27638. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27639. };
  27640. /**
  27641. * Sets the current transform matrix
  27642. * @param view defines the View matrix to use
  27643. * @param projection defines the Projection matrix to use
  27644. */
  27645. Scene.prototype.setTransformMatrix = function (view, projection) {
  27646. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27647. return;
  27648. }
  27649. this._viewUpdateFlag = view.updateFlag;
  27650. this._projectionUpdateFlag = projection.updateFlag;
  27651. this._viewMatrix = view;
  27652. this._projectionMatrix = projection;
  27653. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27654. // Update frustum
  27655. if (!this._frustumPlanes) {
  27656. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27657. }
  27658. else {
  27659. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27660. }
  27661. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27662. var otherCamera = this.activeCamera._alternateCamera;
  27663. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27664. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27665. }
  27666. if (this._sceneUbo.useUbo) {
  27667. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27668. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27669. this._sceneUbo.update();
  27670. }
  27671. };
  27672. /** @hidden */
  27673. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27674. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27675. return;
  27676. }
  27677. this._alternateViewUpdateFlag = view.updateFlag;
  27678. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27679. this._alternateViewMatrix = view;
  27680. this._alternateProjectionMatrix = projection;
  27681. if (!this._alternateTransformMatrix) {
  27682. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27683. }
  27684. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27685. if (!this._alternateSceneUbo) {
  27686. this._createAlternateUbo();
  27687. }
  27688. if (this._alternateSceneUbo.useUbo) {
  27689. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27690. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27691. this._alternateSceneUbo.update();
  27692. }
  27693. };
  27694. /**
  27695. * Gets the uniform buffer used to store scene data
  27696. * @returns a UniformBuffer
  27697. */
  27698. Scene.prototype.getSceneUniformBuffer = function () {
  27699. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27700. };
  27701. /**
  27702. * Gets an unique (relatively to the current scene) Id
  27703. * @returns an unique number for the scene
  27704. */
  27705. Scene.prototype.getUniqueId = function () {
  27706. var result = Scene._uniqueIdCounter;
  27707. Scene._uniqueIdCounter++;
  27708. return result;
  27709. };
  27710. /**
  27711. * Add a mesh to the list of scene's meshes
  27712. * @param newMesh defines the mesh to add
  27713. * @param recursive if all child meshes should also be added to the scene
  27714. */
  27715. Scene.prototype.addMesh = function (newMesh, recursive) {
  27716. var _this = this;
  27717. if (recursive === void 0) { recursive = false; }
  27718. this.meshes.push(newMesh);
  27719. //notify the collision coordinator
  27720. if (this.collisionCoordinator) {
  27721. this.collisionCoordinator.onMeshAdded(newMesh);
  27722. }
  27723. newMesh._resyncLightSources();
  27724. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27725. if (recursive) {
  27726. newMesh.getChildMeshes().forEach(function (m) {
  27727. _this.addMesh(m);
  27728. });
  27729. }
  27730. };
  27731. /**
  27732. * Remove a mesh for the list of scene's meshes
  27733. * @param toRemove defines the mesh to remove
  27734. * @param recursive if all child meshes should also be removed from the scene
  27735. * @returns the index where the mesh was in the mesh list
  27736. */
  27737. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27738. var _this = this;
  27739. if (recursive === void 0) { recursive = false; }
  27740. var index = this.meshes.indexOf(toRemove);
  27741. if (index !== -1) {
  27742. // Remove from the scene if mesh found
  27743. this.meshes[index] = this.meshes[this.meshes.length - 1];
  27744. this.meshes.pop();
  27745. }
  27746. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27747. if (recursive) {
  27748. toRemove.getChildMeshes().forEach(function (m) {
  27749. _this.removeMesh(m);
  27750. });
  27751. }
  27752. return index;
  27753. };
  27754. /**
  27755. * Add a transform node to the list of scene's transform nodes
  27756. * @param newTransformNode defines the transform node to add
  27757. */
  27758. Scene.prototype.addTransformNode = function (newTransformNode) {
  27759. newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length;
  27760. this.transformNodes.push(newTransformNode);
  27761. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27762. };
  27763. /**
  27764. * Remove a transform node for the list of scene's transform nodes
  27765. * @param toRemove defines the transform node to remove
  27766. * @returns the index where the transform node was in the transform node list
  27767. */
  27768. Scene.prototype.removeTransformNode = function (toRemove) {
  27769. var index = toRemove._indexInSceneTransformNodesArray;
  27770. if (index !== -1) {
  27771. if (index !== this.transformNodes.length - 1) {
  27772. var lastNode = this.transformNodes[this.transformNodes.length - 1];
  27773. this.transformNodes[index] = lastNode;
  27774. lastNode._indexInSceneTransformNodesArray = index;
  27775. }
  27776. toRemove._indexInSceneTransformNodesArray = -1;
  27777. this.transformNodes.pop();
  27778. }
  27779. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27780. return index;
  27781. };
  27782. /**
  27783. * Remove a skeleton for the list of scene's skeletons
  27784. * @param toRemove defines the skeleton to remove
  27785. * @returns the index where the skeleton was in the skeleton list
  27786. */
  27787. Scene.prototype.removeSkeleton = function (toRemove) {
  27788. var index = this.skeletons.indexOf(toRemove);
  27789. if (index !== -1) {
  27790. // Remove from the scene if found
  27791. this.skeletons.splice(index, 1);
  27792. }
  27793. return index;
  27794. };
  27795. /**
  27796. * Remove a morph target for the list of scene's morph targets
  27797. * @param toRemove defines the morph target to remove
  27798. * @returns the index where the morph target was in the morph target list
  27799. */
  27800. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27801. var index = this.morphTargetManagers.indexOf(toRemove);
  27802. if (index !== -1) {
  27803. // Remove from the scene if found
  27804. this.morphTargetManagers.splice(index, 1);
  27805. }
  27806. return index;
  27807. };
  27808. /**
  27809. * Remove a light for the list of scene's lights
  27810. * @param toRemove defines the light to remove
  27811. * @returns the index where the light was in the light list
  27812. */
  27813. Scene.prototype.removeLight = function (toRemove) {
  27814. var index = this.lights.indexOf(toRemove);
  27815. if (index !== -1) {
  27816. // Remove from meshes
  27817. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27818. var mesh = _a[_i];
  27819. mesh._removeLightSource(toRemove);
  27820. }
  27821. // Remove from the scene if mesh found
  27822. this.lights.splice(index, 1);
  27823. this.sortLightsByPriority();
  27824. }
  27825. this.onLightRemovedObservable.notifyObservers(toRemove);
  27826. return index;
  27827. };
  27828. /**
  27829. * Remove a camera for the list of scene's cameras
  27830. * @param toRemove defines the camera to remove
  27831. * @returns the index where the camera was in the camera list
  27832. */
  27833. Scene.prototype.removeCamera = function (toRemove) {
  27834. var index = this.cameras.indexOf(toRemove);
  27835. if (index !== -1) {
  27836. // Remove from the scene if mesh found
  27837. this.cameras.splice(index, 1);
  27838. }
  27839. // Remove from activeCameras
  27840. var index2 = this.activeCameras.indexOf(toRemove);
  27841. if (index2 !== -1) {
  27842. // Remove from the scene if mesh found
  27843. this.activeCameras.splice(index2, 1);
  27844. }
  27845. // Reset the activeCamera
  27846. if (this.activeCamera === toRemove) {
  27847. if (this.cameras.length > 0) {
  27848. this.activeCamera = this.cameras[0];
  27849. }
  27850. else {
  27851. this.activeCamera = null;
  27852. }
  27853. }
  27854. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27855. return index;
  27856. };
  27857. /**
  27858. * Remove a particle system for the list of scene's particle systems
  27859. * @param toRemove defines the particle system to remove
  27860. * @returns the index where the particle system was in the particle system list
  27861. */
  27862. Scene.prototype.removeParticleSystem = function (toRemove) {
  27863. var index = this.particleSystems.indexOf(toRemove);
  27864. if (index !== -1) {
  27865. this.particleSystems.splice(index, 1);
  27866. }
  27867. return index;
  27868. };
  27869. /**
  27870. * Remove a animation for the list of scene's animations
  27871. * @param toRemove defines the animation to remove
  27872. * @returns the index where the animation was in the animation list
  27873. */
  27874. Scene.prototype.removeAnimation = function (toRemove) {
  27875. var index = this.animations.indexOf(toRemove);
  27876. if (index !== -1) {
  27877. this.animations.splice(index, 1);
  27878. }
  27879. return index;
  27880. };
  27881. /**
  27882. * Removes the given animation group from this scene.
  27883. * @param toRemove The animation group to remove
  27884. * @returns The index of the removed animation group
  27885. */
  27886. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27887. var index = this.animationGroups.indexOf(toRemove);
  27888. if (index !== -1) {
  27889. this.animationGroups.splice(index, 1);
  27890. }
  27891. return index;
  27892. };
  27893. /**
  27894. * Removes the given multi-material from this scene.
  27895. * @param toRemove The multi-material to remove
  27896. * @returns The index of the removed multi-material
  27897. */
  27898. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27899. var index = this.multiMaterials.indexOf(toRemove);
  27900. if (index !== -1) {
  27901. this.multiMaterials.splice(index, 1);
  27902. }
  27903. return index;
  27904. };
  27905. /**
  27906. * Removes the given material from this scene.
  27907. * @param toRemove The material to remove
  27908. * @returns The index of the removed material
  27909. */
  27910. Scene.prototype.removeMaterial = function (toRemove) {
  27911. var index = toRemove._indexInSceneMaterialArray;
  27912. if (index !== -1) {
  27913. if (index !== this.materials.length - 1) {
  27914. var lastMaterial = this.materials[this.materials.length - 1];
  27915. this.materials[index] = lastMaterial;
  27916. lastMaterial._indexInSceneMaterialArray = index;
  27917. }
  27918. toRemove._indexInSceneMaterialArray = -1;
  27919. this.materials.pop();
  27920. }
  27921. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27922. return index;
  27923. };
  27924. /**
  27925. * Removes the given action manager from this scene.
  27926. * @param toRemove The action manager to remove
  27927. * @returns The index of the removed action manager
  27928. */
  27929. Scene.prototype.removeActionManager = function (toRemove) {
  27930. var index = this.actionManagers.indexOf(toRemove);
  27931. if (index !== -1) {
  27932. this.actionManagers.splice(index, 1);
  27933. }
  27934. return index;
  27935. };
  27936. /**
  27937. * Removes the given texture from this scene.
  27938. * @param toRemove The texture to remove
  27939. * @returns The index of the removed texture
  27940. */
  27941. Scene.prototype.removeTexture = function (toRemove) {
  27942. var index = this.textures.indexOf(toRemove);
  27943. if (index !== -1) {
  27944. this.textures.splice(index, 1);
  27945. }
  27946. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27947. return index;
  27948. };
  27949. /**
  27950. * Adds the given light to this scene
  27951. * @param newLight The light to add
  27952. */
  27953. Scene.prototype.addLight = function (newLight) {
  27954. this.lights.push(newLight);
  27955. this.sortLightsByPriority();
  27956. // Add light to all meshes (To support if the light is removed and then readded)
  27957. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27958. var mesh = _a[_i];
  27959. if (mesh._lightSources.indexOf(newLight) === -1) {
  27960. mesh._lightSources.push(newLight);
  27961. mesh._resyncLightSources();
  27962. }
  27963. }
  27964. this.onNewLightAddedObservable.notifyObservers(newLight);
  27965. };
  27966. /**
  27967. * Sorts the list list based on light priorities
  27968. */
  27969. Scene.prototype.sortLightsByPriority = function () {
  27970. if (this.requireLightSorting) {
  27971. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27972. }
  27973. };
  27974. /**
  27975. * Adds the given camera to this scene
  27976. * @param newCamera The camera to add
  27977. */
  27978. Scene.prototype.addCamera = function (newCamera) {
  27979. this.cameras.push(newCamera);
  27980. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27981. };
  27982. /**
  27983. * Adds the given skeleton to this scene
  27984. * @param newSkeleton The skeleton to add
  27985. */
  27986. Scene.prototype.addSkeleton = function (newSkeleton) {
  27987. this.skeletons.push(newSkeleton);
  27988. };
  27989. /**
  27990. * Adds the given particle system to this scene
  27991. * @param newParticleSystem The particle system to add
  27992. */
  27993. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27994. this.particleSystems.push(newParticleSystem);
  27995. };
  27996. /**
  27997. * Adds the given animation to this scene
  27998. * @param newAnimation The animation to add
  27999. */
  28000. Scene.prototype.addAnimation = function (newAnimation) {
  28001. this.animations.push(newAnimation);
  28002. };
  28003. /**
  28004. * Adds the given animation group to this scene.
  28005. * @param newAnimationGroup The animation group to add
  28006. */
  28007. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  28008. this.animationGroups.push(newAnimationGroup);
  28009. };
  28010. /**
  28011. * Adds the given multi-material to this scene
  28012. * @param newMultiMaterial The multi-material to add
  28013. */
  28014. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  28015. this.multiMaterials.push(newMultiMaterial);
  28016. };
  28017. /**
  28018. * Adds the given material to this scene
  28019. * @param newMaterial The material to add
  28020. */
  28021. Scene.prototype.addMaterial = function (newMaterial) {
  28022. newMaterial._indexInSceneMaterialArray = this.materials.length;
  28023. this.materials.push(newMaterial);
  28024. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  28025. };
  28026. /**
  28027. * Adds the given morph target to this scene
  28028. * @param newMorphTargetManager The morph target to add
  28029. */
  28030. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  28031. this.morphTargetManagers.push(newMorphTargetManager);
  28032. };
  28033. /**
  28034. * Adds the given geometry to this scene
  28035. * @param newGeometry The geometry to add
  28036. */
  28037. Scene.prototype.addGeometry = function (newGeometry) {
  28038. if (this.geometriesById) {
  28039. this.geometriesById[newGeometry.id] = this.geometries.length;
  28040. }
  28041. this.geometries.push(newGeometry);
  28042. };
  28043. /**
  28044. * Adds the given action manager to this scene
  28045. * @param newActionManager The action manager to add
  28046. */
  28047. Scene.prototype.addActionManager = function (newActionManager) {
  28048. this.actionManagers.push(newActionManager);
  28049. };
  28050. /**
  28051. * Adds the given texture to this scene.
  28052. * @param newTexture The texture to add
  28053. */
  28054. Scene.prototype.addTexture = function (newTexture) {
  28055. this.textures.push(newTexture);
  28056. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  28057. };
  28058. /**
  28059. * Switch active camera
  28060. * @param newCamera defines the new active camera
  28061. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  28062. */
  28063. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  28064. if (attachControl === void 0) { attachControl = true; }
  28065. var canvas = this._engine.getRenderingCanvas();
  28066. if (!canvas) {
  28067. return;
  28068. }
  28069. if (this.activeCamera) {
  28070. this.activeCamera.detachControl(canvas);
  28071. }
  28072. this.activeCamera = newCamera;
  28073. if (attachControl) {
  28074. newCamera.attachControl(canvas);
  28075. }
  28076. };
  28077. /**
  28078. * sets the active camera of the scene using its ID
  28079. * @param id defines the camera's ID
  28080. * @return the new active camera or null if none found.
  28081. */
  28082. Scene.prototype.setActiveCameraByID = function (id) {
  28083. var camera = this.getCameraByID(id);
  28084. if (camera) {
  28085. this.activeCamera = camera;
  28086. return camera;
  28087. }
  28088. return null;
  28089. };
  28090. /**
  28091. * sets the active camera of the scene using its name
  28092. * @param name defines the camera's name
  28093. * @returns the new active camera or null if none found.
  28094. */
  28095. Scene.prototype.setActiveCameraByName = function (name) {
  28096. var camera = this.getCameraByName(name);
  28097. if (camera) {
  28098. this.activeCamera = camera;
  28099. return camera;
  28100. }
  28101. return null;
  28102. };
  28103. /**
  28104. * get an animation group using its name
  28105. * @param name defines the material's name
  28106. * @return the animation group or null if none found.
  28107. */
  28108. Scene.prototype.getAnimationGroupByName = function (name) {
  28109. for (var index = 0; index < this.animationGroups.length; index++) {
  28110. if (this.animationGroups[index].name === name) {
  28111. return this.animationGroups[index];
  28112. }
  28113. }
  28114. return null;
  28115. };
  28116. /**
  28117. * get a material using its id
  28118. * @param id defines the material's ID
  28119. * @return the material or null if none found.
  28120. */
  28121. Scene.prototype.getMaterialByID = function (id) {
  28122. for (var index = 0; index < this.materials.length; index++) {
  28123. if (this.materials[index].id === id) {
  28124. return this.materials[index];
  28125. }
  28126. }
  28127. return null;
  28128. };
  28129. /**
  28130. * Gets a material using its name
  28131. * @param name defines the material's name
  28132. * @return the material or null if none found.
  28133. */
  28134. Scene.prototype.getMaterialByName = function (name) {
  28135. for (var index = 0; index < this.materials.length; index++) {
  28136. if (this.materials[index].name === name) {
  28137. return this.materials[index];
  28138. }
  28139. }
  28140. return null;
  28141. };
  28142. /**
  28143. * Gets a camera using its id
  28144. * @param id defines the id to look for
  28145. * @returns the camera or null if not found
  28146. */
  28147. Scene.prototype.getCameraByID = function (id) {
  28148. for (var index = 0; index < this.cameras.length; index++) {
  28149. if (this.cameras[index].id === id) {
  28150. return this.cameras[index];
  28151. }
  28152. }
  28153. return null;
  28154. };
  28155. /**
  28156. * Gets a camera using its unique id
  28157. * @param uniqueId defines the unique id to look for
  28158. * @returns the camera or null if not found
  28159. */
  28160. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  28161. for (var index = 0; index < this.cameras.length; index++) {
  28162. if (this.cameras[index].uniqueId === uniqueId) {
  28163. return this.cameras[index];
  28164. }
  28165. }
  28166. return null;
  28167. };
  28168. /**
  28169. * Gets a camera using its name
  28170. * @param name defines the camera's name
  28171. * @return the camera or null if none found.
  28172. */
  28173. Scene.prototype.getCameraByName = function (name) {
  28174. for (var index = 0; index < this.cameras.length; index++) {
  28175. if (this.cameras[index].name === name) {
  28176. return this.cameras[index];
  28177. }
  28178. }
  28179. return null;
  28180. };
  28181. /**
  28182. * Gets a bone using its id
  28183. * @param id defines the bone's id
  28184. * @return the bone or null if not found
  28185. */
  28186. Scene.prototype.getBoneByID = function (id) {
  28187. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28188. var skeleton = this.skeletons[skeletonIndex];
  28189. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28190. if (skeleton.bones[boneIndex].id === id) {
  28191. return skeleton.bones[boneIndex];
  28192. }
  28193. }
  28194. }
  28195. return null;
  28196. };
  28197. /**
  28198. * Gets a bone using its id
  28199. * @param name defines the bone's name
  28200. * @return the bone or null if not found
  28201. */
  28202. Scene.prototype.getBoneByName = function (name) {
  28203. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28204. var skeleton = this.skeletons[skeletonIndex];
  28205. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28206. if (skeleton.bones[boneIndex].name === name) {
  28207. return skeleton.bones[boneIndex];
  28208. }
  28209. }
  28210. }
  28211. return null;
  28212. };
  28213. /**
  28214. * Gets a light node using its name
  28215. * @param name defines the the light's name
  28216. * @return the light or null if none found.
  28217. */
  28218. Scene.prototype.getLightByName = function (name) {
  28219. for (var index = 0; index < this.lights.length; index++) {
  28220. if (this.lights[index].name === name) {
  28221. return this.lights[index];
  28222. }
  28223. }
  28224. return null;
  28225. };
  28226. /**
  28227. * Gets a light node using its id
  28228. * @param id defines the light's id
  28229. * @return the light or null if none found.
  28230. */
  28231. Scene.prototype.getLightByID = function (id) {
  28232. for (var index = 0; index < this.lights.length; index++) {
  28233. if (this.lights[index].id === id) {
  28234. return this.lights[index];
  28235. }
  28236. }
  28237. return null;
  28238. };
  28239. /**
  28240. * Gets a light node using its scene-generated unique ID
  28241. * @param uniqueId defines the light's unique id
  28242. * @return the light or null if none found.
  28243. */
  28244. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  28245. for (var index = 0; index < this.lights.length; index++) {
  28246. if (this.lights[index].uniqueId === uniqueId) {
  28247. return this.lights[index];
  28248. }
  28249. }
  28250. return null;
  28251. };
  28252. /**
  28253. * Gets a particle system by id
  28254. * @param id defines the particle system id
  28255. * @return the corresponding system or null if none found
  28256. */
  28257. Scene.prototype.getParticleSystemByID = function (id) {
  28258. for (var index = 0; index < this.particleSystems.length; index++) {
  28259. if (this.particleSystems[index].id === id) {
  28260. return this.particleSystems[index];
  28261. }
  28262. }
  28263. return null;
  28264. };
  28265. /**
  28266. * Gets a geometry using its ID
  28267. * @param id defines the geometry's id
  28268. * @return the geometry or null if none found.
  28269. */
  28270. Scene.prototype.getGeometryByID = function (id) {
  28271. if (this.geometriesById) {
  28272. var index_1 = this.geometriesById[id];
  28273. if (index_1 !== undefined) {
  28274. return this.geometries[index_1];
  28275. }
  28276. }
  28277. else {
  28278. for (var index = 0; index < this.geometries.length; index++) {
  28279. if (this.geometries[index].id === id) {
  28280. return this.geometries[index];
  28281. }
  28282. }
  28283. }
  28284. return null;
  28285. };
  28286. /**
  28287. * Add a new geometry to this scene
  28288. * @param geometry defines the geometry to be added to the scene.
  28289. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  28290. * @return a boolean defining if the geometry was added or not
  28291. */
  28292. Scene.prototype.pushGeometry = function (geometry, force) {
  28293. if (!force && this.getGeometryByID(geometry.id)) {
  28294. return false;
  28295. }
  28296. this.addGeometry(geometry);
  28297. //notify the collision coordinator
  28298. if (this.collisionCoordinator) {
  28299. this.collisionCoordinator.onGeometryAdded(geometry);
  28300. }
  28301. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  28302. return true;
  28303. };
  28304. /**
  28305. * Removes an existing geometry
  28306. * @param geometry defines the geometry to be removed from the scene
  28307. * @return a boolean defining if the geometry was removed or not
  28308. */
  28309. Scene.prototype.removeGeometry = function (geometry) {
  28310. var index;
  28311. if (this.geometriesById) {
  28312. index = this.geometriesById[geometry.id];
  28313. if (index === undefined) {
  28314. return false;
  28315. }
  28316. }
  28317. else {
  28318. index = this.geometries.indexOf(geometry);
  28319. if (index < 0) {
  28320. return false;
  28321. }
  28322. }
  28323. if (index !== this.geometries.length - 1) {
  28324. var lastGeometry = this.geometries[this.geometries.length - 1];
  28325. this.geometries[index] = lastGeometry;
  28326. if (this.geometriesById) {
  28327. this.geometriesById[lastGeometry.id] = index;
  28328. this.geometriesById[geometry.id] = undefined;
  28329. }
  28330. }
  28331. this.geometries.pop();
  28332. //notify the collision coordinator
  28333. if (this.collisionCoordinator) {
  28334. this.collisionCoordinator.onGeometryDeleted(geometry);
  28335. }
  28336. this.onGeometryRemovedObservable.notifyObservers(geometry);
  28337. return true;
  28338. };
  28339. /**
  28340. * Gets the list of geometries attached to the scene
  28341. * @returns an array of Geometry
  28342. */
  28343. Scene.prototype.getGeometries = function () {
  28344. return this.geometries;
  28345. };
  28346. /**
  28347. * Gets the first added mesh found of a given ID
  28348. * @param id defines the id to search for
  28349. * @return the mesh found or null if not found at all
  28350. */
  28351. Scene.prototype.getMeshByID = function (id) {
  28352. for (var index = 0; index < this.meshes.length; index++) {
  28353. if (this.meshes[index].id === id) {
  28354. return this.meshes[index];
  28355. }
  28356. }
  28357. return null;
  28358. };
  28359. /**
  28360. * Gets a list of meshes using their id
  28361. * @param id defines the id to search for
  28362. * @returns a list of meshes
  28363. */
  28364. Scene.prototype.getMeshesByID = function (id) {
  28365. return this.meshes.filter(function (m) {
  28366. return m.id === id;
  28367. });
  28368. };
  28369. /**
  28370. * Gets the first added transform node found of a given ID
  28371. * @param id defines the id to search for
  28372. * @return the found transform node or null if not found at all.
  28373. */
  28374. Scene.prototype.getTransformNodeByID = function (id) {
  28375. for (var index = 0; index < this.transformNodes.length; index++) {
  28376. if (this.transformNodes[index].id === id) {
  28377. return this.transformNodes[index];
  28378. }
  28379. }
  28380. return null;
  28381. };
  28382. /**
  28383. * Gets a list of transform nodes using their id
  28384. * @param id defines the id to search for
  28385. * @returns a list of transform nodes
  28386. */
  28387. Scene.prototype.getTransformNodesByID = function (id) {
  28388. return this.transformNodes.filter(function (m) {
  28389. return m.id === id;
  28390. });
  28391. };
  28392. /**
  28393. * Gets a mesh with its auto-generated unique id
  28394. * @param uniqueId defines the unique id to search for
  28395. * @return the found mesh or null if not found at all.
  28396. */
  28397. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28398. for (var index = 0; index < this.meshes.length; index++) {
  28399. if (this.meshes[index].uniqueId === uniqueId) {
  28400. return this.meshes[index];
  28401. }
  28402. }
  28403. return null;
  28404. };
  28405. /**
  28406. * Gets a the last added mesh using a given id
  28407. * @param id defines the id to search for
  28408. * @return the found mesh or null if not found at all.
  28409. */
  28410. Scene.prototype.getLastMeshByID = function (id) {
  28411. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28412. if (this.meshes[index].id === id) {
  28413. return this.meshes[index];
  28414. }
  28415. }
  28416. return null;
  28417. };
  28418. /**
  28419. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28420. * @param id defines the id to search for
  28421. * @return the found node or null if not found at all
  28422. */
  28423. Scene.prototype.getLastEntryByID = function (id) {
  28424. var index;
  28425. for (index = this.meshes.length - 1; index >= 0; index--) {
  28426. if (this.meshes[index].id === id) {
  28427. return this.meshes[index];
  28428. }
  28429. }
  28430. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28431. if (this.transformNodes[index].id === id) {
  28432. return this.transformNodes[index];
  28433. }
  28434. }
  28435. for (index = this.cameras.length - 1; index >= 0; index--) {
  28436. if (this.cameras[index].id === id) {
  28437. return this.cameras[index];
  28438. }
  28439. }
  28440. for (index = this.lights.length - 1; index >= 0; index--) {
  28441. if (this.lights[index].id === id) {
  28442. return this.lights[index];
  28443. }
  28444. }
  28445. return null;
  28446. };
  28447. /**
  28448. * Gets a node (Mesh, Camera, Light) using a given id
  28449. * @param id defines the id to search for
  28450. * @return the found node or null if not found at all
  28451. */
  28452. Scene.prototype.getNodeByID = function (id) {
  28453. var mesh = this.getMeshByID(id);
  28454. if (mesh) {
  28455. return mesh;
  28456. }
  28457. var light = this.getLightByID(id);
  28458. if (light) {
  28459. return light;
  28460. }
  28461. var camera = this.getCameraByID(id);
  28462. if (camera) {
  28463. return camera;
  28464. }
  28465. var bone = this.getBoneByID(id);
  28466. return bone;
  28467. };
  28468. /**
  28469. * Gets a node (Mesh, Camera, Light) using a given name
  28470. * @param name defines the name to search for
  28471. * @return the found node or null if not found at all.
  28472. */
  28473. Scene.prototype.getNodeByName = function (name) {
  28474. var mesh = this.getMeshByName(name);
  28475. if (mesh) {
  28476. return mesh;
  28477. }
  28478. var light = this.getLightByName(name);
  28479. if (light) {
  28480. return light;
  28481. }
  28482. var camera = this.getCameraByName(name);
  28483. if (camera) {
  28484. return camera;
  28485. }
  28486. var bone = this.getBoneByName(name);
  28487. return bone;
  28488. };
  28489. /**
  28490. * Gets a mesh using a given name
  28491. * @param name defines the name to search for
  28492. * @return the found mesh or null if not found at all.
  28493. */
  28494. Scene.prototype.getMeshByName = function (name) {
  28495. for (var index = 0; index < this.meshes.length; index++) {
  28496. if (this.meshes[index].name === name) {
  28497. return this.meshes[index];
  28498. }
  28499. }
  28500. return null;
  28501. };
  28502. /**
  28503. * Gets a transform node using a given name
  28504. * @param name defines the name to search for
  28505. * @return the found transform node or null if not found at all.
  28506. */
  28507. Scene.prototype.getTransformNodeByName = function (name) {
  28508. for (var index = 0; index < this.transformNodes.length; index++) {
  28509. if (this.transformNodes[index].name === name) {
  28510. return this.transformNodes[index];
  28511. }
  28512. }
  28513. return null;
  28514. };
  28515. /**
  28516. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28517. * @param id defines the id to search for
  28518. * @return the found skeleton or null if not found at all.
  28519. */
  28520. Scene.prototype.getLastSkeletonByID = function (id) {
  28521. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28522. if (this.skeletons[index].id === id) {
  28523. return this.skeletons[index];
  28524. }
  28525. }
  28526. return null;
  28527. };
  28528. /**
  28529. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28530. * @param id defines the id to search for
  28531. * @return the found skeleton or null if not found at all.
  28532. */
  28533. Scene.prototype.getSkeletonById = function (id) {
  28534. for (var index = 0; index < this.skeletons.length; index++) {
  28535. if (this.skeletons[index].id === id) {
  28536. return this.skeletons[index];
  28537. }
  28538. }
  28539. return null;
  28540. };
  28541. /**
  28542. * Gets a skeleton using a given name
  28543. * @param name defines the name to search for
  28544. * @return the found skeleton or null if not found at all.
  28545. */
  28546. Scene.prototype.getSkeletonByName = function (name) {
  28547. for (var index = 0; index < this.skeletons.length; index++) {
  28548. if (this.skeletons[index].name === name) {
  28549. return this.skeletons[index];
  28550. }
  28551. }
  28552. return null;
  28553. };
  28554. /**
  28555. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28556. * @param id defines the id to search for
  28557. * @return the found morph target manager or null if not found at all.
  28558. */
  28559. Scene.prototype.getMorphTargetManagerById = function (id) {
  28560. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28561. if (this.morphTargetManagers[index].uniqueId === id) {
  28562. return this.morphTargetManagers[index];
  28563. }
  28564. }
  28565. return null;
  28566. };
  28567. /**
  28568. * Gets a boolean indicating if the given mesh is active
  28569. * @param mesh defines the mesh to look for
  28570. * @returns true if the mesh is in the active list
  28571. */
  28572. Scene.prototype.isActiveMesh = function (mesh) {
  28573. return (this._activeMeshes.indexOf(mesh) !== -1);
  28574. };
  28575. Object.defineProperty(Scene.prototype, "uid", {
  28576. /**
  28577. * Return a unique id as a string which can serve as an identifier for the scene
  28578. */
  28579. get: function () {
  28580. if (!this._uid) {
  28581. this._uid = BABYLON.Tools.RandomId();
  28582. }
  28583. return this._uid;
  28584. },
  28585. enumerable: true,
  28586. configurable: true
  28587. });
  28588. /**
  28589. * Add an externaly attached data from its key.
  28590. * This method call will fail and return false, if such key already exists.
  28591. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28592. * @param key the unique key that identifies the data
  28593. * @param data the data object to associate to the key for this Engine instance
  28594. * @return true if no such key were already present and the data was added successfully, false otherwise
  28595. */
  28596. Scene.prototype.addExternalData = function (key, data) {
  28597. if (!this._externalData) {
  28598. this._externalData = new BABYLON.StringDictionary();
  28599. }
  28600. return this._externalData.add(key, data);
  28601. };
  28602. /**
  28603. * Get an externaly attached data from its key
  28604. * @param key the unique key that identifies the data
  28605. * @return the associated data, if present (can be null), or undefined if not present
  28606. */
  28607. Scene.prototype.getExternalData = function (key) {
  28608. if (!this._externalData) {
  28609. return null;
  28610. }
  28611. return this._externalData.get(key);
  28612. };
  28613. /**
  28614. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28615. * @param key the unique key that identifies the data
  28616. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28617. * @return the associated data, can be null if the factory returned null.
  28618. */
  28619. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28620. if (!this._externalData) {
  28621. this._externalData = new BABYLON.StringDictionary();
  28622. }
  28623. return this._externalData.getOrAddWithFactory(key, factory);
  28624. };
  28625. /**
  28626. * Remove an externaly attached data from the Engine instance
  28627. * @param key the unique key that identifies the data
  28628. * @return true if the data was successfully removed, false if it doesn't exist
  28629. */
  28630. Scene.prototype.removeExternalData = function (key) {
  28631. return this._externalData.remove(key);
  28632. };
  28633. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28634. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28635. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28636. var step = _a[_i];
  28637. step.action(mesh, subMesh);
  28638. }
  28639. var material = subMesh.getMaterial();
  28640. if (material !== null && material !== undefined) {
  28641. // Render targets
  28642. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28643. if (this._processedMaterials.indexOf(material) === -1) {
  28644. this._processedMaterials.push(material);
  28645. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28646. }
  28647. }
  28648. // Dispatch
  28649. this._activeIndices.addCount(subMesh.indexCount, false);
  28650. this._renderingManager.dispatch(subMesh, mesh, material);
  28651. }
  28652. }
  28653. };
  28654. /**
  28655. * Clear the processed materials smart array preventing retention point in material dispose.
  28656. */
  28657. Scene.prototype.freeProcessedMaterials = function () {
  28658. this._processedMaterials.dispose();
  28659. };
  28660. Object.defineProperty(Scene.prototype, "blockfreeActiveMeshesAndRenderingGroups", {
  28661. /** Gets or sets a boolean blocking all the calls to freeActiveMeshes and freeRenderingGroups
  28662. * It can be used in order to prevent going through methods freeRenderingGroups and freeActiveMeshes several times to improve performance
  28663. * when disposing several meshes in a row or a hierarchy of meshes.
  28664. * When used, it is the responsability of the user to blockfreeActiveMeshesAndRenderingGroups back to false.
  28665. */
  28666. get: function () {
  28667. return this._preventFreeActiveMeshesAndRenderingGroups;
  28668. },
  28669. set: function (value) {
  28670. if (this._preventFreeActiveMeshesAndRenderingGroups === value) {
  28671. return;
  28672. }
  28673. if (value) {
  28674. this.freeActiveMeshes();
  28675. this.freeRenderingGroups();
  28676. }
  28677. this._preventFreeActiveMeshesAndRenderingGroups = value;
  28678. },
  28679. enumerable: true,
  28680. configurable: true
  28681. });
  28682. /**
  28683. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28684. */
  28685. Scene.prototype.freeActiveMeshes = function () {
  28686. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  28687. return;
  28688. }
  28689. this._activeMeshes.dispose();
  28690. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28691. this.activeCamera._activeMeshes.dispose();
  28692. }
  28693. if (this.activeCameras) {
  28694. for (var i = 0; i < this.activeCameras.length; i++) {
  28695. var activeCamera = this.activeCameras[i];
  28696. if (activeCamera && activeCamera._activeMeshes) {
  28697. activeCamera._activeMeshes.dispose();
  28698. }
  28699. }
  28700. }
  28701. };
  28702. /**
  28703. * Clear the info related to rendering groups preventing retention points during dispose.
  28704. */
  28705. Scene.prototype.freeRenderingGroups = function () {
  28706. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  28707. return;
  28708. }
  28709. if (this._renderingManager) {
  28710. this._renderingManager.freeRenderingGroups();
  28711. }
  28712. if (this.textures) {
  28713. for (var i = 0; i < this.textures.length; i++) {
  28714. var texture = this.textures[i];
  28715. if (texture && texture.renderList) {
  28716. texture.freeRenderingGroups();
  28717. }
  28718. }
  28719. }
  28720. };
  28721. /** @hidden */
  28722. Scene.prototype._isInIntermediateRendering = function () {
  28723. return this._intermediateRendering;
  28724. };
  28725. /**
  28726. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28727. * @returns the current scene
  28728. */
  28729. Scene.prototype.freezeActiveMeshes = function () {
  28730. if (!this.activeCamera) {
  28731. return this;
  28732. }
  28733. if (!this._frustumPlanes) {
  28734. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28735. }
  28736. this._evaluateActiveMeshes();
  28737. this._activeMeshesFrozen = true;
  28738. return this;
  28739. };
  28740. /**
  28741. * Use this function to restart evaluating active meshes on every frame
  28742. * @returns the current scene
  28743. */
  28744. Scene.prototype.unfreezeActiveMeshes = function () {
  28745. this._activeMeshesFrozen = false;
  28746. return this;
  28747. };
  28748. Scene.prototype._evaluateActiveMeshes = function () {
  28749. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28750. return;
  28751. }
  28752. if (!this.activeCamera) {
  28753. return;
  28754. }
  28755. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28756. this.activeCamera._activeMeshes.reset();
  28757. this._activeMeshes.reset();
  28758. this._renderingManager.reset();
  28759. this._processedMaterials.reset();
  28760. this._activeParticleSystems.reset();
  28761. this._activeSkeletons.reset();
  28762. this._softwareSkinnedMeshes.reset();
  28763. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28764. var step = _a[_i];
  28765. step.action();
  28766. }
  28767. // Determine mesh candidates
  28768. var meshes = this.getActiveMeshCandidates();
  28769. // Check each mesh
  28770. var len = meshes.length;
  28771. for (var i = 0; i < len; i++) {
  28772. var mesh = meshes.data[i];
  28773. if (mesh.isBlocked) {
  28774. continue;
  28775. }
  28776. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28777. if (!mesh.isReady() || !mesh.isEnabled()) {
  28778. continue;
  28779. }
  28780. mesh.computeWorldMatrix();
  28781. // Intersections
  28782. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28783. this._meshesForIntersections.pushNoDuplicate(mesh);
  28784. }
  28785. // Switch to current LOD
  28786. var meshLOD = mesh.getLOD(this.activeCamera);
  28787. if (meshLOD === undefined || meshLOD === null) {
  28788. continue;
  28789. }
  28790. mesh._preActivate();
  28791. if (mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && (mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(this._frustumPlanes))) {
  28792. this._activeMeshes.push(mesh);
  28793. this.activeCamera._activeMeshes.push(mesh);
  28794. mesh._activate(this._renderId);
  28795. if (meshLOD !== mesh) {
  28796. meshLOD._activate(this._renderId);
  28797. }
  28798. this._activeMesh(mesh, meshLOD);
  28799. }
  28800. }
  28801. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28802. // Particle systems
  28803. if (this.particlesEnabled) {
  28804. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28805. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28806. var particleSystem = this.particleSystems[particleIndex];
  28807. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28808. continue;
  28809. }
  28810. var emitter = particleSystem.emitter;
  28811. if (!emitter.position || emitter.isEnabled()) {
  28812. this._activeParticleSystems.push(particleSystem);
  28813. particleSystem.animate();
  28814. this._renderingManager.dispatchParticles(particleSystem);
  28815. }
  28816. }
  28817. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28818. }
  28819. };
  28820. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28821. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28822. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28823. mesh.skeleton.prepare();
  28824. }
  28825. if (!mesh.computeBonesUsingShaders) {
  28826. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28827. }
  28828. }
  28829. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28830. var step = _a[_i];
  28831. step.action(sourceMesh, mesh);
  28832. }
  28833. if (mesh !== undefined && mesh !== null
  28834. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28835. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28836. var len = subMeshes.length;
  28837. for (var i = 0; i < len; i++) {
  28838. var subMesh = subMeshes.data[i];
  28839. this._evaluateSubMesh(subMesh, mesh);
  28840. }
  28841. }
  28842. };
  28843. /**
  28844. * Update the transform matrix to update from the current active camera
  28845. * @param force defines a boolean used to force the update even if cache is up to date
  28846. */
  28847. Scene.prototype.updateTransformMatrix = function (force) {
  28848. if (!this.activeCamera) {
  28849. return;
  28850. }
  28851. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28852. };
  28853. /**
  28854. * 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)
  28855. * @param alternateCamera defines the camera to use
  28856. */
  28857. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28858. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28859. };
  28860. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28861. if (camera && camera._skipRendering) {
  28862. return;
  28863. }
  28864. var engine = this._engine;
  28865. this.activeCamera = camera;
  28866. if (!this.activeCamera) {
  28867. throw new Error("Active camera not set");
  28868. }
  28869. // Viewport
  28870. engine.setViewport(this.activeCamera.viewport);
  28871. // Camera
  28872. this.resetCachedMaterial();
  28873. this._renderId++;
  28874. this.updateTransformMatrix();
  28875. if (camera._alternateCamera) {
  28876. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28877. this._alternateRendering = true;
  28878. }
  28879. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28880. // Meshes
  28881. this._evaluateActiveMeshes();
  28882. // Software skinning
  28883. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28884. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28885. mesh.applySkeleton(mesh.skeleton);
  28886. }
  28887. // Render targets
  28888. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28889. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28890. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28891. }
  28892. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28893. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28894. }
  28895. // Collects render targets from external components.
  28896. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28897. var step = _a[_i];
  28898. step.action(this._renderTargets);
  28899. }
  28900. if (this.renderTargetsEnabled) {
  28901. this._intermediateRendering = true;
  28902. if (this._renderTargets.length > 0) {
  28903. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28904. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28905. var renderTarget = this._renderTargets.data[renderIndex];
  28906. if (renderTarget._shouldRender()) {
  28907. this._renderId++;
  28908. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28909. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28910. }
  28911. }
  28912. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28913. this._renderId++;
  28914. }
  28915. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28916. var step = _c[_b];
  28917. step.action(this.activeCamera);
  28918. }
  28919. this._intermediateRendering = false;
  28920. if (this.activeCamera.outputRenderTarget) {
  28921. var internalTexture = this.activeCamera.outputRenderTarget.getInternalTexture();
  28922. if (internalTexture) {
  28923. engine.bindFramebuffer(internalTexture);
  28924. }
  28925. else {
  28926. BABYLON.Tools.Error("Camera contains invalid customDefaultRenderTarget");
  28927. }
  28928. }
  28929. else {
  28930. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28931. }
  28932. }
  28933. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28934. // Prepare Frame
  28935. if (this.postProcessManager) {
  28936. this.postProcessManager._prepareFrame();
  28937. }
  28938. // Before Camera Draw
  28939. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28940. var step = _e[_d];
  28941. step.action(this.activeCamera);
  28942. }
  28943. // Render
  28944. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28945. this._renderingManager.render(null, null, true, true);
  28946. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28947. // After Camera Draw
  28948. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28949. var step = _g[_f];
  28950. step.action(this.activeCamera);
  28951. }
  28952. // Finalize frame
  28953. if (this.postProcessManager) {
  28954. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28955. }
  28956. // Reset some special arrays
  28957. this._renderTargets.reset();
  28958. this._alternateRendering = false;
  28959. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28960. };
  28961. Scene.prototype._processSubCameras = function (camera) {
  28962. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28963. this._renderForCamera(camera);
  28964. return;
  28965. }
  28966. // rig cameras
  28967. for (var index = 0; index < camera._rigCameras.length; index++) {
  28968. this._renderForCamera(camera._rigCameras[index], camera);
  28969. }
  28970. this.activeCamera = camera;
  28971. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28972. };
  28973. Scene.prototype._checkIntersections = function () {
  28974. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28975. var sourceMesh = this._meshesForIntersections.data[index];
  28976. if (!sourceMesh.actionManager) {
  28977. continue;
  28978. }
  28979. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28980. var action = sourceMesh.actionManager.actions[actionIndex];
  28981. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28982. var parameters = action.getTriggerParameter();
  28983. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28984. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28985. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28986. if (areIntersecting && currentIntersectionInProgress === -1) {
  28987. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28988. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28989. sourceMesh._intersectionsInProgress.push(otherMesh);
  28990. }
  28991. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28992. sourceMesh._intersectionsInProgress.push(otherMesh);
  28993. }
  28994. }
  28995. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28996. //They intersected, and now they don't.
  28997. //is this trigger an exit trigger? execute an event.
  28998. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28999. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  29000. }
  29001. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  29002. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  29003. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  29004. return otherMesh === parameterMesh;
  29005. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29006. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  29007. }
  29008. }
  29009. }
  29010. }
  29011. }
  29012. };
  29013. /** @hidden */
  29014. Scene.prototype._advancePhysicsEngineStep = function (step) {
  29015. // Do nothing. Code will be replaced if physics engine component is referenced
  29016. };
  29017. /**
  29018. * Render the scene
  29019. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  29020. */
  29021. Scene.prototype.render = function (updateCameras) {
  29022. if (updateCameras === void 0) { updateCameras = true; }
  29023. if (this.isDisposed) {
  29024. return;
  29025. }
  29026. this._frameId++;
  29027. // Register components that have been associated lately to the scene.
  29028. this._registerTransientComponents();
  29029. this._activeParticles.fetchNewFrame();
  29030. this._totalVertices.fetchNewFrame();
  29031. this._activeIndices.fetchNewFrame();
  29032. this._activeBones.fetchNewFrame();
  29033. this._meshesForIntersections.reset();
  29034. this.resetCachedMaterial();
  29035. this.onBeforeAnimationsObservable.notifyObservers(this);
  29036. // Actions
  29037. if (this.actionManager) {
  29038. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  29039. }
  29040. if (this._engine.isDeterministicLockStep()) {
  29041. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  29042. var defaultFPS = (60.0 / 1000.0);
  29043. var defaultFrameTime = this.getDeterministicFrameTime();
  29044. var stepsTaken = 0;
  29045. var maxSubSteps = this._engine.getLockstepMaxSteps();
  29046. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  29047. internalSteps = Math.min(internalSteps, maxSubSteps);
  29048. do {
  29049. this.onBeforeStepObservable.notifyObservers(this);
  29050. // Animations
  29051. this._animationRatio = defaultFrameTime * defaultFPS;
  29052. this._animate();
  29053. this.onAfterAnimationsObservable.notifyObservers(this);
  29054. // Physics
  29055. this._advancePhysicsEngineStep(defaultFrameTime);
  29056. this.onAfterStepObservable.notifyObservers(this);
  29057. this._currentStepId++;
  29058. stepsTaken++;
  29059. deltaTime -= defaultFrameTime;
  29060. } while (deltaTime > 0 && stepsTaken < internalSteps);
  29061. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  29062. }
  29063. else {
  29064. // Animations
  29065. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  29066. this._animationRatio = deltaTime * (60.0 / 1000.0);
  29067. this._animate();
  29068. this.onAfterAnimationsObservable.notifyObservers(this);
  29069. // Physics
  29070. this._advancePhysicsEngineStep(deltaTime);
  29071. }
  29072. // Before camera update steps
  29073. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  29074. var step = _a[_i];
  29075. step.action();
  29076. }
  29077. // Update Cameras
  29078. if (updateCameras) {
  29079. if (this.activeCameras.length > 0) {
  29080. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29081. var camera = this.activeCameras[cameraIndex];
  29082. camera.update();
  29083. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29084. // rig cameras
  29085. for (var index = 0; index < camera._rigCameras.length; index++) {
  29086. camera._rigCameras[index].update();
  29087. }
  29088. }
  29089. }
  29090. }
  29091. else if (this.activeCamera) {
  29092. this.activeCamera.update();
  29093. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29094. // rig cameras
  29095. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  29096. this.activeCamera._rigCameras[index].update();
  29097. }
  29098. }
  29099. }
  29100. }
  29101. // Before render
  29102. this.onBeforeRenderObservable.notifyObservers(this);
  29103. // Customs render targets
  29104. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  29105. var engine = this.getEngine();
  29106. var currentActiveCamera = this.activeCamera;
  29107. if (this.renderTargetsEnabled) {
  29108. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29109. this._intermediateRendering = true;
  29110. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  29111. var renderTarget = this.customRenderTargets[customIndex];
  29112. if (renderTarget._shouldRender()) {
  29113. this._renderId++;
  29114. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  29115. if (!this.activeCamera) {
  29116. throw new Error("Active camera not set");
  29117. }
  29118. // Viewport
  29119. engine.setViewport(this.activeCamera.viewport);
  29120. // Camera
  29121. this.updateTransformMatrix();
  29122. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  29123. }
  29124. }
  29125. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29126. this._intermediateRendering = false;
  29127. this._renderId++;
  29128. }
  29129. // Restore back buffer
  29130. if (this.customRenderTargets.length > 0) {
  29131. engine.restoreDefaultFramebuffer();
  29132. }
  29133. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29134. this.activeCamera = currentActiveCamera;
  29135. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  29136. var step = _c[_b];
  29137. step.action();
  29138. }
  29139. // Clear
  29140. if (this.autoClearDepthAndStencil || this.autoClear) {
  29141. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  29142. }
  29143. // Collects render targets from external components.
  29144. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  29145. var step = _e[_d];
  29146. step.action(this._renderTargets);
  29147. }
  29148. // Multi-cameras?
  29149. if (this.activeCameras.length > 0) {
  29150. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29151. if (cameraIndex > 0) {
  29152. this._engine.clear(null, false, true, true);
  29153. }
  29154. this._processSubCameras(this.activeCameras[cameraIndex]);
  29155. }
  29156. }
  29157. else {
  29158. if (!this.activeCamera) {
  29159. throw new Error("No camera defined");
  29160. }
  29161. this._processSubCameras(this.activeCamera);
  29162. }
  29163. // Intersection checks
  29164. this._checkIntersections();
  29165. // Executes the after render stage actions.
  29166. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  29167. var step = _g[_f];
  29168. step.action();
  29169. }
  29170. // After render
  29171. if (this.afterRender) {
  29172. this.afterRender();
  29173. }
  29174. this.onAfterRenderObservable.notifyObservers(this);
  29175. // Cleaning
  29176. if (this._toBeDisposed.length) {
  29177. for (var index = 0; index < this._toBeDisposed.length; index++) {
  29178. var data = this._toBeDisposed[index];
  29179. if (data) {
  29180. data.dispose();
  29181. }
  29182. }
  29183. this._toBeDisposed = [];
  29184. }
  29185. if (this.dumpNextRenderTargets) {
  29186. this.dumpNextRenderTargets = false;
  29187. }
  29188. this._activeBones.addCount(0, true);
  29189. this._activeIndices.addCount(0, true);
  29190. this._activeParticles.addCount(0, true);
  29191. };
  29192. /**
  29193. * Freeze all materials
  29194. * A frozen material will not be updatable but should be faster to render
  29195. */
  29196. Scene.prototype.freezeMaterials = function () {
  29197. for (var i = 0; i < this.materials.length; i++) {
  29198. this.materials[i].freeze();
  29199. }
  29200. };
  29201. /**
  29202. * Unfreeze all materials
  29203. * A frozen material will not be updatable but should be faster to render
  29204. */
  29205. Scene.prototype.unfreezeMaterials = function () {
  29206. for (var i = 0; i < this.materials.length; i++) {
  29207. this.materials[i].unfreeze();
  29208. }
  29209. };
  29210. /**
  29211. * Releases all held ressources
  29212. */
  29213. Scene.prototype.dispose = function () {
  29214. this.beforeRender = null;
  29215. this.afterRender = null;
  29216. this.skeletons = [];
  29217. this.morphTargetManagers = [];
  29218. this._transientComponents = [];
  29219. this._isReadyForMeshStage.clear();
  29220. this._beforeEvaluateActiveMeshStage.clear();
  29221. this._evaluateSubMeshStage.clear();
  29222. this._activeMeshStage.clear();
  29223. this._cameraDrawRenderTargetStage.clear();
  29224. this._beforeCameraDrawStage.clear();
  29225. this._beforeRenderingGroupDrawStage.clear();
  29226. this._beforeRenderingMeshStage.clear();
  29227. this._afterRenderingMeshStage.clear();
  29228. this._afterRenderingGroupDrawStage.clear();
  29229. this._afterCameraDrawStage.clear();
  29230. this._afterRenderStage.clear();
  29231. this._beforeCameraUpdateStage.clear();
  29232. this._beforeClearStage.clear();
  29233. this._gatherRenderTargetsStage.clear();
  29234. this._gatherActiveCameraRenderTargetsStage.clear();
  29235. this._pointerMoveStage.clear();
  29236. this._pointerDownStage.clear();
  29237. this._pointerUpStage.clear();
  29238. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  29239. var component = _a[_i];
  29240. component.dispose();
  29241. }
  29242. this.importedMeshesFiles = new Array();
  29243. this.stopAllAnimations();
  29244. this.resetCachedMaterial();
  29245. // Smart arrays
  29246. if (this.activeCamera) {
  29247. this.activeCamera._activeMeshes.dispose();
  29248. this.activeCamera = null;
  29249. }
  29250. this._activeMeshes.dispose();
  29251. this._renderingManager.dispose();
  29252. this._processedMaterials.dispose();
  29253. this._activeParticleSystems.dispose();
  29254. this._activeSkeletons.dispose();
  29255. this._softwareSkinnedMeshes.dispose();
  29256. this._renderTargets.dispose();
  29257. this._registeredForLateAnimationBindings.dispose();
  29258. this._meshesForIntersections.dispose();
  29259. this._toBeDisposed = [];
  29260. // Abort active requests
  29261. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  29262. var request = _c[_b];
  29263. request.abort();
  29264. }
  29265. // Events
  29266. this.onDisposeObservable.notifyObservers(this);
  29267. this.onDisposeObservable.clear();
  29268. this.onBeforeRenderObservable.clear();
  29269. this.onAfterRenderObservable.clear();
  29270. this.onBeforeRenderTargetsRenderObservable.clear();
  29271. this.onAfterRenderTargetsRenderObservable.clear();
  29272. this.onAfterStepObservable.clear();
  29273. this.onBeforeStepObservable.clear();
  29274. this.onBeforeActiveMeshesEvaluationObservable.clear();
  29275. this.onAfterActiveMeshesEvaluationObservable.clear();
  29276. this.onBeforeParticlesRenderingObservable.clear();
  29277. this.onAfterParticlesRenderingObservable.clear();
  29278. this.onBeforeDrawPhaseObservable.clear();
  29279. this.onAfterDrawPhaseObservable.clear();
  29280. this.onBeforeAnimationsObservable.clear();
  29281. this.onAfterAnimationsObservable.clear();
  29282. this.onDataLoadedObservable.clear();
  29283. this.onBeforeRenderingGroupObservable.clear();
  29284. this.onAfterRenderingGroupObservable.clear();
  29285. this.onMeshImportedObservable.clear();
  29286. this.onBeforeCameraRenderObservable.clear();
  29287. this.onAfterCameraRenderObservable.clear();
  29288. this.onReadyObservable.clear();
  29289. this.onNewCameraAddedObservable.clear();
  29290. this.onCameraRemovedObservable.clear();
  29291. this.onNewLightAddedObservable.clear();
  29292. this.onLightRemovedObservable.clear();
  29293. this.onNewGeometryAddedObservable.clear();
  29294. this.onGeometryRemovedObservable.clear();
  29295. this.onNewTransformNodeAddedObservable.clear();
  29296. this.onTransformNodeRemovedObservable.clear();
  29297. this.onNewMeshAddedObservable.clear();
  29298. this.onMeshRemovedObservable.clear();
  29299. this.onNewMaterialAddedObservable.clear();
  29300. this.onMaterialRemovedObservable.clear();
  29301. this.onNewTextureAddedObservable.clear();
  29302. this.onTextureRemovedObservable.clear();
  29303. this.onPrePointerObservable.clear();
  29304. this.onPointerObservable.clear();
  29305. this.onPreKeyboardObservable.clear();
  29306. this.onKeyboardObservable.clear();
  29307. this.detachControl();
  29308. // Detach cameras
  29309. var canvas = this._engine.getRenderingCanvas();
  29310. if (canvas) {
  29311. var index;
  29312. for (index = 0; index < this.cameras.length; index++) {
  29313. this.cameras[index].detachControl(canvas);
  29314. }
  29315. }
  29316. // Release animation groups
  29317. while (this.animationGroups.length) {
  29318. this.animationGroups[0].dispose();
  29319. }
  29320. // Release lights
  29321. while (this.lights.length) {
  29322. this.lights[0].dispose();
  29323. }
  29324. // Release meshes
  29325. while (this.meshes.length) {
  29326. this.meshes[0].dispose(true);
  29327. }
  29328. while (this.transformNodes.length) {
  29329. this.removeTransformNode(this.transformNodes[0]);
  29330. }
  29331. // Release cameras
  29332. while (this.cameras.length) {
  29333. this.cameras[0].dispose();
  29334. }
  29335. // Release materials
  29336. if (this.defaultMaterial) {
  29337. this.defaultMaterial.dispose();
  29338. }
  29339. while (this.multiMaterials.length) {
  29340. this.multiMaterials[0].dispose();
  29341. }
  29342. while (this.materials.length) {
  29343. this.materials[0].dispose();
  29344. }
  29345. // Release particles
  29346. while (this.particleSystems.length) {
  29347. this.particleSystems[0].dispose();
  29348. }
  29349. // Release postProcesses
  29350. while (this.postProcesses.length) {
  29351. this.postProcesses[0].dispose();
  29352. }
  29353. // Release textures
  29354. while (this.textures.length) {
  29355. this.textures[0].dispose();
  29356. }
  29357. // Release UBO
  29358. this._sceneUbo.dispose();
  29359. if (this._alternateSceneUbo) {
  29360. this._alternateSceneUbo.dispose();
  29361. }
  29362. // Post-processes
  29363. this.postProcessManager.dispose();
  29364. // Remove from engine
  29365. index = this._engine.scenes.indexOf(this);
  29366. if (index > -1) {
  29367. this._engine.scenes.splice(index, 1);
  29368. }
  29369. this._engine.wipeCaches(true);
  29370. this._isDisposed = true;
  29371. };
  29372. Object.defineProperty(Scene.prototype, "isDisposed", {
  29373. /**
  29374. * Gets if the scene is already disposed
  29375. */
  29376. get: function () {
  29377. return this._isDisposed;
  29378. },
  29379. enumerable: true,
  29380. configurable: true
  29381. });
  29382. /**
  29383. * Call this function to reduce memory footprint of the scene.
  29384. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  29385. */
  29386. Scene.prototype.clearCachedVertexData = function () {
  29387. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29388. var mesh = this.meshes[meshIndex];
  29389. var geometry = mesh.geometry;
  29390. if (geometry) {
  29391. geometry._indices = [];
  29392. for (var vbName in geometry._vertexBuffers) {
  29393. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  29394. continue;
  29395. }
  29396. geometry._vertexBuffers[vbName]._buffer._data = null;
  29397. }
  29398. }
  29399. }
  29400. };
  29401. /**
  29402. * This function will remove the local cached buffer data from texture.
  29403. * It will save memory but will prevent the texture from being rebuilt
  29404. */
  29405. Scene.prototype.cleanCachedTextureBuffer = function () {
  29406. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29407. var baseTexture = _a[_i];
  29408. var buffer = baseTexture._buffer;
  29409. if (buffer) {
  29410. baseTexture._buffer = null;
  29411. }
  29412. }
  29413. };
  29414. /**
  29415. * Get the world extend vectors with an optional filter
  29416. *
  29417. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  29418. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  29419. */
  29420. Scene.prototype.getWorldExtends = function (filterPredicate) {
  29421. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29422. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29423. filterPredicate = filterPredicate || (function () { return true; });
  29424. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29425. mesh.computeWorldMatrix(true);
  29426. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29427. return;
  29428. }
  29429. var boundingInfo = mesh.getBoundingInfo();
  29430. var minBox = boundingInfo.boundingBox.minimumWorld;
  29431. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29432. BABYLON.Tools.CheckExtends(minBox, min, max);
  29433. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29434. });
  29435. return {
  29436. min: min,
  29437. max: max
  29438. };
  29439. };
  29440. // Picking
  29441. /**
  29442. * Creates a ray that can be used to pick in the scene
  29443. * @param x defines the x coordinate of the origin (on-screen)
  29444. * @param y defines the y coordinate of the origin (on-screen)
  29445. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29446. * @param camera defines the camera to use for the picking
  29447. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29448. * @returns a Ray
  29449. */
  29450. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29451. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29452. var result = BABYLON.Ray.Zero();
  29453. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29454. return result;
  29455. };
  29456. /**
  29457. * Creates a ray that can be used to pick in the scene
  29458. * @param x defines the x coordinate of the origin (on-screen)
  29459. * @param y defines the y coordinate of the origin (on-screen)
  29460. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29461. * @param result defines the ray where to store the picking ray
  29462. * @param camera defines the camera to use for the picking
  29463. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29464. * @returns the current scene
  29465. */
  29466. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29467. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29468. var engine = this._engine;
  29469. if (!camera) {
  29470. if (!this.activeCamera) {
  29471. throw new Error("Active camera not set");
  29472. }
  29473. camera = this.activeCamera;
  29474. }
  29475. var cameraViewport = camera.viewport;
  29476. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29477. // Moving coordinates to local viewport world
  29478. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29479. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29480. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29481. return this;
  29482. };
  29483. /**
  29484. * Creates a ray that can be used to pick in the scene
  29485. * @param x defines the x coordinate of the origin (on-screen)
  29486. * @param y defines the y coordinate of the origin (on-screen)
  29487. * @param camera defines the camera to use for the picking
  29488. * @returns a Ray
  29489. */
  29490. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29491. var result = BABYLON.Ray.Zero();
  29492. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29493. return result;
  29494. };
  29495. /**
  29496. * Creates a ray that can be used to pick in the scene
  29497. * @param x defines the x coordinate of the origin (on-screen)
  29498. * @param y defines the y coordinate of the origin (on-screen)
  29499. * @param result defines the ray where to store the picking ray
  29500. * @param camera defines the camera to use for the picking
  29501. * @returns the current scene
  29502. */
  29503. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29504. if (!BABYLON.PickingInfo) {
  29505. return this;
  29506. }
  29507. var engine = this._engine;
  29508. if (!camera) {
  29509. if (!this.activeCamera) {
  29510. throw new Error("Active camera not set");
  29511. }
  29512. camera = this.activeCamera;
  29513. }
  29514. var cameraViewport = camera.viewport;
  29515. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29516. var identity = BABYLON.Matrix.Identity();
  29517. // Moving coordinates to local viewport world
  29518. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29519. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29520. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29521. return this;
  29522. };
  29523. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29524. if (!BABYLON.PickingInfo) {
  29525. return null;
  29526. }
  29527. var pickingInfo = null;
  29528. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29529. var mesh = this.meshes[meshIndex];
  29530. if (predicate) {
  29531. if (!predicate(mesh)) {
  29532. continue;
  29533. }
  29534. }
  29535. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29536. continue;
  29537. }
  29538. var world = mesh.getWorldMatrix();
  29539. var ray = rayFunction(world);
  29540. var result = mesh.intersects(ray, fastCheck);
  29541. if (!result || !result.hit) {
  29542. continue;
  29543. }
  29544. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  29545. continue;
  29546. }
  29547. pickingInfo = result;
  29548. if (fastCheck) {
  29549. break;
  29550. }
  29551. }
  29552. return pickingInfo || new BABYLON.PickingInfo();
  29553. };
  29554. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29555. if (!BABYLON.PickingInfo) {
  29556. return null;
  29557. }
  29558. var pickingInfos = new Array();
  29559. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29560. var mesh = this.meshes[meshIndex];
  29561. if (predicate) {
  29562. if (!predicate(mesh)) {
  29563. continue;
  29564. }
  29565. }
  29566. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29567. continue;
  29568. }
  29569. var world = mesh.getWorldMatrix();
  29570. var ray = rayFunction(world);
  29571. var result = mesh.intersects(ray, false);
  29572. if (!result || !result.hit) {
  29573. continue;
  29574. }
  29575. pickingInfos.push(result);
  29576. }
  29577. return pickingInfos;
  29578. };
  29579. /** Launch a ray to try to pick a mesh in the scene
  29580. * @param x position on screen
  29581. * @param y position on screen
  29582. * @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
  29583. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29584. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29585. * @returns a PickingInfo
  29586. */
  29587. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29588. var _this = this;
  29589. if (!BABYLON.PickingInfo) {
  29590. return null;
  29591. }
  29592. var result = this._internalPick(function (world) {
  29593. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29594. return _this._tempPickingRay;
  29595. }, predicate, fastCheck);
  29596. if (result) {
  29597. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29598. }
  29599. return result;
  29600. };
  29601. /** Use the given ray to pick a mesh in the scene
  29602. * @param ray The ray to use to pick meshes
  29603. * @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
  29604. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29605. * @returns a PickingInfo
  29606. */
  29607. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29608. var _this = this;
  29609. var result = this._internalPick(function (world) {
  29610. if (!_this._pickWithRayInverseMatrix) {
  29611. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29612. }
  29613. world.invertToRef(_this._pickWithRayInverseMatrix);
  29614. if (!_this._cachedRayForTransform) {
  29615. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29616. }
  29617. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29618. return _this._cachedRayForTransform;
  29619. }, predicate, fastCheck);
  29620. if (result) {
  29621. result.ray = ray;
  29622. }
  29623. return result;
  29624. };
  29625. /**
  29626. * Launch a ray to try to pick a mesh in the scene
  29627. * @param x X position on screen
  29628. * @param y Y position on screen
  29629. * @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
  29630. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29631. * @returns an array of PickingInfo
  29632. */
  29633. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29634. var _this = this;
  29635. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29636. };
  29637. /**
  29638. * Launch a ray to try to pick a mesh in the scene
  29639. * @param ray Ray to use
  29640. * @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
  29641. * @returns an array of PickingInfo
  29642. */
  29643. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29644. var _this = this;
  29645. return this._internalMultiPick(function (world) {
  29646. if (!_this._pickWithRayInverseMatrix) {
  29647. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29648. }
  29649. world.invertToRef(_this._pickWithRayInverseMatrix);
  29650. if (!_this._cachedRayForTransform) {
  29651. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29652. }
  29653. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29654. return _this._cachedRayForTransform;
  29655. }, predicate);
  29656. };
  29657. /**
  29658. * Force the value of meshUnderPointer
  29659. * @param mesh defines the mesh to use
  29660. */
  29661. Scene.prototype.setPointerOverMesh = function (mesh) {
  29662. if (this._pointerOverMesh === mesh) {
  29663. return;
  29664. }
  29665. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29666. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29667. }
  29668. this._pointerOverMesh = mesh;
  29669. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29670. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29671. }
  29672. };
  29673. /**
  29674. * Gets the mesh under the pointer
  29675. * @returns a Mesh or null if no mesh is under the pointer
  29676. */
  29677. Scene.prototype.getPointerOverMesh = function () {
  29678. return this._pointerOverMesh;
  29679. };
  29680. // Misc.
  29681. /** @hidden */
  29682. Scene.prototype._rebuildGeometries = function () {
  29683. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29684. var geometry = _a[_i];
  29685. geometry._rebuild();
  29686. }
  29687. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29688. var mesh = _c[_b];
  29689. mesh._rebuild();
  29690. }
  29691. if (this.postProcessManager) {
  29692. this.postProcessManager._rebuild();
  29693. }
  29694. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29695. var component = _e[_d];
  29696. component.rebuild();
  29697. }
  29698. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29699. var system = _g[_f];
  29700. system.rebuild();
  29701. }
  29702. };
  29703. /** @hidden */
  29704. Scene.prototype._rebuildTextures = function () {
  29705. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29706. var texture = _a[_i];
  29707. texture._rebuild();
  29708. }
  29709. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29710. };
  29711. // Tags
  29712. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29713. if (tagsQuery === undefined) {
  29714. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29715. return list;
  29716. }
  29717. var listByTags = [];
  29718. forEach = forEach || (function (item) { return; });
  29719. for (var i in list) {
  29720. var item = list[i];
  29721. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29722. listByTags.push(item);
  29723. forEach(item);
  29724. }
  29725. }
  29726. return listByTags;
  29727. };
  29728. /**
  29729. * Get a list of meshes by tags
  29730. * @param tagsQuery defines the tags query to use
  29731. * @param forEach defines a predicate used to filter results
  29732. * @returns an array of Mesh
  29733. */
  29734. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29735. return this._getByTags(this.meshes, tagsQuery, forEach);
  29736. };
  29737. /**
  29738. * Get a list of cameras by tags
  29739. * @param tagsQuery defines the tags query to use
  29740. * @param forEach defines a predicate used to filter results
  29741. * @returns an array of Camera
  29742. */
  29743. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29744. return this._getByTags(this.cameras, tagsQuery, forEach);
  29745. };
  29746. /**
  29747. * Get a list of lights by tags
  29748. * @param tagsQuery defines the tags query to use
  29749. * @param forEach defines a predicate used to filter results
  29750. * @returns an array of Light
  29751. */
  29752. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29753. return this._getByTags(this.lights, tagsQuery, forEach);
  29754. };
  29755. /**
  29756. * Get a list of materials by tags
  29757. * @param tagsQuery defines the tags query to use
  29758. * @param forEach defines a predicate used to filter results
  29759. * @returns an array of Material
  29760. */
  29761. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29762. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29763. };
  29764. /**
  29765. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29766. * This allowed control for front to back rendering or reversly depending of the special needs.
  29767. *
  29768. * @param renderingGroupId The rendering group id corresponding to its index
  29769. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29770. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29771. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29772. */
  29773. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29774. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29775. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29776. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29777. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29778. };
  29779. /**
  29780. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29781. *
  29782. * @param renderingGroupId The rendering group id corresponding to its index
  29783. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29784. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29785. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29786. */
  29787. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29788. if (depth === void 0) { depth = true; }
  29789. if (stencil === void 0) { stencil = true; }
  29790. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29791. };
  29792. /**
  29793. * Gets the current auto clear configuration for one rendering group of the rendering
  29794. * manager.
  29795. * @param index the rendering group index to get the information for
  29796. * @returns The auto clear setup for the requested rendering group
  29797. */
  29798. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29799. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29800. };
  29801. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29802. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29803. get: function () {
  29804. return this._blockMaterialDirtyMechanism;
  29805. },
  29806. set: function (value) {
  29807. if (this._blockMaterialDirtyMechanism === value) {
  29808. return;
  29809. }
  29810. this._blockMaterialDirtyMechanism = value;
  29811. if (!value) { // Do a complete update
  29812. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29813. }
  29814. },
  29815. enumerable: true,
  29816. configurable: true
  29817. });
  29818. /**
  29819. * Will flag all materials as dirty to trigger new shader compilation
  29820. * @param flag defines the flag used to specify which material part must be marked as dirty
  29821. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29822. */
  29823. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29824. if (this._blockMaterialDirtyMechanism) {
  29825. return;
  29826. }
  29827. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29828. var material = _a[_i];
  29829. if (predicate && !predicate(material)) {
  29830. continue;
  29831. }
  29832. material.markAsDirty(flag);
  29833. }
  29834. };
  29835. /** @hidden */
  29836. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError) {
  29837. var _this = this;
  29838. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError);
  29839. this._activeRequests.push(request);
  29840. request.onCompleteObservable.add(function (request) {
  29841. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29842. });
  29843. return request;
  29844. };
  29845. /** @hidden */
  29846. Scene.prototype._loadFileAsync = function (url, useOfflineSupport, useArrayBuffer) {
  29847. var _this = this;
  29848. return new Promise(function (resolve, reject) {
  29849. _this._loadFile(url, function (data) {
  29850. resolve(data);
  29851. }, undefined, useOfflineSupport, useArrayBuffer, function (request, exception) {
  29852. reject(exception);
  29853. });
  29854. });
  29855. };
  29856. // Statics
  29857. Scene._uniqueIdCounter = 0;
  29858. /** The fog is deactivated */
  29859. Scene.FOGMODE_NONE = 0;
  29860. /** The fog density is following an exponential function */
  29861. Scene.FOGMODE_EXP = 1;
  29862. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29863. Scene.FOGMODE_EXP2 = 2;
  29864. /** The fog density is following a linear function. */
  29865. Scene.FOGMODE_LINEAR = 3;
  29866. /**
  29867. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29868. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29869. */
  29870. Scene.MinDeltaTime = 1.0;
  29871. /**
  29872. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29873. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29874. */
  29875. Scene.MaxDeltaTime = 1000.0;
  29876. /** The distance in pixel that you have to move to prevent some events */
  29877. Scene.DragMovementThreshold = 10; // in pixels
  29878. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29879. Scene.LongPressDelay = 500; // in milliseconds
  29880. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29881. Scene.DoubleClickDelay = 300; // in milliseconds
  29882. /** If you need to check double click without raising a single click at first click, enable this flag */
  29883. Scene.ExclusiveDoubleClickMode = false;
  29884. return Scene;
  29885. }(BABYLON.AbstractScene));
  29886. BABYLON.Scene = Scene;
  29887. })(BABYLON || (BABYLON = {}));
  29888. //# sourceMappingURL=babylon.scene.js.map
  29889. var BABYLON;
  29890. (function (BABYLON) {
  29891. /**
  29892. * Set of assets to keep when moving a scene into an asset container.
  29893. */
  29894. var KeepAssets = /** @class */ (function (_super) {
  29895. __extends(KeepAssets, _super);
  29896. function KeepAssets() {
  29897. return _super !== null && _super.apply(this, arguments) || this;
  29898. }
  29899. return KeepAssets;
  29900. }(BABYLON.AbstractScene));
  29901. BABYLON.KeepAssets = KeepAssets;
  29902. /**
  29903. * Container with a set of assets that can be added or removed from a scene.
  29904. */
  29905. var AssetContainer = /** @class */ (function (_super) {
  29906. __extends(AssetContainer, _super);
  29907. /**
  29908. * Instantiates an AssetContainer.
  29909. * @param scene The scene the AssetContainer belongs to.
  29910. */
  29911. function AssetContainer(scene) {
  29912. var _this = _super.call(this) || this;
  29913. _this.scene = scene;
  29914. _this["sounds"] = [];
  29915. _this["effectLayers"] = [];
  29916. _this["layers"] = [];
  29917. _this["lensFlareSystems"] = [];
  29918. _this["proceduralTextures"] = [];
  29919. return _this;
  29920. }
  29921. /**
  29922. * Adds all the assets from the container to the scene.
  29923. */
  29924. AssetContainer.prototype.addAllToScene = function () {
  29925. var _this = this;
  29926. this.cameras.forEach(function (o) {
  29927. _this.scene.addCamera(o);
  29928. });
  29929. this.lights.forEach(function (o) {
  29930. _this.scene.addLight(o);
  29931. });
  29932. this.meshes.forEach(function (o) {
  29933. _this.scene.addMesh(o);
  29934. });
  29935. this.skeletons.forEach(function (o) {
  29936. _this.scene.addSkeleton(o);
  29937. });
  29938. this.animations.forEach(function (o) {
  29939. _this.scene.addAnimation(o);
  29940. });
  29941. this.animationGroups.forEach(function (o) {
  29942. _this.scene.addAnimationGroup(o);
  29943. });
  29944. this.multiMaterials.forEach(function (o) {
  29945. _this.scene.addMultiMaterial(o);
  29946. });
  29947. this.materials.forEach(function (o) {
  29948. _this.scene.addMaterial(o);
  29949. });
  29950. this.morphTargetManagers.forEach(function (o) {
  29951. _this.scene.addMorphTargetManager(o);
  29952. });
  29953. this.geometries.forEach(function (o) {
  29954. _this.scene.addGeometry(o);
  29955. });
  29956. this.transformNodes.forEach(function (o) {
  29957. _this.scene.addTransformNode(o);
  29958. });
  29959. this.actionManagers.forEach(function (o) {
  29960. _this.scene.addActionManager(o);
  29961. });
  29962. this.textures.forEach(function (o) {
  29963. _this.scene.addTexture(o);
  29964. });
  29965. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29966. var component = _a[_i];
  29967. component.addFromContainer(this);
  29968. }
  29969. };
  29970. /**
  29971. * Removes all the assets in the container from the scene
  29972. */
  29973. AssetContainer.prototype.removeAllFromScene = function () {
  29974. var _this = this;
  29975. this.cameras.forEach(function (o) {
  29976. _this.scene.removeCamera(o);
  29977. });
  29978. this.lights.forEach(function (o) {
  29979. _this.scene.removeLight(o);
  29980. });
  29981. this.meshes.forEach(function (o) {
  29982. _this.scene.removeMesh(o);
  29983. });
  29984. this.skeletons.forEach(function (o) {
  29985. _this.scene.removeSkeleton(o);
  29986. });
  29987. this.animations.forEach(function (o) {
  29988. _this.scene.removeAnimation(o);
  29989. });
  29990. this.animationGroups.forEach(function (o) {
  29991. _this.scene.removeAnimationGroup(o);
  29992. });
  29993. this.multiMaterials.forEach(function (o) {
  29994. _this.scene.removeMultiMaterial(o);
  29995. });
  29996. this.materials.forEach(function (o) {
  29997. _this.scene.removeMaterial(o);
  29998. });
  29999. this.morphTargetManagers.forEach(function (o) {
  30000. _this.scene.removeMorphTargetManager(o);
  30001. });
  30002. this.geometries.forEach(function (o) {
  30003. _this.scene.removeGeometry(o);
  30004. });
  30005. this.transformNodes.forEach(function (o) {
  30006. _this.scene.removeTransformNode(o);
  30007. });
  30008. this.actionManagers.forEach(function (o) {
  30009. _this.scene.removeActionManager(o);
  30010. });
  30011. this.textures.forEach(function (o) {
  30012. _this.scene.removeTexture(o);
  30013. });
  30014. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30015. var component = _a[_i];
  30016. component.removeFromContainer(this);
  30017. }
  30018. };
  30019. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  30020. if (!sourceAssets) {
  30021. return;
  30022. }
  30023. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  30024. var asset = sourceAssets_1[_i];
  30025. var move = true;
  30026. if (keepAssets) {
  30027. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  30028. var keepAsset = keepAssets_1[_a];
  30029. if (asset === keepAsset) {
  30030. move = false;
  30031. break;
  30032. }
  30033. }
  30034. }
  30035. if (move) {
  30036. targetAssets.push(asset);
  30037. }
  30038. }
  30039. };
  30040. /**
  30041. * Removes all the assets contained in the scene and adds them to the container.
  30042. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  30043. */
  30044. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  30045. if (keepAssets === undefined) {
  30046. keepAssets = new KeepAssets();
  30047. }
  30048. for (var key in this) {
  30049. if (this.hasOwnProperty(key)) {
  30050. this[key] = this[key] || [];
  30051. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  30052. }
  30053. }
  30054. this.removeAllFromScene();
  30055. };
  30056. /**
  30057. * 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.
  30058. * @returns the root mesh
  30059. */
  30060. AssetContainer.prototype.createRootMesh = function () {
  30061. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  30062. this.meshes.forEach(function (m) {
  30063. if (!m.parent) {
  30064. rootMesh.addChild(m);
  30065. }
  30066. });
  30067. this.meshes.unshift(rootMesh);
  30068. return rootMesh;
  30069. };
  30070. return AssetContainer;
  30071. }(BABYLON.AbstractScene));
  30072. BABYLON.AssetContainer = AssetContainer;
  30073. })(BABYLON || (BABYLON = {}));
  30074. //# sourceMappingURL=babylon.assetContainer.js.map
  30075. var BABYLON;
  30076. (function (BABYLON) {
  30077. /**
  30078. * Class used to store data that will be store in GPU memory
  30079. */
  30080. var Buffer = /** @class */ (function () {
  30081. /**
  30082. * Constructor
  30083. * @param engine the engine
  30084. * @param data the data to use for this buffer
  30085. * @param updatable whether the data is updatable
  30086. * @param stride the stride (optional)
  30087. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30088. * @param instanced whether the buffer is instanced (optional)
  30089. * @param useBytes set to true if the stride in in bytes (optional)
  30090. */
  30091. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  30092. if (stride === void 0) { stride = 0; }
  30093. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  30094. if (instanced === void 0) { instanced = false; }
  30095. if (useBytes === void 0) { useBytes = false; }
  30096. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  30097. this._engine = engine.getScene().getEngine();
  30098. }
  30099. else {
  30100. this._engine = engine;
  30101. }
  30102. this._updatable = updatable;
  30103. this._instanced = instanced;
  30104. this._data = data;
  30105. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  30106. if (!postponeInternalCreation) { // by default
  30107. this.create();
  30108. }
  30109. }
  30110. /**
  30111. * Create a new VertexBuffer based on the current buffer
  30112. * @param kind defines the vertex buffer kind (position, normal, etc.)
  30113. * @param offset defines offset in the buffer (0 by default)
  30114. * @param size defines the size in floats of attributes (position is 3 for instance)
  30115. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  30116. * @param instanced defines if the vertex buffer contains indexed data
  30117. * @param useBytes defines if the offset and stride are in bytes
  30118. * @returns the new vertex buffer
  30119. */
  30120. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  30121. if (useBytes === void 0) { useBytes = false; }
  30122. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  30123. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  30124. // a lot of these parameters are ignored as they are overriden by the buffer
  30125. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  30126. };
  30127. // Properties
  30128. /**
  30129. * Gets a boolean indicating if the Buffer is updatable?
  30130. * @returns true if the buffer is updatable
  30131. */
  30132. Buffer.prototype.isUpdatable = function () {
  30133. return this._updatable;
  30134. };
  30135. /**
  30136. * Gets current buffer's data
  30137. * @returns a DataArray or null
  30138. */
  30139. Buffer.prototype.getData = function () {
  30140. return this._data;
  30141. };
  30142. /**
  30143. * Gets underlying native buffer
  30144. * @returns underlying native buffer
  30145. */
  30146. Buffer.prototype.getBuffer = function () {
  30147. return this._buffer;
  30148. };
  30149. /**
  30150. * Gets the stride in float32 units (i.e. byte stride / 4).
  30151. * May not be an integer if the byte stride is not divisible by 4.
  30152. * DEPRECATED. Use byteStride instead.
  30153. * @returns the stride in float32 units
  30154. */
  30155. Buffer.prototype.getStrideSize = function () {
  30156. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  30157. };
  30158. // Methods
  30159. /**
  30160. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30161. * @param data defines the data to store
  30162. */
  30163. Buffer.prototype.create = function (data) {
  30164. if (data === void 0) { data = null; }
  30165. if (!data && this._buffer) {
  30166. return; // nothing to do
  30167. }
  30168. data = data || this._data;
  30169. if (!data) {
  30170. return;
  30171. }
  30172. if (!this._buffer) { // create buffer
  30173. if (this._updatable) {
  30174. this._buffer = this._engine.createDynamicVertexBuffer(data);
  30175. this._data = data;
  30176. }
  30177. else {
  30178. this._buffer = this._engine.createVertexBuffer(data);
  30179. }
  30180. }
  30181. else if (this._updatable) { // update buffer
  30182. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  30183. this._data = data;
  30184. }
  30185. };
  30186. /** @hidden */
  30187. Buffer.prototype._rebuild = function () {
  30188. this._buffer = null;
  30189. this.create(this._data);
  30190. };
  30191. /**
  30192. * Update current buffer data
  30193. * @param data defines the data to store
  30194. */
  30195. Buffer.prototype.update = function (data) {
  30196. this.create(data);
  30197. };
  30198. /**
  30199. * Updates the data directly.
  30200. * @param data the new data
  30201. * @param offset the new offset
  30202. * @param vertexCount the vertex count (optional)
  30203. * @param useBytes set to true if the offset is in bytes
  30204. */
  30205. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  30206. if (useBytes === void 0) { useBytes = false; }
  30207. if (!this._buffer) {
  30208. return;
  30209. }
  30210. if (this._updatable) { // update buffer
  30211. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  30212. this._data = null;
  30213. }
  30214. };
  30215. /**
  30216. * Release all resources
  30217. */
  30218. Buffer.prototype.dispose = function () {
  30219. if (!this._buffer) {
  30220. return;
  30221. }
  30222. if (this._engine._releaseBuffer(this._buffer)) {
  30223. this._buffer = null;
  30224. }
  30225. };
  30226. return Buffer;
  30227. }());
  30228. BABYLON.Buffer = Buffer;
  30229. })(BABYLON || (BABYLON = {}));
  30230. //# sourceMappingURL=babylon.buffer.js.map
  30231. var BABYLON;
  30232. (function (BABYLON) {
  30233. /**
  30234. * Specialized buffer used to store vertex data
  30235. */
  30236. var VertexBuffer = /** @class */ (function () {
  30237. /**
  30238. * Constructor
  30239. * @param engine the engine
  30240. * @param data the data to use for this vertex buffer
  30241. * @param kind the vertex buffer kind
  30242. * @param updatable whether the data is updatable
  30243. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30244. * @param stride the stride (optional)
  30245. * @param instanced whether the buffer is instanced (optional)
  30246. * @param offset the offset of the data (optional)
  30247. * @param size the number of components (optional)
  30248. * @param type the type of the component (optional)
  30249. * @param normalized whether the data contains normalized data (optional)
  30250. * @param useBytes set to true if stride and offset are in bytes (optional)
  30251. */
  30252. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  30253. if (normalized === void 0) { normalized = false; }
  30254. if (useBytes === void 0) { useBytes = false; }
  30255. if (data instanceof BABYLON.Buffer) {
  30256. this._buffer = data;
  30257. this._ownsBuffer = false;
  30258. }
  30259. else {
  30260. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  30261. this._ownsBuffer = true;
  30262. }
  30263. this._kind = kind;
  30264. if (type == undefined) {
  30265. var data_1 = this.getData();
  30266. this.type = VertexBuffer.FLOAT;
  30267. if (data_1 instanceof Int8Array) {
  30268. this.type = VertexBuffer.BYTE;
  30269. }
  30270. else if (data_1 instanceof Uint8Array) {
  30271. this.type = VertexBuffer.UNSIGNED_BYTE;
  30272. }
  30273. else if (data_1 instanceof Int16Array) {
  30274. this.type = VertexBuffer.SHORT;
  30275. }
  30276. else if (data_1 instanceof Uint16Array) {
  30277. this.type = VertexBuffer.UNSIGNED_SHORT;
  30278. }
  30279. else if (data_1 instanceof Int32Array) {
  30280. this.type = VertexBuffer.INT;
  30281. }
  30282. else if (data_1 instanceof Uint32Array) {
  30283. this.type = VertexBuffer.UNSIGNED_INT;
  30284. }
  30285. }
  30286. else {
  30287. this.type = type;
  30288. }
  30289. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  30290. if (useBytes) {
  30291. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  30292. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  30293. this.byteOffset = offset || 0;
  30294. }
  30295. else {
  30296. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  30297. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  30298. this.byteOffset = (offset || 0) * typeByteLength;
  30299. }
  30300. this.normalized = normalized;
  30301. this._instanced = instanced !== undefined ? instanced : false;
  30302. this._instanceDivisor = instanced ? 1 : 0;
  30303. }
  30304. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  30305. /**
  30306. * Gets or sets the instance divisor when in instanced mode
  30307. */
  30308. get: function () {
  30309. return this._instanceDivisor;
  30310. },
  30311. set: function (value) {
  30312. this._instanceDivisor = value;
  30313. if (value == 0) {
  30314. this._instanced = false;
  30315. }
  30316. else {
  30317. this._instanced = true;
  30318. }
  30319. },
  30320. enumerable: true,
  30321. configurable: true
  30322. });
  30323. /** @hidden */
  30324. VertexBuffer.prototype._rebuild = function () {
  30325. if (!this._buffer) {
  30326. return;
  30327. }
  30328. this._buffer._rebuild();
  30329. };
  30330. /**
  30331. * Returns the kind of the VertexBuffer (string)
  30332. * @returns a string
  30333. */
  30334. VertexBuffer.prototype.getKind = function () {
  30335. return this._kind;
  30336. };
  30337. // Properties
  30338. /**
  30339. * Gets a boolean indicating if the VertexBuffer is updatable?
  30340. * @returns true if the buffer is updatable
  30341. */
  30342. VertexBuffer.prototype.isUpdatable = function () {
  30343. return this._buffer.isUpdatable();
  30344. };
  30345. /**
  30346. * Gets current buffer's data
  30347. * @returns a DataArray or null
  30348. */
  30349. VertexBuffer.prototype.getData = function () {
  30350. return this._buffer.getData();
  30351. };
  30352. /**
  30353. * Gets underlying native buffer
  30354. * @returns underlying native buffer
  30355. */
  30356. VertexBuffer.prototype.getBuffer = function () {
  30357. return this._buffer.getBuffer();
  30358. };
  30359. /**
  30360. * Gets the stride in float32 units (i.e. byte stride / 4).
  30361. * May not be an integer if the byte stride is not divisible by 4.
  30362. * DEPRECATED. Use byteStride instead.
  30363. * @returns the stride in float32 units
  30364. */
  30365. VertexBuffer.prototype.getStrideSize = function () {
  30366. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  30367. };
  30368. /**
  30369. * Returns the offset as a multiple of the type byte length.
  30370. * DEPRECATED. Use byteOffset instead.
  30371. * @returns the offset in bytes
  30372. */
  30373. VertexBuffer.prototype.getOffset = function () {
  30374. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  30375. };
  30376. /**
  30377. * Returns the number of components per vertex attribute (integer)
  30378. * @returns the size in float
  30379. */
  30380. VertexBuffer.prototype.getSize = function () {
  30381. return this._size;
  30382. };
  30383. /**
  30384. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  30385. * @returns true if this buffer is instanced
  30386. */
  30387. VertexBuffer.prototype.getIsInstanced = function () {
  30388. return this._instanced;
  30389. };
  30390. /**
  30391. * Returns the instancing divisor, zero for non-instanced (integer).
  30392. * @returns a number
  30393. */
  30394. VertexBuffer.prototype.getInstanceDivisor = function () {
  30395. return this._instanceDivisor;
  30396. };
  30397. // Methods
  30398. /**
  30399. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30400. * @param data defines the data to store
  30401. */
  30402. VertexBuffer.prototype.create = function (data) {
  30403. this._buffer.create(data);
  30404. };
  30405. /**
  30406. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  30407. * This function will create a new buffer if the current one is not updatable
  30408. * @param data defines the data to store
  30409. */
  30410. VertexBuffer.prototype.update = function (data) {
  30411. this._buffer.update(data);
  30412. };
  30413. /**
  30414. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30415. * Returns the directly updated WebGLBuffer.
  30416. * @param data the new data
  30417. * @param offset the new offset
  30418. * @param useBytes set to true if the offset is in bytes
  30419. */
  30420. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30421. if (useBytes === void 0) { useBytes = false; }
  30422. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30423. };
  30424. /**
  30425. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30426. */
  30427. VertexBuffer.prototype.dispose = function () {
  30428. if (this._ownsBuffer) {
  30429. this._buffer.dispose();
  30430. }
  30431. };
  30432. /**
  30433. * Enumerates each value of this vertex buffer as numbers.
  30434. * @param count the number of values to enumerate
  30435. * @param callback the callback function called for each value
  30436. */
  30437. VertexBuffer.prototype.forEach = function (count, callback) {
  30438. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30439. };
  30440. /**
  30441. * Deduces the stride given a kind.
  30442. * @param kind The kind string to deduce
  30443. * @returns The deduced stride
  30444. */
  30445. VertexBuffer.DeduceStride = function (kind) {
  30446. switch (kind) {
  30447. case VertexBuffer.UVKind:
  30448. case VertexBuffer.UV2Kind:
  30449. case VertexBuffer.UV3Kind:
  30450. case VertexBuffer.UV4Kind:
  30451. case VertexBuffer.UV5Kind:
  30452. case VertexBuffer.UV6Kind:
  30453. return 2;
  30454. case VertexBuffer.NormalKind:
  30455. case VertexBuffer.PositionKind:
  30456. return 3;
  30457. case VertexBuffer.ColorKind:
  30458. case VertexBuffer.MatricesIndicesKind:
  30459. case VertexBuffer.MatricesIndicesExtraKind:
  30460. case VertexBuffer.MatricesWeightsKind:
  30461. case VertexBuffer.MatricesWeightsExtraKind:
  30462. case VertexBuffer.TangentKind:
  30463. return 4;
  30464. default:
  30465. throw new Error("Invalid kind '" + kind + "'");
  30466. }
  30467. };
  30468. /**
  30469. * Gets the byte length of the given type.
  30470. * @param type the type
  30471. * @returns the number of bytes
  30472. */
  30473. VertexBuffer.GetTypeByteLength = function (type) {
  30474. switch (type) {
  30475. case VertexBuffer.BYTE:
  30476. case VertexBuffer.UNSIGNED_BYTE:
  30477. return 1;
  30478. case VertexBuffer.SHORT:
  30479. case VertexBuffer.UNSIGNED_SHORT:
  30480. return 2;
  30481. case VertexBuffer.INT:
  30482. case VertexBuffer.FLOAT:
  30483. return 4;
  30484. default:
  30485. throw new Error("Invalid type '" + type + "'");
  30486. }
  30487. };
  30488. /**
  30489. * Enumerates each value of the given parameters as numbers.
  30490. * @param data the data to enumerate
  30491. * @param byteOffset the byte offset of the data
  30492. * @param byteStride the byte stride of the data
  30493. * @param componentCount the number of components per element
  30494. * @param componentType the type of the component
  30495. * @param count the total number of components
  30496. * @param normalized whether the data is normalized
  30497. * @param callback the callback function called for each value
  30498. */
  30499. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30500. if (data instanceof Array) {
  30501. var offset = byteOffset / 4;
  30502. var stride = byteStride / 4;
  30503. for (var index = 0; index < count; index += componentCount) {
  30504. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30505. callback(data[offset + componentIndex], index + componentIndex);
  30506. }
  30507. offset += stride;
  30508. }
  30509. }
  30510. else {
  30511. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30512. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30513. for (var index = 0; index < count; index += componentCount) {
  30514. var componentByteOffset = byteOffset;
  30515. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30516. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30517. callback(value, index + componentIndex);
  30518. componentByteOffset += componentByteLength;
  30519. }
  30520. byteOffset += byteStride;
  30521. }
  30522. }
  30523. };
  30524. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30525. switch (type) {
  30526. case VertexBuffer.BYTE: {
  30527. var value = dataView.getInt8(byteOffset);
  30528. if (normalized) {
  30529. value = Math.max(value / 127, -1);
  30530. }
  30531. return value;
  30532. }
  30533. case VertexBuffer.UNSIGNED_BYTE: {
  30534. var value = dataView.getUint8(byteOffset);
  30535. if (normalized) {
  30536. value = value / 255;
  30537. }
  30538. return value;
  30539. }
  30540. case VertexBuffer.SHORT: {
  30541. var value = dataView.getInt16(byteOffset, true);
  30542. if (normalized) {
  30543. value = Math.max(value / 16383, -1);
  30544. }
  30545. return value;
  30546. }
  30547. case VertexBuffer.UNSIGNED_SHORT: {
  30548. var value = dataView.getUint16(byteOffset, true);
  30549. if (normalized) {
  30550. value = value / 65535;
  30551. }
  30552. return value;
  30553. }
  30554. case VertexBuffer.FLOAT: {
  30555. return dataView.getFloat32(byteOffset, true);
  30556. }
  30557. default: {
  30558. throw new Error("Invalid component type " + type);
  30559. }
  30560. }
  30561. };
  30562. /**
  30563. * The byte type.
  30564. */
  30565. VertexBuffer.BYTE = 5120;
  30566. /**
  30567. * The unsigned byte type.
  30568. */
  30569. VertexBuffer.UNSIGNED_BYTE = 5121;
  30570. /**
  30571. * The short type.
  30572. */
  30573. VertexBuffer.SHORT = 5122;
  30574. /**
  30575. * The unsigned short type.
  30576. */
  30577. VertexBuffer.UNSIGNED_SHORT = 5123;
  30578. /**
  30579. * The integer type.
  30580. */
  30581. VertexBuffer.INT = 5124;
  30582. /**
  30583. * The unsigned integer type.
  30584. */
  30585. VertexBuffer.UNSIGNED_INT = 5125;
  30586. /**
  30587. * The float type.
  30588. */
  30589. VertexBuffer.FLOAT = 5126;
  30590. // Enums
  30591. /**
  30592. * Positions
  30593. */
  30594. VertexBuffer.PositionKind = "position";
  30595. /**
  30596. * Normals
  30597. */
  30598. VertexBuffer.NormalKind = "normal";
  30599. /**
  30600. * Tangents
  30601. */
  30602. VertexBuffer.TangentKind = "tangent";
  30603. /**
  30604. * Texture coordinates
  30605. */
  30606. VertexBuffer.UVKind = "uv";
  30607. /**
  30608. * Texture coordinates 2
  30609. */
  30610. VertexBuffer.UV2Kind = "uv2";
  30611. /**
  30612. * Texture coordinates 3
  30613. */
  30614. VertexBuffer.UV3Kind = "uv3";
  30615. /**
  30616. * Texture coordinates 4
  30617. */
  30618. VertexBuffer.UV4Kind = "uv4";
  30619. /**
  30620. * Texture coordinates 5
  30621. */
  30622. VertexBuffer.UV5Kind = "uv5";
  30623. /**
  30624. * Texture coordinates 6
  30625. */
  30626. VertexBuffer.UV6Kind = "uv6";
  30627. /**
  30628. * Colors
  30629. */
  30630. VertexBuffer.ColorKind = "color";
  30631. /**
  30632. * Matrix indices (for bones)
  30633. */
  30634. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30635. /**
  30636. * Matrix weights (for bones)
  30637. */
  30638. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30639. /**
  30640. * Additional matrix indices (for bones)
  30641. */
  30642. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30643. /**
  30644. * Additional matrix weights (for bones)
  30645. */
  30646. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30647. return VertexBuffer;
  30648. }());
  30649. BABYLON.VertexBuffer = VertexBuffer;
  30650. })(BABYLON || (BABYLON = {}));
  30651. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30652. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30653. var BABYLON;
  30654. (function (BABYLON) {
  30655. /**
  30656. * Internal class used by the engine to get list of InternalTexture already bound to the GL context
  30657. */
  30658. var DummyInternalTextureTracker = /** @class */ (function () {
  30659. function DummyInternalTextureTracker() {
  30660. /**
  30661. * Gets or set the previous tracker in the list
  30662. */
  30663. this.previous = null;
  30664. /**
  30665. * Gets or set the next tracker in the list
  30666. */
  30667. this.next = null;
  30668. }
  30669. return DummyInternalTextureTracker;
  30670. }());
  30671. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30672. })(BABYLON || (BABYLON = {}));
  30673. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30674. var BABYLON;
  30675. (function (BABYLON) {
  30676. /**
  30677. * Class used to store data associated with WebGL texture data for the engine
  30678. * This class should not be used directly
  30679. */
  30680. var InternalTexture = /** @class */ (function () {
  30681. /**
  30682. * Creates a new InternalTexture
  30683. * @param engine defines the engine to use
  30684. * @param dataSource defines the type of data that will be used
  30685. * @param delayAllocation if the texture allocation should be delayed (default: false)
  30686. */
  30687. function InternalTexture(engine, dataSource, delayAllocation) {
  30688. if (delayAllocation === void 0) { delayAllocation = false; }
  30689. /**
  30690. * Observable called when the texture is loaded
  30691. */
  30692. this.onLoadedObservable = new BABYLON.Observable();
  30693. /**
  30694. * Gets or set the previous tracker in the list
  30695. */
  30696. this.previous = null;
  30697. /**
  30698. * Gets or set the next tracker in the list
  30699. */
  30700. this.next = null;
  30701. // Private
  30702. /** @hidden */
  30703. this._initialSlot = -1;
  30704. /** @hidden */
  30705. this._designatedSlot = -1;
  30706. /** @hidden */
  30707. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30708. /** @hidden */
  30709. this._comparisonFunction = 0;
  30710. /** @hidden */
  30711. this._sphericalPolynomial = null;
  30712. /** @hidden */
  30713. this._lodGenerationScale = 0;
  30714. /** @hidden */
  30715. this._lodGenerationOffset = 0;
  30716. /** @hidden */
  30717. this._isRGBD = false;
  30718. /** @hidden */
  30719. this._references = 1;
  30720. this._engine = engine;
  30721. this._dataSource = dataSource;
  30722. if (!delayAllocation) {
  30723. this._webGLTexture = engine._createTexture();
  30724. }
  30725. }
  30726. /**
  30727. * Gets the Engine the texture belongs to.
  30728. * @returns The babylon engine
  30729. */
  30730. InternalTexture.prototype.getEngine = function () {
  30731. return this._engine;
  30732. };
  30733. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30734. /**
  30735. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30736. */
  30737. get: function () {
  30738. return this._dataSource;
  30739. },
  30740. enumerable: true,
  30741. configurable: true
  30742. });
  30743. /**
  30744. * Increments the number of references (ie. the number of Texture that point to it)
  30745. */
  30746. InternalTexture.prototype.incrementReferences = function () {
  30747. this._references++;
  30748. };
  30749. /**
  30750. * Change the size of the texture (not the size of the content)
  30751. * @param width defines the new width
  30752. * @param height defines the new height
  30753. * @param depth defines the new depth (1 by default)
  30754. */
  30755. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30756. if (depth === void 0) { depth = 1; }
  30757. this.width = width;
  30758. this.height = height;
  30759. this.depth = depth;
  30760. this.baseWidth = width;
  30761. this.baseHeight = height;
  30762. this.baseDepth = depth;
  30763. this._size = width * height * depth;
  30764. };
  30765. /** @hidden */
  30766. InternalTexture.prototype._rebuild = function () {
  30767. var _this = this;
  30768. var proxy;
  30769. this.isReady = false;
  30770. this._cachedCoordinatesMode = null;
  30771. this._cachedWrapU = null;
  30772. this._cachedWrapV = null;
  30773. this._cachedAnisotropicFilteringLevel = null;
  30774. switch (this._dataSource) {
  30775. case InternalTexture.DATASOURCE_TEMP:
  30776. return;
  30777. case InternalTexture.DATASOURCE_URL:
  30778. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30779. _this.isReady = true;
  30780. }, null, this._buffer, undefined, this.format);
  30781. proxy._swapAndDie(this);
  30782. return;
  30783. case InternalTexture.DATASOURCE_RAW:
  30784. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30785. proxy._swapAndDie(this);
  30786. this.isReady = true;
  30787. return;
  30788. case InternalTexture.DATASOURCE_RAW3D:
  30789. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30790. proxy._swapAndDie(this);
  30791. this.isReady = true;
  30792. return;
  30793. case InternalTexture.DATASOURCE_DYNAMIC:
  30794. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30795. proxy._swapAndDie(this);
  30796. // The engine will make sure to update content so no need to flag it as isReady = true
  30797. return;
  30798. case InternalTexture.DATASOURCE_RENDERTARGET:
  30799. var options = new BABYLON.RenderTargetCreationOptions();
  30800. options.generateDepthBuffer = this._generateDepthBuffer;
  30801. options.generateMipMaps = this.generateMipMaps;
  30802. options.generateStencilBuffer = this._generateStencilBuffer;
  30803. options.samplingMode = this.samplingMode;
  30804. options.type = this.type;
  30805. if (this.isCube) {
  30806. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30807. }
  30808. else {
  30809. var size = {
  30810. width: this.width,
  30811. height: this.height
  30812. };
  30813. proxy = this._engine.createRenderTargetTexture(size, options);
  30814. }
  30815. proxy._swapAndDie(this);
  30816. this.isReady = true;
  30817. return;
  30818. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30819. var depthTextureOptions = {
  30820. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30821. comparisonFunction: this._comparisonFunction,
  30822. generateStencil: this._generateStencilBuffer,
  30823. isCube: this.isCube
  30824. };
  30825. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30826. proxy._swapAndDie(this);
  30827. this.isReady = true;
  30828. return;
  30829. case InternalTexture.DATASOURCE_CUBE:
  30830. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30831. _this.isReady = true;
  30832. }, null, this.format, this._extension);
  30833. proxy._swapAndDie(this);
  30834. return;
  30835. case InternalTexture.DATASOURCE_CUBERAW:
  30836. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30837. proxy._swapAndDie(this);
  30838. this.isReady = true;
  30839. return;
  30840. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30841. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30842. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30843. _this.isReady = true;
  30844. });
  30845. proxy._swapAndDie(this);
  30846. return;
  30847. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30848. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30849. if (proxy) {
  30850. proxy._swapAndDie(_this);
  30851. }
  30852. _this.isReady = true;
  30853. }, null, this.format, this._extension);
  30854. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30855. return;
  30856. }
  30857. };
  30858. /** @hidden */
  30859. InternalTexture.prototype._swapAndDie = function (target) {
  30860. target._webGLTexture = this._webGLTexture;
  30861. if (this._framebuffer) {
  30862. target._framebuffer = this._framebuffer;
  30863. }
  30864. if (this._depthStencilBuffer) {
  30865. target._depthStencilBuffer = this._depthStencilBuffer;
  30866. }
  30867. if (this._lodTextureHigh) {
  30868. if (target._lodTextureHigh) {
  30869. target._lodTextureHigh.dispose();
  30870. }
  30871. target._lodTextureHigh = this._lodTextureHigh;
  30872. }
  30873. if (this._lodTextureMid) {
  30874. if (target._lodTextureMid) {
  30875. target._lodTextureMid.dispose();
  30876. }
  30877. target._lodTextureMid = this._lodTextureMid;
  30878. }
  30879. if (this._lodTextureLow) {
  30880. if (target._lodTextureLow) {
  30881. target._lodTextureLow.dispose();
  30882. }
  30883. target._lodTextureLow = this._lodTextureLow;
  30884. }
  30885. var cache = this._engine.getLoadedTexturesCache();
  30886. var index = cache.indexOf(this);
  30887. if (index !== -1) {
  30888. cache.splice(index, 1);
  30889. }
  30890. };
  30891. /**
  30892. * Dispose the current allocated resources
  30893. */
  30894. InternalTexture.prototype.dispose = function () {
  30895. if (!this._webGLTexture) {
  30896. return;
  30897. }
  30898. this._references--;
  30899. if (this._references === 0) {
  30900. this._engine._releaseTexture(this);
  30901. this._webGLTexture = null;
  30902. this.previous = null;
  30903. this.next = null;
  30904. }
  30905. };
  30906. /**
  30907. * The source of the texture data is unknown
  30908. */
  30909. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30910. /**
  30911. * Texture data comes from an URL
  30912. */
  30913. InternalTexture.DATASOURCE_URL = 1;
  30914. /**
  30915. * Texture data is only used for temporary storage
  30916. */
  30917. InternalTexture.DATASOURCE_TEMP = 2;
  30918. /**
  30919. * Texture data comes from raw data (ArrayBuffer)
  30920. */
  30921. InternalTexture.DATASOURCE_RAW = 3;
  30922. /**
  30923. * Texture content is dynamic (video or dynamic texture)
  30924. */
  30925. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30926. /**
  30927. * Texture content is generated by rendering to it
  30928. */
  30929. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30930. /**
  30931. * Texture content is part of a multi render target process
  30932. */
  30933. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30934. /**
  30935. * Texture data comes from a cube data file
  30936. */
  30937. InternalTexture.DATASOURCE_CUBE = 7;
  30938. /**
  30939. * Texture data comes from a raw cube data
  30940. */
  30941. InternalTexture.DATASOURCE_CUBERAW = 8;
  30942. /**
  30943. * Texture data come from a prefiltered cube data file
  30944. */
  30945. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30946. /**
  30947. * Texture content is raw 3D data
  30948. */
  30949. InternalTexture.DATASOURCE_RAW3D = 10;
  30950. /**
  30951. * Texture content is a depth texture
  30952. */
  30953. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30954. /**
  30955. * Texture data comes from a raw cube data encoded with RGBD
  30956. */
  30957. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30958. return InternalTexture;
  30959. }());
  30960. BABYLON.InternalTexture = InternalTexture;
  30961. })(BABYLON || (BABYLON = {}));
  30962. //# sourceMappingURL=babylon.internalTexture.js.map
  30963. var BABYLON;
  30964. (function (BABYLON) {
  30965. /**
  30966. * Base class of all the textures in babylon.
  30967. * It groups all the common properties the materials, post process, lights... might need
  30968. * in order to make a correct use of the texture.
  30969. */
  30970. var BaseTexture = /** @class */ (function () {
  30971. /**
  30972. * Instantiates a new BaseTexture.
  30973. * Base class of all the textures in babylon.
  30974. * It groups all the common properties the materials, post process, lights... might need
  30975. * in order to make a correct use of the texture.
  30976. * @param scene Define the scene the texture blongs to
  30977. */
  30978. function BaseTexture(scene) {
  30979. this._hasAlpha = false;
  30980. /**
  30981. * Defines if the alpha value should be determined via the rgb values.
  30982. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  30983. */
  30984. this.getAlphaFromRGB = false;
  30985. /**
  30986. * Intensity or strength of the texture.
  30987. * It is commonly used by materials to fine tune the intensity of the texture
  30988. */
  30989. this.level = 1;
  30990. /**
  30991. * Define the UV chanel to use starting from 0 and defaulting to 0.
  30992. * This is part of the texture as textures usually maps to one uv set.
  30993. */
  30994. this.coordinatesIndex = 0;
  30995. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30996. /**
  30997. * | Value | Type | Description |
  30998. * | ----- | ------------------ | ----------- |
  30999. * | 0 | CLAMP_ADDRESSMODE | |
  31000. * | 1 | WRAP_ADDRESSMODE | |
  31001. * | 2 | MIRROR_ADDRESSMODE | |
  31002. */
  31003. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31004. /**
  31005. * | Value | Type | Description |
  31006. * | ----- | ------------------ | ----------- |
  31007. * | 0 | CLAMP_ADDRESSMODE | |
  31008. * | 1 | WRAP_ADDRESSMODE | |
  31009. * | 2 | MIRROR_ADDRESSMODE | |
  31010. */
  31011. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31012. /**
  31013. * | Value | Type | Description |
  31014. * | ----- | ------------------ | ----------- |
  31015. * | 0 | CLAMP_ADDRESSMODE | |
  31016. * | 1 | WRAP_ADDRESSMODE | |
  31017. * | 2 | MIRROR_ADDRESSMODE | |
  31018. */
  31019. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  31020. /**
  31021. * With compliant hardware and browser (supporting anisotropic filtering)
  31022. * this defines the level of anisotropic filtering in the texture.
  31023. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  31024. */
  31025. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  31026. /**
  31027. * Define if the texture is a cube texture or if false a 2d texture.
  31028. */
  31029. this.isCube = false;
  31030. /**
  31031. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  31032. */
  31033. this.is3D = false;
  31034. /**
  31035. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  31036. * HDR texture are usually stored in linear space.
  31037. * This only impacts the PBR and Background materials
  31038. */
  31039. this.gammaSpace = true;
  31040. /**
  31041. * Is Z inverted in the texture (useful in a cube texture).
  31042. */
  31043. this.invertZ = false;
  31044. /**
  31045. * @hidden
  31046. */
  31047. this.lodLevelInAlpha = false;
  31048. /**
  31049. * Define if the texture is a render target.
  31050. */
  31051. this.isRenderTarget = false;
  31052. /**
  31053. * Define the list of animation attached to the texture.
  31054. */
  31055. this.animations = new Array();
  31056. /**
  31057. * An event triggered when the texture is disposed.
  31058. */
  31059. this.onDisposeObservable = new BABYLON.Observable();
  31060. /**
  31061. * Define the current state of the loading sequence when in delayed load mode.
  31062. */
  31063. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31064. this._cachedSize = BABYLON.Size.Zero();
  31065. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31066. if (this._scene) {
  31067. this._scene.textures.push(this);
  31068. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  31069. }
  31070. this._uid = null;
  31071. }
  31072. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  31073. get: function () {
  31074. return this._hasAlpha;
  31075. },
  31076. /**
  31077. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  31078. */
  31079. set: function (value) {
  31080. if (this._hasAlpha === value) {
  31081. return;
  31082. }
  31083. this._hasAlpha = value;
  31084. if (this._scene) {
  31085. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  31086. }
  31087. },
  31088. enumerable: true,
  31089. configurable: true
  31090. });
  31091. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  31092. get: function () {
  31093. return this._coordinatesMode;
  31094. },
  31095. /**
  31096. * How a texture is mapped.
  31097. *
  31098. * | Value | Type | Description |
  31099. * | ----- | ----------------------------------- | ----------- |
  31100. * | 0 | EXPLICIT_MODE | |
  31101. * | 1 | SPHERICAL_MODE | |
  31102. * | 2 | PLANAR_MODE | |
  31103. * | 3 | CUBIC_MODE | |
  31104. * | 4 | PROJECTION_MODE | |
  31105. * | 5 | SKYBOX_MODE | |
  31106. * | 6 | INVCUBIC_MODE | |
  31107. * | 7 | EQUIRECTANGULAR_MODE | |
  31108. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  31109. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  31110. */
  31111. set: function (value) {
  31112. if (this._coordinatesMode === value) {
  31113. return;
  31114. }
  31115. this._coordinatesMode = value;
  31116. if (this._scene) {
  31117. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31118. }
  31119. },
  31120. enumerable: true,
  31121. configurable: true
  31122. });
  31123. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  31124. /**
  31125. * Gets whether or not the texture contains RGBD data.
  31126. */
  31127. get: function () {
  31128. return this._texture != null && this._texture._isRGBD;
  31129. },
  31130. enumerable: true,
  31131. configurable: true
  31132. });
  31133. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  31134. /**
  31135. * With prefiltered texture, defined the offset used during the prefiltering steps.
  31136. */
  31137. get: function () {
  31138. if (this._texture) {
  31139. return this._texture._lodGenerationOffset;
  31140. }
  31141. return 0.0;
  31142. },
  31143. set: function (value) {
  31144. if (this._texture) {
  31145. this._texture._lodGenerationOffset = value;
  31146. }
  31147. },
  31148. enumerable: true,
  31149. configurable: true
  31150. });
  31151. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  31152. /**
  31153. * With prefiltered texture, defined the scale used during the prefiltering steps.
  31154. */
  31155. get: function () {
  31156. if (this._texture) {
  31157. return this._texture._lodGenerationScale;
  31158. }
  31159. return 0.0;
  31160. },
  31161. set: function (value) {
  31162. if (this._texture) {
  31163. this._texture._lodGenerationScale = value;
  31164. }
  31165. },
  31166. enumerable: true,
  31167. configurable: true
  31168. });
  31169. Object.defineProperty(BaseTexture.prototype, "uid", {
  31170. /**
  31171. * Define the unique id of the texture in the scene.
  31172. */
  31173. get: function () {
  31174. if (!this._uid) {
  31175. this._uid = BABYLON.Tools.RandomId();
  31176. }
  31177. return this._uid;
  31178. },
  31179. enumerable: true,
  31180. configurable: true
  31181. });
  31182. /**
  31183. * Return a string representation of the texture.
  31184. * @returns the texture as a string
  31185. */
  31186. BaseTexture.prototype.toString = function () {
  31187. return this.name;
  31188. };
  31189. /**
  31190. * Get the class name of the texture.
  31191. * @returns "BaseTexture"
  31192. */
  31193. BaseTexture.prototype.getClassName = function () {
  31194. return "BaseTexture";
  31195. };
  31196. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  31197. /**
  31198. * Callback triggered when the texture has been disposed.
  31199. * Kept for back compatibility, you can use the onDisposeObservable instead.
  31200. */
  31201. set: function (callback) {
  31202. if (this._onDisposeObserver) {
  31203. this.onDisposeObservable.remove(this._onDisposeObserver);
  31204. }
  31205. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31206. },
  31207. enumerable: true,
  31208. configurable: true
  31209. });
  31210. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  31211. /**
  31212. * Define if the texture is preventinga material to render or not.
  31213. * If not and the texture is not ready, the engine will use a default black texture instead.
  31214. */
  31215. get: function () {
  31216. return true;
  31217. },
  31218. enumerable: true,
  31219. configurable: true
  31220. });
  31221. /**
  31222. * Get the scene the texture belongs to.
  31223. * @returns the scene or null if undefined
  31224. */
  31225. BaseTexture.prototype.getScene = function () {
  31226. return this._scene;
  31227. };
  31228. /**
  31229. * Get the texture transform matrix used to offset tile the texture for istance.
  31230. * @returns the transformation matrix
  31231. */
  31232. BaseTexture.prototype.getTextureMatrix = function () {
  31233. return BABYLON.Matrix.IdentityReadOnly;
  31234. };
  31235. /**
  31236. * Get the texture reflection matrix used to rotate/transform the reflection.
  31237. * @returns the reflection matrix
  31238. */
  31239. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  31240. return BABYLON.Matrix.IdentityReadOnly;
  31241. };
  31242. /**
  31243. * Get the underlying lower level texture from Babylon.
  31244. * @returns the insternal texture
  31245. */
  31246. BaseTexture.prototype.getInternalTexture = function () {
  31247. return this._texture;
  31248. };
  31249. /**
  31250. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  31251. * @returns true if ready or not blocking
  31252. */
  31253. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  31254. return !this.isBlocking || this.isReady();
  31255. };
  31256. /**
  31257. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  31258. * @returns true if fully ready
  31259. */
  31260. BaseTexture.prototype.isReady = function () {
  31261. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31262. this.delayLoad();
  31263. return false;
  31264. }
  31265. if (this._texture) {
  31266. return this._texture.isReady;
  31267. }
  31268. return false;
  31269. };
  31270. /**
  31271. * Get the size of the texture.
  31272. * @returns the texture size.
  31273. */
  31274. BaseTexture.prototype.getSize = function () {
  31275. if (this._texture) {
  31276. if (this._texture.width) {
  31277. this._cachedSize.width = this._texture.width;
  31278. this._cachedSize.height = this._texture.height;
  31279. return this._cachedSize;
  31280. }
  31281. if (this._texture._size) {
  31282. this._cachedSize.width = this._texture._size;
  31283. this._cachedSize.height = this._texture._size;
  31284. return this._cachedSize;
  31285. }
  31286. }
  31287. return this._cachedSize;
  31288. };
  31289. /**
  31290. * Get the base size of the texture.
  31291. * It can be different from the size if the texture has been resized for POT for instance
  31292. * @returns the base size
  31293. */
  31294. BaseTexture.prototype.getBaseSize = function () {
  31295. if (!this.isReady() || !this._texture) {
  31296. return BABYLON.Size.Zero();
  31297. }
  31298. if (this._texture._size) {
  31299. return new BABYLON.Size(this._texture._size, this._texture._size);
  31300. }
  31301. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  31302. };
  31303. /**
  31304. * Scales the texture if is `canRescale()`
  31305. * @param ratio the resize factor we want to use to rescale
  31306. */
  31307. BaseTexture.prototype.scale = function (ratio) {
  31308. };
  31309. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  31310. /**
  31311. * Get if the texture can rescale.
  31312. */
  31313. get: function () {
  31314. return false;
  31315. },
  31316. enumerable: true,
  31317. configurable: true
  31318. });
  31319. /** @hidden */
  31320. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  31321. if (!this._scene) {
  31322. return null;
  31323. }
  31324. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  31325. for (var index = 0; index < texturesCache.length; index++) {
  31326. var texturesCacheEntry = texturesCache[index];
  31327. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  31328. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  31329. texturesCacheEntry.incrementReferences();
  31330. return texturesCacheEntry;
  31331. }
  31332. }
  31333. }
  31334. return null;
  31335. };
  31336. /** @hidden */
  31337. BaseTexture.prototype._rebuild = function () {
  31338. };
  31339. /**
  31340. * Triggers the load sequence in delayed load mode.
  31341. */
  31342. BaseTexture.prototype.delayLoad = function () {
  31343. };
  31344. /**
  31345. * Clones the texture.
  31346. * @returns the cloned texture
  31347. */
  31348. BaseTexture.prototype.clone = function () {
  31349. return null;
  31350. };
  31351. Object.defineProperty(BaseTexture.prototype, "textureType", {
  31352. /**
  31353. * Get the texture underlying type (INT, FLOAT...)
  31354. */
  31355. get: function () {
  31356. if (!this._texture) {
  31357. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31358. }
  31359. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31360. },
  31361. enumerable: true,
  31362. configurable: true
  31363. });
  31364. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  31365. /**
  31366. * Get the texture underlying format (RGB, RGBA...)
  31367. */
  31368. get: function () {
  31369. if (!this._texture) {
  31370. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31371. }
  31372. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31373. },
  31374. enumerable: true,
  31375. configurable: true
  31376. });
  31377. /**
  31378. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  31379. * This will returns an RGBA array buffer containing either in values (0-255) or
  31380. * float values (0-1) depending of the underlying buffer type.
  31381. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  31382. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  31383. * @param buffer defines a user defined buffer to fill with data (can be null)
  31384. * @returns The Array buffer containing the pixels data.
  31385. */
  31386. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  31387. if (faceIndex === void 0) { faceIndex = 0; }
  31388. if (level === void 0) { level = 0; }
  31389. if (buffer === void 0) { buffer = null; }
  31390. if (!this._texture) {
  31391. return null;
  31392. }
  31393. var size = this.getSize();
  31394. var width = size.width;
  31395. var height = size.height;
  31396. var scene = this.getScene();
  31397. if (!scene) {
  31398. return null;
  31399. }
  31400. var engine = scene.getEngine();
  31401. if (level != 0) {
  31402. width = width / Math.pow(2, level);
  31403. height = height / Math.pow(2, level);
  31404. width = Math.round(width);
  31405. height = Math.round(height);
  31406. }
  31407. if (this._texture.isCube) {
  31408. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  31409. }
  31410. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  31411. };
  31412. /**
  31413. * Release and destroy the underlying lower level texture aka internalTexture.
  31414. */
  31415. BaseTexture.prototype.releaseInternalTexture = function () {
  31416. if (this._texture) {
  31417. this._texture.dispose();
  31418. this._texture = null;
  31419. }
  31420. };
  31421. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  31422. /**
  31423. * Get the polynomial representation of the texture data.
  31424. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  31425. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  31426. */
  31427. get: function () {
  31428. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  31429. return null;
  31430. }
  31431. if (!this._texture._sphericalPolynomial) {
  31432. this._texture._sphericalPolynomial =
  31433. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  31434. }
  31435. return this._texture._sphericalPolynomial;
  31436. },
  31437. set: function (value) {
  31438. if (this._texture) {
  31439. this._texture._sphericalPolynomial = value;
  31440. }
  31441. },
  31442. enumerable: true,
  31443. configurable: true
  31444. });
  31445. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  31446. /** @hidden */
  31447. get: function () {
  31448. if (this._texture) {
  31449. return this._texture._lodTextureHigh;
  31450. }
  31451. return null;
  31452. },
  31453. enumerable: true,
  31454. configurable: true
  31455. });
  31456. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31457. /** @hidden */
  31458. get: function () {
  31459. if (this._texture) {
  31460. return this._texture._lodTextureMid;
  31461. }
  31462. return null;
  31463. },
  31464. enumerable: true,
  31465. configurable: true
  31466. });
  31467. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31468. /** @hidden */
  31469. get: function () {
  31470. if (this._texture) {
  31471. return this._texture._lodTextureLow;
  31472. }
  31473. return null;
  31474. },
  31475. enumerable: true,
  31476. configurable: true
  31477. });
  31478. /**
  31479. * Dispose the texture and release its associated resources.
  31480. */
  31481. BaseTexture.prototype.dispose = function () {
  31482. if (!this._scene) {
  31483. return;
  31484. }
  31485. // Animations
  31486. this._scene.stopAnimation(this);
  31487. // Remove from scene
  31488. this._scene._removePendingData(this);
  31489. var index = this._scene.textures.indexOf(this);
  31490. if (index >= 0) {
  31491. this._scene.textures.splice(index, 1);
  31492. }
  31493. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31494. if (this._texture === undefined) {
  31495. return;
  31496. }
  31497. // Release
  31498. this.releaseInternalTexture();
  31499. // Callback
  31500. this.onDisposeObservable.notifyObservers(this);
  31501. this.onDisposeObservable.clear();
  31502. };
  31503. /**
  31504. * Serialize the texture into a JSON representation that can be parsed later on.
  31505. * @returns the JSON representation of the texture
  31506. */
  31507. BaseTexture.prototype.serialize = function () {
  31508. if (!this.name) {
  31509. return null;
  31510. }
  31511. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31512. // Animations
  31513. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31514. return serializationObject;
  31515. };
  31516. /**
  31517. * Helper function to be called back once a list of texture contains only ready textures.
  31518. * @param textures Define the list of textures to wait for
  31519. * @param callback Define the callback triggered once the entire list will be ready
  31520. */
  31521. BaseTexture.WhenAllReady = function (textures, callback) {
  31522. var numRemaining = textures.length;
  31523. if (numRemaining === 0) {
  31524. callback();
  31525. return;
  31526. }
  31527. var _loop_1 = function () {
  31528. texture = textures[i];
  31529. if (texture.isReady()) {
  31530. if (--numRemaining === 0) {
  31531. callback();
  31532. }
  31533. }
  31534. else {
  31535. onLoadObservable = texture.onLoadObservable;
  31536. var onLoadCallback_1 = function () {
  31537. onLoadObservable.removeCallback(onLoadCallback_1);
  31538. if (--numRemaining === 0) {
  31539. callback();
  31540. }
  31541. };
  31542. onLoadObservable.add(onLoadCallback_1);
  31543. }
  31544. };
  31545. var texture, onLoadObservable;
  31546. for (var i = 0; i < textures.length; i++) {
  31547. _loop_1();
  31548. }
  31549. };
  31550. /**
  31551. * Default anisotropic filtering level for the application.
  31552. * It is set to 4 as a good tradeoff between perf and quality.
  31553. */
  31554. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31555. __decorate([
  31556. BABYLON.serialize()
  31557. ], BaseTexture.prototype, "name", void 0);
  31558. __decorate([
  31559. BABYLON.serialize("hasAlpha")
  31560. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31561. __decorate([
  31562. BABYLON.serialize()
  31563. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31564. __decorate([
  31565. BABYLON.serialize()
  31566. ], BaseTexture.prototype, "level", void 0);
  31567. __decorate([
  31568. BABYLON.serialize()
  31569. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31570. __decorate([
  31571. BABYLON.serialize("coordinatesMode")
  31572. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31573. __decorate([
  31574. BABYLON.serialize()
  31575. ], BaseTexture.prototype, "wrapU", void 0);
  31576. __decorate([
  31577. BABYLON.serialize()
  31578. ], BaseTexture.prototype, "wrapV", void 0);
  31579. __decorate([
  31580. BABYLON.serialize()
  31581. ], BaseTexture.prototype, "wrapR", void 0);
  31582. __decorate([
  31583. BABYLON.serialize()
  31584. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31585. __decorate([
  31586. BABYLON.serialize()
  31587. ], BaseTexture.prototype, "isCube", void 0);
  31588. __decorate([
  31589. BABYLON.serialize()
  31590. ], BaseTexture.prototype, "is3D", void 0);
  31591. __decorate([
  31592. BABYLON.serialize()
  31593. ], BaseTexture.prototype, "gammaSpace", void 0);
  31594. __decorate([
  31595. BABYLON.serialize()
  31596. ], BaseTexture.prototype, "invertZ", void 0);
  31597. __decorate([
  31598. BABYLON.serialize()
  31599. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31600. __decorate([
  31601. BABYLON.serialize()
  31602. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31603. __decorate([
  31604. BABYLON.serialize()
  31605. ], BaseTexture.prototype, "lodGenerationScale", null);
  31606. __decorate([
  31607. BABYLON.serialize()
  31608. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31609. return BaseTexture;
  31610. }());
  31611. BABYLON.BaseTexture = BaseTexture;
  31612. })(BABYLON || (BABYLON = {}));
  31613. //# sourceMappingURL=babylon.baseTexture.js.map
  31614. var BABYLON;
  31615. (function (BABYLON) {
  31616. /**
  31617. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31618. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31619. */
  31620. var Texture = /** @class */ (function (_super) {
  31621. __extends(Texture, _super);
  31622. /**
  31623. * Instantiates a new texture.
  31624. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31625. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31626. * @param url define the url of the picture to load as a texture
  31627. * @param scene define the scene the texture will belong to
  31628. * @param noMipmap define if the texture will require mip maps or not
  31629. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31630. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31631. * @param onLoad define a callback triggered when the texture has been loaded
  31632. * @param onError define a callback triggered when an error occurred during the loading session
  31633. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31634. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31635. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31636. */
  31637. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31638. if (noMipmap === void 0) { noMipmap = false; }
  31639. if (invertY === void 0) { invertY = true; }
  31640. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31641. if (onLoad === void 0) { onLoad = null; }
  31642. if (onError === void 0) { onError = null; }
  31643. if (buffer === void 0) { buffer = null; }
  31644. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31645. var _this = _super.call(this, scene) || this;
  31646. /**
  31647. * Define an offset on the texture to offset the u coordinates of the UVs
  31648. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31649. */
  31650. _this.uOffset = 0;
  31651. /**
  31652. * Define an offset on the texture to offset the v coordinates of the UVs
  31653. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31654. */
  31655. _this.vOffset = 0;
  31656. /**
  31657. * Define an offset on the texture to scale the u coordinates of the UVs
  31658. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31659. */
  31660. _this.uScale = 1.0;
  31661. /**
  31662. * Define an offset on the texture to scale the v coordinates of the UVs
  31663. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31664. */
  31665. _this.vScale = 1.0;
  31666. /**
  31667. * Define an offset on the texture to rotate around the u coordinates of the UVs
  31668. * @see http://doc.babylonjs.com/how_to/more_materials
  31669. */
  31670. _this.uAng = 0;
  31671. /**
  31672. * Define an offset on the texture to rotate around the v coordinates of the UVs
  31673. * @see http://doc.babylonjs.com/how_to/more_materials
  31674. */
  31675. _this.vAng = 0;
  31676. /**
  31677. * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
  31678. * @see http://doc.babylonjs.com/how_to/more_materials
  31679. */
  31680. _this.wAng = 0;
  31681. /**
  31682. * Defines the center of rotation (U)
  31683. */
  31684. _this.uRotationCenter = 0.5;
  31685. /**
  31686. * Defines the center of rotation (V)
  31687. */
  31688. _this.vRotationCenter = 0.5;
  31689. /**
  31690. * Defines the center of rotation (W)
  31691. */
  31692. _this.wRotationCenter = 0.5;
  31693. /**
  31694. * Observable triggered once the texture has been loaded.
  31695. */
  31696. _this.onLoadObservable = new BABYLON.Observable();
  31697. _this._isBlocking = true;
  31698. _this.name = url || "";
  31699. _this.url = url;
  31700. _this._noMipmap = noMipmap;
  31701. _this._invertY = invertY;
  31702. _this._samplingMode = samplingMode;
  31703. _this._buffer = buffer;
  31704. _this._deleteBuffer = deleteBuffer;
  31705. if (format) {
  31706. _this._format = format;
  31707. }
  31708. scene = _this.getScene();
  31709. if (!scene) {
  31710. return _this;
  31711. }
  31712. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31713. var load = function () {
  31714. if (_this.onLoadObservable.hasObservers()) {
  31715. _this.onLoadObservable.notifyObservers(_this);
  31716. }
  31717. if (onLoad) {
  31718. onLoad();
  31719. }
  31720. if (!_this.isBlocking && scene) {
  31721. scene.resetCachedMaterial();
  31722. }
  31723. };
  31724. if (!_this.url) {
  31725. _this._delayedOnLoad = load;
  31726. _this._delayedOnError = onError;
  31727. return _this;
  31728. }
  31729. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31730. if (!_this._texture) {
  31731. if (!scene.useDelayedTextureLoading) {
  31732. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31733. if (deleteBuffer) {
  31734. delete _this._buffer;
  31735. }
  31736. }
  31737. else {
  31738. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31739. _this._delayedOnLoad = load;
  31740. _this._delayedOnError = onError;
  31741. }
  31742. }
  31743. else {
  31744. if (_this._texture.isReady) {
  31745. BABYLON.Tools.SetImmediate(function () { return load(); });
  31746. }
  31747. else {
  31748. _this._texture.onLoadedObservable.add(load);
  31749. }
  31750. }
  31751. return _this;
  31752. }
  31753. Object.defineProperty(Texture.prototype, "noMipmap", {
  31754. /**
  31755. * Are mip maps generated for this texture or not.
  31756. */
  31757. get: function () {
  31758. return this._noMipmap;
  31759. },
  31760. enumerable: true,
  31761. configurable: true
  31762. });
  31763. Object.defineProperty(Texture.prototype, "isBlocking", {
  31764. get: function () {
  31765. return this._isBlocking;
  31766. },
  31767. /**
  31768. * Is the texture preventing material to render while loading.
  31769. * If false, a default texture will be used instead of the loading one during the preparation step.
  31770. */
  31771. set: function (value) {
  31772. this._isBlocking = value;
  31773. },
  31774. enumerable: true,
  31775. configurable: true
  31776. });
  31777. Object.defineProperty(Texture.prototype, "samplingMode", {
  31778. /**
  31779. * Get the current sampling mode associated with the texture.
  31780. */
  31781. get: function () {
  31782. return this._samplingMode;
  31783. },
  31784. enumerable: true,
  31785. configurable: true
  31786. });
  31787. /**
  31788. * Update the url (and optional buffer) of this texture if url was null during construction.
  31789. * @param url the url of the texture
  31790. * @param buffer the buffer of the texture (defaults to null)
  31791. */
  31792. Texture.prototype.updateURL = function (url, buffer) {
  31793. if (buffer === void 0) { buffer = null; }
  31794. if (this.url) {
  31795. throw new Error("URL is already set");
  31796. }
  31797. this.url = url;
  31798. this._buffer = buffer;
  31799. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31800. this.delayLoad();
  31801. };
  31802. /**
  31803. * Finish the loading sequence of a texture flagged as delayed load.
  31804. * @hidden
  31805. */
  31806. Texture.prototype.delayLoad = function () {
  31807. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31808. return;
  31809. }
  31810. var scene = this.getScene();
  31811. if (!scene) {
  31812. return;
  31813. }
  31814. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31815. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31816. if (!this._texture) {
  31817. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31818. if (this._deleteBuffer) {
  31819. delete this._buffer;
  31820. }
  31821. }
  31822. else {
  31823. if (this._delayedOnLoad) {
  31824. if (this._texture.isReady) {
  31825. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31826. }
  31827. else {
  31828. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31829. }
  31830. }
  31831. }
  31832. this._delayedOnLoad = null;
  31833. this._delayedOnError = null;
  31834. };
  31835. /**
  31836. * Update the sampling mode of the texture.
  31837. * Default is Trilinear mode.
  31838. *
  31839. * | Value | Type | Description |
  31840. * | ----- | ------------------ | ----------- |
  31841. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31842. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31843. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31844. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31845. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31846. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31847. * | 7 | NEAREST_LINEAR | |
  31848. * | 8 | NEAREST_NEAREST | |
  31849. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31850. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31851. * | 11 | LINEAR_LINEAR | |
  31852. * | 12 | LINEAR_NEAREST | |
  31853. *
  31854. * > _mag_: magnification filter (close to the viewer)
  31855. * > _min_: minification filter (far from the viewer)
  31856. * > _mip_: filter used between mip map levels
  31857. *@param samplingMode Define the new sampling mode of the texture
  31858. */
  31859. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31860. if (!this._texture) {
  31861. return;
  31862. }
  31863. var scene = this.getScene();
  31864. if (!scene) {
  31865. return;
  31866. }
  31867. this._samplingMode = samplingMode;
  31868. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31869. };
  31870. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31871. x *= this.uScale;
  31872. y *= this.vScale;
  31873. x -= this.uRotationCenter * this.uScale;
  31874. y -= this.vRotationCenter * this.vScale;
  31875. z -= this.wRotationCenter;
  31876. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31877. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31878. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31879. t.z += this.wRotationCenter;
  31880. };
  31881. /**
  31882. * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
  31883. * @returns the transform matrix of the texture.
  31884. */
  31885. Texture.prototype.getTextureMatrix = function () {
  31886. var _this = this;
  31887. if (this.uOffset === this._cachedUOffset &&
  31888. this.vOffset === this._cachedVOffset &&
  31889. this.uScale === this._cachedUScale &&
  31890. this.vScale === this._cachedVScale &&
  31891. this.uAng === this._cachedUAng &&
  31892. this.vAng === this._cachedVAng &&
  31893. this.wAng === this._cachedWAng) {
  31894. return this._cachedTextureMatrix;
  31895. }
  31896. this._cachedUOffset = this.uOffset;
  31897. this._cachedVOffset = this.vOffset;
  31898. this._cachedUScale = this.uScale;
  31899. this._cachedVScale = this.vScale;
  31900. this._cachedUAng = this.uAng;
  31901. this._cachedVAng = this.vAng;
  31902. this._cachedWAng = this.wAng;
  31903. if (!this._cachedTextureMatrix) {
  31904. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31905. this._rowGenerationMatrix = new BABYLON.Matrix();
  31906. this._t0 = BABYLON.Vector3.Zero();
  31907. this._t1 = BABYLON.Vector3.Zero();
  31908. this._t2 = BABYLON.Vector3.Zero();
  31909. }
  31910. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31911. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31912. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31913. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31914. this._t1.subtractInPlace(this._t0);
  31915. this._t2.subtractInPlace(this._t0);
  31916. 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);
  31917. var scene = this.getScene();
  31918. if (!scene) {
  31919. return this._cachedTextureMatrix;
  31920. }
  31921. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31922. return mat.hasTexture(_this);
  31923. });
  31924. return this._cachedTextureMatrix;
  31925. };
  31926. /**
  31927. * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
  31928. * @returns The reflection texture transform
  31929. */
  31930. Texture.prototype.getReflectionTextureMatrix = function () {
  31931. var _this = this;
  31932. var scene = this.getScene();
  31933. if (!scene) {
  31934. return this._cachedTextureMatrix;
  31935. }
  31936. if (this.uOffset === this._cachedUOffset &&
  31937. this.vOffset === this._cachedVOffset &&
  31938. this.uScale === this._cachedUScale &&
  31939. this.vScale === this._cachedVScale &&
  31940. this.coordinatesMode === this._cachedCoordinatesMode) {
  31941. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31942. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31943. return this._cachedTextureMatrix;
  31944. }
  31945. }
  31946. else {
  31947. return this._cachedTextureMatrix;
  31948. }
  31949. }
  31950. if (!this._cachedTextureMatrix) {
  31951. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31952. }
  31953. if (!this._projectionModeMatrix) {
  31954. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31955. }
  31956. this._cachedUOffset = this.uOffset;
  31957. this._cachedVOffset = this.vOffset;
  31958. this._cachedUScale = this.uScale;
  31959. this._cachedVScale = this.vScale;
  31960. this._cachedCoordinatesMode = this.coordinatesMode;
  31961. switch (this.coordinatesMode) {
  31962. case Texture.PLANAR_MODE:
  31963. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31964. this._cachedTextureMatrix[0] = this.uScale;
  31965. this._cachedTextureMatrix[5] = this.vScale;
  31966. this._cachedTextureMatrix[12] = this.uOffset;
  31967. this._cachedTextureMatrix[13] = this.vOffset;
  31968. break;
  31969. case Texture.PROJECTION_MODE:
  31970. 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);
  31971. var projectionMatrix = scene.getProjectionMatrix();
  31972. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31973. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31974. break;
  31975. default:
  31976. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31977. break;
  31978. }
  31979. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31980. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31981. });
  31982. return this._cachedTextureMatrix;
  31983. };
  31984. /**
  31985. * Clones the texture.
  31986. * @returns the cloned texture
  31987. */
  31988. Texture.prototype.clone = function () {
  31989. var _this = this;
  31990. return BABYLON.SerializationHelper.Clone(function () {
  31991. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31992. }, this);
  31993. };
  31994. /**
  31995. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  31996. * @returns The JSON representation of the texture
  31997. */
  31998. Texture.prototype.serialize = function () {
  31999. var serializationObject = _super.prototype.serialize.call(this);
  32000. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  32001. serializationObject.base64String = this._buffer;
  32002. serializationObject.name = serializationObject.name.replace("data:", "");
  32003. }
  32004. serializationObject.invertY = this._invertY;
  32005. serializationObject.samplingMode = this.samplingMode;
  32006. return serializationObject;
  32007. };
  32008. /**
  32009. * Get the current class name of the texture usefull for serialization or dynamic coding.
  32010. * @returns "Texture"
  32011. */
  32012. Texture.prototype.getClassName = function () {
  32013. return "Texture";
  32014. };
  32015. /**
  32016. * Dispose the texture and release its associated resources.
  32017. */
  32018. Texture.prototype.dispose = function () {
  32019. _super.prototype.dispose.call(this);
  32020. this.onLoadObservable.clear();
  32021. this._delayedOnLoad = null;
  32022. this._delayedOnError = null;
  32023. };
  32024. /**
  32025. * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
  32026. * @param parsedTexture Define the JSON representation of the texture
  32027. * @param scene Define the scene the parsed texture should be instantiated in
  32028. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  32029. * @returns The parsed texture if successful
  32030. */
  32031. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  32032. if (parsedTexture.customType) {
  32033. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  32034. // Update Sampling Mode
  32035. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  32036. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  32037. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  32038. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  32039. }
  32040. }
  32041. return parsedCustomTexture;
  32042. }
  32043. if (parsedTexture.isCube) {
  32044. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  32045. }
  32046. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  32047. return null;
  32048. }
  32049. var texture = BABYLON.SerializationHelper.Parse(function () {
  32050. var generateMipMaps = true;
  32051. if (parsedTexture.noMipmap) {
  32052. generateMipMaps = false;
  32053. }
  32054. if (parsedTexture.mirrorPlane) {
  32055. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  32056. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  32057. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  32058. return mirrorTexture;
  32059. }
  32060. else if (parsedTexture.isRenderTarget) {
  32061. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  32062. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  32063. return renderTargetTexture;
  32064. }
  32065. else {
  32066. var texture;
  32067. if (parsedTexture.base64String) {
  32068. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  32069. }
  32070. else {
  32071. var url = rootUrl + parsedTexture.name;
  32072. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  32073. url = parsedTexture.url;
  32074. }
  32075. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  32076. }
  32077. return texture;
  32078. }
  32079. }, parsedTexture, scene);
  32080. // Update Sampling Mode
  32081. if (parsedTexture.samplingMode) {
  32082. var sampling = parsedTexture.samplingMode;
  32083. if (texture._samplingMode !== sampling) {
  32084. texture.updateSamplingMode(sampling);
  32085. }
  32086. }
  32087. // Animations
  32088. if (parsedTexture.animations) {
  32089. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  32090. var parsedAnimation = parsedTexture.animations[animationIndex];
  32091. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32092. }
  32093. }
  32094. return texture;
  32095. };
  32096. /**
  32097. * Creates a texture from its base 64 representation.
  32098. * @param data Define the base64 payload without the data: prefix
  32099. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32100. * @param scene Define the scene the texture should belong to
  32101. * @param noMipmap Forces the texture to not create mip map information if true
  32102. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32103. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32104. * @param onLoad define a callback triggered when the texture has been loaded
  32105. * @param onError define a callback triggered when an error occurred during the loading session
  32106. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32107. * @returns the created texture
  32108. */
  32109. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32110. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32111. if (onLoad === void 0) { onLoad = null; }
  32112. if (onError === void 0) { onError = null; }
  32113. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32114. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  32115. };
  32116. /**
  32117. * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
  32118. * @param data Define the base64 payload without the data: prefix
  32119. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32120. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  32121. * @param scene Define the scene the texture should belong to
  32122. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  32123. * @param noMipmap Forces the texture to not create mip map information if true
  32124. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32125. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32126. * @param onLoad define a callback triggered when the texture has been loaded
  32127. * @param onError define a callback triggered when an error occurred during the loading session
  32128. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32129. * @returns the created texture
  32130. */
  32131. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32132. if (deleteBuffer === void 0) { deleteBuffer = false; }
  32133. if (noMipmap === void 0) { noMipmap = false; }
  32134. if (invertY === void 0) { invertY = true; }
  32135. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32136. if (onLoad === void 0) { onLoad = null; }
  32137. if (onError === void 0) { onError = null; }
  32138. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32139. if (name.substr(0, 5) !== "data:") {
  32140. name = "data:" + name;
  32141. }
  32142. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  32143. };
  32144. /** nearest is mag = nearest and min = nearest and mip = linear */
  32145. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  32146. /** nearest is mag = nearest and min = nearest and mip = linear */
  32147. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  32148. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32149. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  32150. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32151. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  32152. /** Trilinear is mag = linear and min = linear and mip = linear */
  32153. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  32154. /** Trilinear is mag = linear and min = linear and mip = linear */
  32155. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  32156. /** mag = nearest and min = nearest and mip = nearest */
  32157. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  32158. /** mag = nearest and min = linear and mip = nearest */
  32159. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  32160. /** mag = nearest and min = linear and mip = linear */
  32161. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  32162. /** mag = nearest and min = linear and mip = none */
  32163. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  32164. /** mag = nearest and min = nearest and mip = none */
  32165. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  32166. /** mag = linear and min = nearest and mip = nearest */
  32167. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  32168. /** mag = linear and min = nearest and mip = linear */
  32169. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  32170. /** mag = linear and min = linear and mip = none */
  32171. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  32172. /** mag = linear and min = nearest and mip = none */
  32173. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  32174. /** Explicit coordinates mode */
  32175. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  32176. /** Spherical coordinates mode */
  32177. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  32178. /** Planar coordinates mode */
  32179. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  32180. /** Cubic coordinates mode */
  32181. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  32182. /** Projection coordinates mode */
  32183. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  32184. /** Inverse Cubic coordinates mode */
  32185. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  32186. /** Inverse Cubic coordinates mode */
  32187. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  32188. /** Equirectangular coordinates mode */
  32189. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  32190. /** Equirectangular Fixed coordinates mode */
  32191. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  32192. /** Equirectangular Fixed Mirrored coordinates mode */
  32193. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  32194. /** Texture is not repeating outside of 0..1 UVs */
  32195. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  32196. /** Texture is repeating outside of 0..1 UVs */
  32197. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  32198. /** Texture is repeating and mirrored */
  32199. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  32200. /**
  32201. * 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
  32202. */
  32203. Texture.UseSerializedUrlIfAny = false;
  32204. __decorate([
  32205. BABYLON.serialize()
  32206. ], Texture.prototype, "url", void 0);
  32207. __decorate([
  32208. BABYLON.serialize()
  32209. ], Texture.prototype, "uOffset", void 0);
  32210. __decorate([
  32211. BABYLON.serialize()
  32212. ], Texture.prototype, "vOffset", void 0);
  32213. __decorate([
  32214. BABYLON.serialize()
  32215. ], Texture.prototype, "uScale", void 0);
  32216. __decorate([
  32217. BABYLON.serialize()
  32218. ], Texture.prototype, "vScale", void 0);
  32219. __decorate([
  32220. BABYLON.serialize()
  32221. ], Texture.prototype, "uAng", void 0);
  32222. __decorate([
  32223. BABYLON.serialize()
  32224. ], Texture.prototype, "vAng", void 0);
  32225. __decorate([
  32226. BABYLON.serialize()
  32227. ], Texture.prototype, "wAng", void 0);
  32228. __decorate([
  32229. BABYLON.serialize()
  32230. ], Texture.prototype, "uRotationCenter", void 0);
  32231. __decorate([
  32232. BABYLON.serialize()
  32233. ], Texture.prototype, "vRotationCenter", void 0);
  32234. __decorate([
  32235. BABYLON.serialize()
  32236. ], Texture.prototype, "wRotationCenter", void 0);
  32237. __decorate([
  32238. BABYLON.serialize()
  32239. ], Texture.prototype, "isBlocking", null);
  32240. return Texture;
  32241. }(BABYLON.BaseTexture));
  32242. BABYLON.Texture = Texture;
  32243. })(BABYLON || (BABYLON = {}));
  32244. //# sourceMappingURL=babylon.texture.js.map
  32245. var BABYLON;
  32246. (function (BABYLON) {
  32247. /**
  32248. * @hidden
  32249. **/
  32250. var _CreationDataStorage = /** @class */ (function () {
  32251. function _CreationDataStorage() {
  32252. }
  32253. return _CreationDataStorage;
  32254. }());
  32255. BABYLON._CreationDataStorage = _CreationDataStorage;
  32256. /**
  32257. * @hidden
  32258. **/
  32259. var _InstanceDataStorage = /** @class */ (function () {
  32260. function _InstanceDataStorage() {
  32261. this.visibleInstances = {};
  32262. this.renderIdForInstances = new Array();
  32263. this.batchCache = new _InstancesBatch();
  32264. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  32265. }
  32266. return _InstanceDataStorage;
  32267. }());
  32268. /**
  32269. * @hidden
  32270. **/
  32271. var _InstancesBatch = /** @class */ (function () {
  32272. function _InstancesBatch() {
  32273. this.mustReturn = false;
  32274. this.visibleInstances = new Array();
  32275. this.renderSelf = new Array();
  32276. }
  32277. return _InstancesBatch;
  32278. }());
  32279. BABYLON._InstancesBatch = _InstancesBatch;
  32280. /**
  32281. * Class used to represent renderable models
  32282. */
  32283. var Mesh = /** @class */ (function (_super) {
  32284. __extends(Mesh, _super);
  32285. /**
  32286. * @constructor
  32287. * @param name The value used by scene.getMeshByName() to do a lookup.
  32288. * @param scene The scene to add this mesh to.
  32289. * @param parent The parent of this mesh, if it has one
  32290. * @param source An optional Mesh from which geometry is shared, cloned.
  32291. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  32292. * When false, achieved by calling a clone(), also passing False.
  32293. * This will make creation of children, recursive.
  32294. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  32295. */
  32296. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  32297. if (scene === void 0) { scene = null; }
  32298. if (parent === void 0) { parent = null; }
  32299. if (source === void 0) { source = null; }
  32300. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32301. var _this = _super.call(this, name, scene) || this;
  32302. // Members
  32303. /**
  32304. * Gets the delay loading state of the mesh (when delay loading is turned on)
  32305. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  32306. */
  32307. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32308. /**
  32309. * Gets the list of instances created from this mesh
  32310. * it is not supposed to be modified manually.
  32311. * Note also that the order of the InstancedMesh wihin the array is not significant and might change.
  32312. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32313. */
  32314. _this.instances = new Array();
  32315. _this._LODLevels = new Array();
  32316. /** @hidden */
  32317. _this._instanceDataStorage = new _InstanceDataStorage();
  32318. // Use by builder only to know what orientation were the mesh build in.
  32319. /** @hidden */
  32320. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  32321. /**
  32322. * Use this property to change the original side orientation defined at construction time
  32323. */
  32324. _this.overrideMaterialSideOrientation = null;
  32325. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  32326. // Will be used to save a source mesh reference, If any
  32327. _this._source = null;
  32328. scene = _this.getScene();
  32329. if (source) {
  32330. // Geometry
  32331. if (source._geometry) {
  32332. source._geometry.applyToMesh(_this);
  32333. }
  32334. // Deep copy
  32335. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  32336. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  32337. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  32338. ], ["_poseMatrix"]);
  32339. // Source mesh
  32340. _this._source = source;
  32341. if (scene.useClonedMeshhMap) {
  32342. if (!source.meshMap) {
  32343. source.meshMap = {};
  32344. }
  32345. source.meshMap[_this.uniqueId] = _this;
  32346. }
  32347. // Construction Params
  32348. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  32349. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  32350. _this._creationDataStorage = source._creationDataStorage;
  32351. // Animation ranges
  32352. if (_this._source._ranges) {
  32353. var ranges = _this._source._ranges;
  32354. for (var name in ranges) {
  32355. if (!ranges.hasOwnProperty(name)) {
  32356. continue;
  32357. }
  32358. if (!ranges[name]) {
  32359. continue;
  32360. }
  32361. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  32362. }
  32363. }
  32364. // Metadata
  32365. if (source.metadata && source.metadata.clone) {
  32366. _this.metadata = source.metadata.clone();
  32367. }
  32368. else {
  32369. _this.metadata = source.metadata;
  32370. }
  32371. // Tags
  32372. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  32373. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  32374. }
  32375. // Parent
  32376. _this.parent = source.parent;
  32377. // Pivot
  32378. _this.setPivotMatrix(source.getPivotMatrix());
  32379. _this.id = name + "." + source.id;
  32380. // Material
  32381. _this.material = source.material;
  32382. var index;
  32383. if (!doNotCloneChildren) {
  32384. // Children
  32385. var directDescendants = source.getDescendants(true);
  32386. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  32387. var child = directDescendants[index_1];
  32388. if (child.clone) {
  32389. child.clone(name + "." + child.name, _this);
  32390. }
  32391. }
  32392. }
  32393. // Physics clone
  32394. var physicsEngine = _this.getScene().getPhysicsEngine();
  32395. if (clonePhysicsImpostor && physicsEngine) {
  32396. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  32397. if (impostor) {
  32398. _this.physicsImpostor = impostor.clone(_this);
  32399. }
  32400. }
  32401. // Particles
  32402. for (index = 0; index < scene.particleSystems.length; index++) {
  32403. var system = scene.particleSystems[index];
  32404. if (system.emitter === source) {
  32405. system.clone(system.name, _this);
  32406. }
  32407. }
  32408. _this.refreshBoundingInfo();
  32409. _this.computeWorldMatrix(true);
  32410. }
  32411. // Parent
  32412. if (parent !== null) {
  32413. _this.parent = parent;
  32414. }
  32415. return _this;
  32416. }
  32417. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  32418. /**
  32419. * An event triggered before rendering the mesh
  32420. */
  32421. get: function () {
  32422. if (!this._onBeforeRenderObservable) {
  32423. this._onBeforeRenderObservable = new BABYLON.Observable();
  32424. }
  32425. return this._onBeforeRenderObservable;
  32426. },
  32427. enumerable: true,
  32428. configurable: true
  32429. });
  32430. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  32431. /**
  32432. * An event triggered after rendering the mesh
  32433. */
  32434. get: function () {
  32435. if (!this._onAfterRenderObservable) {
  32436. this._onAfterRenderObservable = new BABYLON.Observable();
  32437. }
  32438. return this._onAfterRenderObservable;
  32439. },
  32440. enumerable: true,
  32441. configurable: true
  32442. });
  32443. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  32444. /**
  32445. * An event triggered before drawing the mesh
  32446. */
  32447. get: function () {
  32448. if (!this._onBeforeDrawObservable) {
  32449. this._onBeforeDrawObservable = new BABYLON.Observable();
  32450. }
  32451. return this._onBeforeDrawObservable;
  32452. },
  32453. enumerable: true,
  32454. configurable: true
  32455. });
  32456. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  32457. /**
  32458. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  32459. */
  32460. set: function (callback) {
  32461. if (this._onBeforeDrawObserver) {
  32462. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  32463. }
  32464. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  32465. },
  32466. enumerable: true,
  32467. configurable: true
  32468. });
  32469. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  32470. /**
  32471. * Gets or sets the morph target manager
  32472. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  32473. */
  32474. get: function () {
  32475. return this._morphTargetManager;
  32476. },
  32477. set: function (value) {
  32478. if (this._morphTargetManager === value) {
  32479. return;
  32480. }
  32481. this._morphTargetManager = value;
  32482. this._syncGeometryWithMorphTargetManager();
  32483. },
  32484. enumerable: true,
  32485. configurable: true
  32486. });
  32487. Object.defineProperty(Mesh.prototype, "source", {
  32488. /**
  32489. * Gets the source mesh (the one used to clone this one from)
  32490. */
  32491. get: function () {
  32492. return this._source;
  32493. },
  32494. enumerable: true,
  32495. configurable: true
  32496. });
  32497. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  32498. /**
  32499. * Gets or sets a boolean indicating that this mesh does not use index buffer
  32500. */
  32501. get: function () {
  32502. return this._unIndexed;
  32503. },
  32504. set: function (value) {
  32505. if (this._unIndexed !== value) {
  32506. this._unIndexed = value;
  32507. this._markSubMeshesAsAttributesDirty();
  32508. }
  32509. },
  32510. enumerable: true,
  32511. configurable: true
  32512. });
  32513. // Methods
  32514. /**
  32515. * Gets the class name
  32516. * @returns the string "Mesh".
  32517. */
  32518. Mesh.prototype.getClassName = function () {
  32519. return "Mesh";
  32520. };
  32521. /**
  32522. * Returns a description of this mesh
  32523. * @param fullDetails define if full details about this mesh must be used
  32524. * @returns a descriptive string representing this mesh
  32525. */
  32526. Mesh.prototype.toString = function (fullDetails) {
  32527. var ret = _super.prototype.toString.call(this, fullDetails);
  32528. ret += ", n vertices: " + this.getTotalVertices();
  32529. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  32530. if (this.animations) {
  32531. for (var i = 0; i < this.animations.length; i++) {
  32532. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  32533. }
  32534. }
  32535. if (fullDetails) {
  32536. if (this._geometry) {
  32537. var ib = this.getIndices();
  32538. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32539. if (vb && ib) {
  32540. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  32541. }
  32542. }
  32543. else {
  32544. ret += ", flat shading: UNKNOWN";
  32545. }
  32546. }
  32547. return ret;
  32548. };
  32549. /** @hidden */
  32550. Mesh.prototype._unBindEffect = function () {
  32551. _super.prototype._unBindEffect.call(this);
  32552. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  32553. var instance = _a[_i];
  32554. instance._unBindEffect();
  32555. }
  32556. };
  32557. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  32558. /**
  32559. * Gets a boolean indicating if this mesh has LOD
  32560. */
  32561. get: function () {
  32562. return this._LODLevels.length > 0;
  32563. },
  32564. enumerable: true,
  32565. configurable: true
  32566. });
  32567. /**
  32568. * Gets the list of MeshLODLevel associated with the current mesh
  32569. * @returns an array of MeshLODLevel
  32570. */
  32571. Mesh.prototype.getLODLevels = function () {
  32572. return this._LODLevels;
  32573. };
  32574. Mesh.prototype._sortLODLevels = function () {
  32575. this._LODLevels.sort(function (a, b) {
  32576. if (a.distance < b.distance) {
  32577. return 1;
  32578. }
  32579. if (a.distance > b.distance) {
  32580. return -1;
  32581. }
  32582. return 0;
  32583. });
  32584. };
  32585. /**
  32586. * Add a mesh as LOD level triggered at the given distance.
  32587. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32588. * @param distance The distance from the center of the object to show this level
  32589. * @param mesh The mesh to be added as LOD level (can be null)
  32590. * @return This mesh (for chaining)
  32591. */
  32592. Mesh.prototype.addLODLevel = function (distance, mesh) {
  32593. if (mesh && mesh._masterMesh) {
  32594. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  32595. return this;
  32596. }
  32597. var level = new BABYLON.MeshLODLevel(distance, mesh);
  32598. this._LODLevels.push(level);
  32599. if (mesh) {
  32600. mesh._masterMesh = this;
  32601. }
  32602. this._sortLODLevels();
  32603. return this;
  32604. };
  32605. /**
  32606. * Returns the LOD level mesh at the passed distance or null if not found.
  32607. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32608. * @param distance The distance from the center of the object to show this level
  32609. * @returns a Mesh or `null`
  32610. */
  32611. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32612. for (var index = 0; index < this._LODLevels.length; index++) {
  32613. var level = this._LODLevels[index];
  32614. if (level.distance === distance) {
  32615. return level.mesh;
  32616. }
  32617. }
  32618. return null;
  32619. };
  32620. /**
  32621. * Remove a mesh from the LOD array
  32622. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32623. * @param mesh defines the mesh to be removed
  32624. * @return This mesh (for chaining)
  32625. */
  32626. Mesh.prototype.removeLODLevel = function (mesh) {
  32627. for (var index = 0; index < this._LODLevels.length; index++) {
  32628. if (this._LODLevels[index].mesh === mesh) {
  32629. this._LODLevels.splice(index, 1);
  32630. if (mesh) {
  32631. mesh._masterMesh = null;
  32632. }
  32633. }
  32634. }
  32635. this._sortLODLevels();
  32636. return this;
  32637. };
  32638. /**
  32639. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32640. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32641. * @param camera defines the camera to use to compute distance
  32642. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32643. * @return This mesh (for chaining)
  32644. */
  32645. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32646. if (!this._LODLevels || this._LODLevels.length === 0) {
  32647. return this;
  32648. }
  32649. var bSphere;
  32650. if (boundingSphere) {
  32651. bSphere = boundingSphere;
  32652. }
  32653. else {
  32654. var boundingInfo = this.getBoundingInfo();
  32655. bSphere = boundingInfo.boundingSphere;
  32656. }
  32657. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32658. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32659. if (this.onLODLevelSelection) {
  32660. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32661. }
  32662. return this;
  32663. }
  32664. for (var index = 0; index < this._LODLevels.length; index++) {
  32665. var level = this._LODLevels[index];
  32666. if (level.distance < distanceToCamera) {
  32667. if (level.mesh) {
  32668. level.mesh._preActivate();
  32669. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32670. }
  32671. if (this.onLODLevelSelection) {
  32672. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32673. }
  32674. return level.mesh;
  32675. }
  32676. }
  32677. if (this.onLODLevelSelection) {
  32678. this.onLODLevelSelection(distanceToCamera, this, this);
  32679. }
  32680. return this;
  32681. };
  32682. Object.defineProperty(Mesh.prototype, "geometry", {
  32683. /**
  32684. * Gets the mesh internal Geometry object
  32685. */
  32686. get: function () {
  32687. return this._geometry;
  32688. },
  32689. enumerable: true,
  32690. configurable: true
  32691. });
  32692. /**
  32693. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32694. * @returns the total number of vertices
  32695. */
  32696. Mesh.prototype.getTotalVertices = function () {
  32697. if (this._geometry === null || this._geometry === undefined) {
  32698. return 0;
  32699. }
  32700. return this._geometry.getTotalVertices();
  32701. };
  32702. /**
  32703. * Returns the content of an associated vertex buffer
  32704. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32705. * - BABYLON.VertexBuffer.PositionKind
  32706. * - BABYLON.VertexBuffer.UVKind
  32707. * - BABYLON.VertexBuffer.UV2Kind
  32708. * - BABYLON.VertexBuffer.UV3Kind
  32709. * - BABYLON.VertexBuffer.UV4Kind
  32710. * - BABYLON.VertexBuffer.UV5Kind
  32711. * - BABYLON.VertexBuffer.UV6Kind
  32712. * - BABYLON.VertexBuffer.ColorKind
  32713. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32714. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32715. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32716. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32717. * @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
  32718. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32719. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32720. */
  32721. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32722. if (!this._geometry) {
  32723. return null;
  32724. }
  32725. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32726. };
  32727. /**
  32728. * Returns the mesh VertexBuffer object from the requested `kind`
  32729. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32730. * - BABYLON.VertexBuffer.PositionKind
  32731. * - BABYLON.VertexBuffer.UVKind
  32732. * - BABYLON.VertexBuffer.UV2Kind
  32733. * - BABYLON.VertexBuffer.UV3Kind
  32734. * - BABYLON.VertexBuffer.UV4Kind
  32735. * - BABYLON.VertexBuffer.UV5Kind
  32736. * - BABYLON.VertexBuffer.UV6Kind
  32737. * - BABYLON.VertexBuffer.ColorKind
  32738. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32739. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32740. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32741. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32742. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32743. */
  32744. Mesh.prototype.getVertexBuffer = function (kind) {
  32745. if (!this._geometry) {
  32746. return null;
  32747. }
  32748. return this._geometry.getVertexBuffer(kind);
  32749. };
  32750. /**
  32751. * Tests if a specific vertex buffer is associated with this mesh
  32752. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32753. * - BABYLON.VertexBuffer.PositionKind
  32754. * - BABYLON.VertexBuffer.UVKind
  32755. * - BABYLON.VertexBuffer.UV2Kind
  32756. * - BABYLON.VertexBuffer.UV3Kind
  32757. * - BABYLON.VertexBuffer.UV4Kind
  32758. * - BABYLON.VertexBuffer.UV5Kind
  32759. * - BABYLON.VertexBuffer.UV6Kind
  32760. * - BABYLON.VertexBuffer.ColorKind
  32761. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32762. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32763. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32764. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32765. * @returns a boolean
  32766. */
  32767. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32768. if (!this._geometry) {
  32769. if (this._delayInfo) {
  32770. return this._delayInfo.indexOf(kind) !== -1;
  32771. }
  32772. return false;
  32773. }
  32774. return this._geometry.isVerticesDataPresent(kind);
  32775. };
  32776. /**
  32777. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32778. * @param kind defines which buffer to check (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 boolean
  32792. */
  32793. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32794. if (!this._geometry) {
  32795. if (this._delayInfo) {
  32796. return this._delayInfo.indexOf(kind) !== -1;
  32797. }
  32798. return false;
  32799. }
  32800. return this._geometry.isVertexBufferUpdatable(kind);
  32801. };
  32802. /**
  32803. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32804. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32805. * - BABYLON.VertexBuffer.PositionKind
  32806. * - BABYLON.VertexBuffer.UVKind
  32807. * - BABYLON.VertexBuffer.UV2Kind
  32808. * - BABYLON.VertexBuffer.UV3Kind
  32809. * - BABYLON.VertexBuffer.UV4Kind
  32810. * - BABYLON.VertexBuffer.UV5Kind
  32811. * - BABYLON.VertexBuffer.UV6Kind
  32812. * - BABYLON.VertexBuffer.ColorKind
  32813. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32814. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32815. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32816. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32817. * @returns an array of strings
  32818. */
  32819. Mesh.prototype.getVerticesDataKinds = function () {
  32820. if (!this._geometry) {
  32821. var result = new Array();
  32822. if (this._delayInfo) {
  32823. this._delayInfo.forEach(function (kind, index, array) {
  32824. result.push(kind);
  32825. });
  32826. }
  32827. return result;
  32828. }
  32829. return this._geometry.getVerticesDataKinds();
  32830. };
  32831. /**
  32832. * Returns a positive integer : the total number of indices in this mesh geometry.
  32833. * @returns the numner of indices or zero if the mesh has no geometry.
  32834. */
  32835. Mesh.prototype.getTotalIndices = function () {
  32836. if (!this._geometry) {
  32837. return 0;
  32838. }
  32839. return this._geometry.getTotalIndices();
  32840. };
  32841. /**
  32842. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32843. * @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.
  32844. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32845. * @returns the indices array or an empty array if the mesh has no geometry
  32846. */
  32847. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32848. if (!this._geometry) {
  32849. return [];
  32850. }
  32851. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32852. };
  32853. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32854. get: function () {
  32855. return this._masterMesh !== null && this._masterMesh !== undefined;
  32856. },
  32857. enumerable: true,
  32858. configurable: true
  32859. });
  32860. /**
  32861. * Determine if the current mesh is ready to be rendered
  32862. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32863. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32864. * @returns true if all associated assets are ready (material, textures, shaders)
  32865. */
  32866. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32867. if (completeCheck === void 0) { completeCheck = false; }
  32868. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32869. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32870. return false;
  32871. }
  32872. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32873. return false;
  32874. }
  32875. if (!this.subMeshes || this.subMeshes.length === 0) {
  32876. return true;
  32877. }
  32878. if (!completeCheck) {
  32879. return true;
  32880. }
  32881. var engine = this.getEngine();
  32882. var scene = this.getScene();
  32883. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32884. this.computeWorldMatrix();
  32885. var mat = this.material || scene.defaultMaterial;
  32886. if (mat) {
  32887. if (mat._storeEffectOnSubMeshes) {
  32888. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32889. var subMesh = _a[_i];
  32890. var effectiveMaterial = subMesh.getMaterial();
  32891. if (effectiveMaterial) {
  32892. if (effectiveMaterial._storeEffectOnSubMeshes) {
  32893. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32894. return false;
  32895. }
  32896. }
  32897. else {
  32898. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32899. return false;
  32900. }
  32901. }
  32902. }
  32903. }
  32904. }
  32905. else {
  32906. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32907. return false;
  32908. }
  32909. }
  32910. }
  32911. // Shadows
  32912. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32913. var light = _c[_b];
  32914. var generator = light.getShadowGenerator();
  32915. if (generator) {
  32916. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32917. var subMesh = _e[_d];
  32918. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32919. return false;
  32920. }
  32921. }
  32922. }
  32923. }
  32924. // LOD
  32925. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32926. var lod = _g[_f];
  32927. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32928. return false;
  32929. }
  32930. }
  32931. return true;
  32932. };
  32933. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32934. /**
  32935. * 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.
  32936. */
  32937. get: function () {
  32938. return this._areNormalsFrozen;
  32939. },
  32940. enumerable: true,
  32941. configurable: true
  32942. });
  32943. /**
  32944. * 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.
  32945. * @returns the current mesh
  32946. */
  32947. Mesh.prototype.freezeNormals = function () {
  32948. this._areNormalsFrozen = true;
  32949. return this;
  32950. };
  32951. /**
  32952. * 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
  32953. * @returns the current mesh
  32954. */
  32955. Mesh.prototype.unfreezeNormals = function () {
  32956. this._areNormalsFrozen = false;
  32957. return this;
  32958. };
  32959. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32960. /**
  32961. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32962. */
  32963. set: function (count) {
  32964. this._instanceDataStorage.overridenInstanceCount = count;
  32965. },
  32966. enumerable: true,
  32967. configurable: true
  32968. });
  32969. // Methods
  32970. /** @hidden */
  32971. Mesh.prototype._preActivate = function () {
  32972. var sceneRenderId = this.getScene().getRenderId();
  32973. if (this._preActivateId === sceneRenderId) {
  32974. return this;
  32975. }
  32976. this._preActivateId = sceneRenderId;
  32977. this._instanceDataStorage.visibleInstances = null;
  32978. return this;
  32979. };
  32980. /** @hidden */
  32981. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32982. if (this._instanceDataStorage.visibleInstances) {
  32983. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  32984. }
  32985. return this;
  32986. };
  32987. /** @hidden */
  32988. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32989. if (!this._instanceDataStorage.visibleInstances) {
  32990. this._instanceDataStorage.visibleInstances = {
  32991. defaultRenderId: renderId,
  32992. selfDefaultRenderId: this._renderId
  32993. };
  32994. }
  32995. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  32996. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  32997. }
  32998. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  32999. return this;
  33000. };
  33001. /**
  33002. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  33003. * This means the mesh underlying bounding box and sphere are recomputed.
  33004. * @returns the current mesh
  33005. */
  33006. Mesh.prototype.refreshBoundingInfo = function () {
  33007. return this._refreshBoundingInfo(false);
  33008. };
  33009. /** @hidden */
  33010. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  33011. if (this._boundingInfo && this._boundingInfo.isLocked) {
  33012. return this;
  33013. }
  33014. var data = this._getPositionData(applySkeleton);
  33015. if (data) {
  33016. var bias = this.geometry ? this.geometry.boundingBias : null;
  33017. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  33018. if (this._boundingInfo) {
  33019. this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
  33020. }
  33021. else {
  33022. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33023. }
  33024. }
  33025. if (this.subMeshes) {
  33026. for (var index = 0; index < this.subMeshes.length; index++) {
  33027. this.subMeshes[index].refreshBoundingInfo();
  33028. }
  33029. }
  33030. this._updateBoundingInfo();
  33031. return this;
  33032. };
  33033. Mesh.prototype._getPositionData = function (applySkeleton) {
  33034. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33035. if (data && applySkeleton && this.skeleton) {
  33036. data = BABYLON.Tools.Slice(data);
  33037. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33038. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33039. if (matricesWeightsData && matricesIndicesData) {
  33040. var needExtras = this.numBoneInfluencers > 4;
  33041. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33042. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33043. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  33044. var tempVector = BABYLON.Tmp.Vector3[0];
  33045. var finalMatrix = BABYLON.Tmp.Matrix[0];
  33046. var tempMatrix = BABYLON.Tmp.Matrix[1];
  33047. var matWeightIdx = 0;
  33048. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  33049. finalMatrix.reset();
  33050. var inf;
  33051. var weight;
  33052. for (inf = 0; inf < 4; inf++) {
  33053. weight = matricesWeightsData[matWeightIdx + inf];
  33054. if (weight > 0) {
  33055. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33056. finalMatrix.addToSelf(tempMatrix);
  33057. }
  33058. }
  33059. if (needExtras) {
  33060. for (inf = 0; inf < 4; inf++) {
  33061. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33062. if (weight > 0) {
  33063. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33064. finalMatrix.addToSelf(tempMatrix);
  33065. }
  33066. }
  33067. }
  33068. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  33069. tempVector.toArray(data, index);
  33070. }
  33071. }
  33072. }
  33073. return data;
  33074. };
  33075. /** @hidden */
  33076. Mesh.prototype._createGlobalSubMesh = function (force) {
  33077. var totalVertices = this.getTotalVertices();
  33078. if (!totalVertices || !this.getIndices()) {
  33079. return null;
  33080. }
  33081. // Check if we need to recreate the submeshes
  33082. if (this.subMeshes && this.subMeshes.length > 0) {
  33083. var ib = this.getIndices();
  33084. if (!ib) {
  33085. return null;
  33086. }
  33087. var totalIndices = ib.length;
  33088. var needToRecreate = false;
  33089. if (force) {
  33090. needToRecreate = true;
  33091. }
  33092. else {
  33093. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  33094. var submesh = _a[_i];
  33095. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  33096. needToRecreate = true;
  33097. break;
  33098. }
  33099. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  33100. needToRecreate = true;
  33101. break;
  33102. }
  33103. }
  33104. }
  33105. if (!needToRecreate) {
  33106. return this.subMeshes[0];
  33107. }
  33108. }
  33109. this.releaseSubMeshes();
  33110. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  33111. };
  33112. /**
  33113. * This function will subdivide the mesh into multiple submeshes
  33114. * @param count defines the expected number of submeshes
  33115. */
  33116. Mesh.prototype.subdivide = function (count) {
  33117. if (count < 1) {
  33118. return;
  33119. }
  33120. var totalIndices = this.getTotalIndices();
  33121. var subdivisionSize = (totalIndices / count) | 0;
  33122. var offset = 0;
  33123. // Ensure that subdivisionSize is a multiple of 3
  33124. while (subdivisionSize % 3 !== 0) {
  33125. subdivisionSize++;
  33126. }
  33127. this.releaseSubMeshes();
  33128. for (var index = 0; index < count; index++) {
  33129. if (offset >= totalIndices) {
  33130. break;
  33131. }
  33132. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  33133. offset += subdivisionSize;
  33134. }
  33135. this.synchronizeInstances();
  33136. };
  33137. /**
  33138. * Copy a FloatArray into a specific associated vertex buffer
  33139. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33140. * - BABYLON.VertexBuffer.PositionKind
  33141. * - BABYLON.VertexBuffer.UVKind
  33142. * - BABYLON.VertexBuffer.UV2Kind
  33143. * - BABYLON.VertexBuffer.UV3Kind
  33144. * - BABYLON.VertexBuffer.UV4Kind
  33145. * - BABYLON.VertexBuffer.UV5Kind
  33146. * - BABYLON.VertexBuffer.UV6Kind
  33147. * - BABYLON.VertexBuffer.ColorKind
  33148. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33149. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33150. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33151. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33152. * @param data defines the data source
  33153. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33154. * @param stride defines the data stride size (can be null)
  33155. * @returns the current mesh
  33156. */
  33157. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33158. if (updatable === void 0) { updatable = false; }
  33159. if (!this._geometry) {
  33160. var vertexData = new BABYLON.VertexData();
  33161. vertexData.set(data, kind);
  33162. var scene = this.getScene();
  33163. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33164. }
  33165. else {
  33166. this._geometry.setVerticesData(kind, data, updatable, stride);
  33167. }
  33168. return this;
  33169. };
  33170. /**
  33171. * Flags an associated vertex buffer as updatable
  33172. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  33173. * - BABYLON.VertexBuffer.PositionKind
  33174. * - BABYLON.VertexBuffer.UVKind
  33175. * - BABYLON.VertexBuffer.UV2Kind
  33176. * - BABYLON.VertexBuffer.UV3Kind
  33177. * - BABYLON.VertexBuffer.UV4Kind
  33178. * - BABYLON.VertexBuffer.UV5Kind
  33179. * - BABYLON.VertexBuffer.UV6Kind
  33180. * - BABYLON.VertexBuffer.ColorKind
  33181. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33182. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33183. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33184. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33185. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33186. */
  33187. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  33188. if (updatable === void 0) { updatable = true; }
  33189. var vb = this.getVertexBuffer(kind);
  33190. if (!vb || vb.isUpdatable() === updatable) {
  33191. return;
  33192. }
  33193. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  33194. };
  33195. /**
  33196. * Sets the mesh global Vertex Buffer
  33197. * @param buffer defines the buffer to use
  33198. * @returns the current mesh
  33199. */
  33200. Mesh.prototype.setVerticesBuffer = function (buffer) {
  33201. if (!this._geometry) {
  33202. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  33203. }
  33204. this._geometry.setVerticesBuffer(buffer);
  33205. return this;
  33206. };
  33207. /**
  33208. * Update a specific associated vertex buffer
  33209. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33210. * - BABYLON.VertexBuffer.PositionKind
  33211. * - BABYLON.VertexBuffer.UVKind
  33212. * - BABYLON.VertexBuffer.UV2Kind
  33213. * - BABYLON.VertexBuffer.UV3Kind
  33214. * - BABYLON.VertexBuffer.UV4Kind
  33215. * - BABYLON.VertexBuffer.UV5Kind
  33216. * - BABYLON.VertexBuffer.UV6Kind
  33217. * - BABYLON.VertexBuffer.ColorKind
  33218. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33219. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33220. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33221. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33222. * @param data defines the data source
  33223. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  33224. * @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)
  33225. * @returns the current mesh
  33226. */
  33227. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  33228. if (!this._geometry) {
  33229. return this;
  33230. }
  33231. if (!makeItUnique) {
  33232. this._geometry.updateVerticesData(kind, data, updateExtends);
  33233. }
  33234. else {
  33235. this.makeGeometryUnique();
  33236. this.updateVerticesData(kind, data, updateExtends, false);
  33237. }
  33238. return this;
  33239. };
  33240. /**
  33241. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  33242. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  33243. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  33244. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  33245. * @returns the current mesh
  33246. */
  33247. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  33248. if (computeNormals === void 0) { computeNormals = true; }
  33249. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33250. if (!positions) {
  33251. return this;
  33252. }
  33253. positionFunction(positions);
  33254. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  33255. if (computeNormals) {
  33256. var indices = this.getIndices();
  33257. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33258. if (!normals) {
  33259. return this;
  33260. }
  33261. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  33262. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  33263. }
  33264. return this;
  33265. };
  33266. /**
  33267. * Creates a un-shared specific occurence of the geometry for the mesh.
  33268. * @returns the current mesh
  33269. */
  33270. Mesh.prototype.makeGeometryUnique = function () {
  33271. if (!this._geometry) {
  33272. return this;
  33273. }
  33274. var oldGeometry = this._geometry;
  33275. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  33276. oldGeometry.releaseForMesh(this, true);
  33277. geometry.applyToMesh(this);
  33278. return this;
  33279. };
  33280. /**
  33281. * Set the index buffer of this mesh
  33282. * @param indices defines the source data
  33283. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  33284. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  33285. * @returns the current mesh
  33286. */
  33287. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  33288. if (totalVertices === void 0) { totalVertices = null; }
  33289. if (updatable === void 0) { updatable = false; }
  33290. if (!this._geometry) {
  33291. var vertexData = new BABYLON.VertexData();
  33292. vertexData.indices = indices;
  33293. var scene = this.getScene();
  33294. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33295. }
  33296. else {
  33297. this._geometry.setIndices(indices, totalVertices, updatable);
  33298. }
  33299. return this;
  33300. };
  33301. /**
  33302. * Update the current index buffer
  33303. * @param indices defines the source data
  33304. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  33305. * @returns the current mesh
  33306. */
  33307. Mesh.prototype.updateIndices = function (indices, offset) {
  33308. if (!this._geometry) {
  33309. return this;
  33310. }
  33311. this._geometry.updateIndices(indices, offset);
  33312. return this;
  33313. };
  33314. /**
  33315. * Invert the geometry to move from a right handed system to a left handed one.
  33316. * @returns the current mesh
  33317. */
  33318. Mesh.prototype.toLeftHanded = function () {
  33319. if (!this._geometry) {
  33320. return this;
  33321. }
  33322. this._geometry.toLeftHanded();
  33323. return this;
  33324. };
  33325. /** @hidden */
  33326. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  33327. if (!this._geometry) {
  33328. return this;
  33329. }
  33330. var engine = this.getScene().getEngine();
  33331. // Wireframe
  33332. var indexToBind;
  33333. if (this._unIndexed) {
  33334. indexToBind = null;
  33335. }
  33336. else {
  33337. switch (fillMode) {
  33338. case BABYLON.Material.PointFillMode:
  33339. indexToBind = null;
  33340. break;
  33341. case BABYLON.Material.WireFrameFillMode:
  33342. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  33343. break;
  33344. default:
  33345. case BABYLON.Material.TriangleFillMode:
  33346. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  33347. break;
  33348. }
  33349. }
  33350. // VBOs
  33351. this._geometry._bind(effect, indexToBind);
  33352. return this;
  33353. };
  33354. /** @hidden */
  33355. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  33356. if (alternate === void 0) { alternate = false; }
  33357. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33358. return this;
  33359. }
  33360. if (this._onBeforeDrawObservable) {
  33361. this._onBeforeDrawObservable.notifyObservers(this);
  33362. }
  33363. var scene = this.getScene();
  33364. var engine = scene.getEngine();
  33365. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  33366. // or triangles as points
  33367. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  33368. }
  33369. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  33370. // Triangles as wireframe
  33371. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  33372. }
  33373. else {
  33374. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  33375. }
  33376. if (scene._isAlternateRenderingEnabled && !alternate) {
  33377. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  33378. if (!effect || !scene.activeCamera) {
  33379. return this;
  33380. }
  33381. scene._switchToAlternateCameraConfiguration(true);
  33382. this._effectiveMaterial.bindView(effect);
  33383. this._effectiveMaterial.bindViewProjection(effect);
  33384. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  33385. this._draw(subMesh, fillMode, instancesCount, true);
  33386. engine.setViewport(scene.activeCamera.viewport);
  33387. scene._switchToAlternateCameraConfiguration(false);
  33388. this._effectiveMaterial.bindView(effect);
  33389. this._effectiveMaterial.bindViewProjection(effect);
  33390. }
  33391. return this;
  33392. };
  33393. /**
  33394. * Registers for this mesh a javascript function called just before the rendering process
  33395. * @param func defines the function to call before rendering this mesh
  33396. * @returns the current mesh
  33397. */
  33398. Mesh.prototype.registerBeforeRender = function (func) {
  33399. this.onBeforeRenderObservable.add(func);
  33400. return this;
  33401. };
  33402. /**
  33403. * Disposes a previously registered javascript function called before the rendering
  33404. * @param func defines the function to remove
  33405. * @returns the current mesh
  33406. */
  33407. Mesh.prototype.unregisterBeforeRender = function (func) {
  33408. this.onBeforeRenderObservable.removeCallback(func);
  33409. return this;
  33410. };
  33411. /**
  33412. * Registers for this mesh a javascript function called just after the rendering is complete
  33413. * @param func defines the function to call after rendering this mesh
  33414. * @returns the current mesh
  33415. */
  33416. Mesh.prototype.registerAfterRender = function (func) {
  33417. this.onAfterRenderObservable.add(func);
  33418. return this;
  33419. };
  33420. /**
  33421. * Disposes a previously registered javascript function called after the rendering.
  33422. * @param func defines the function to remove
  33423. * @returns the current mesh
  33424. */
  33425. Mesh.prototype.unregisterAfterRender = function (func) {
  33426. this.onAfterRenderObservable.removeCallback(func);
  33427. return this;
  33428. };
  33429. /** @hidden */
  33430. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  33431. var scene = this.getScene();
  33432. var batchCache = this._instanceDataStorage.batchCache;
  33433. batchCache.mustReturn = false;
  33434. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  33435. batchCache.visibleInstances[subMeshId] = null;
  33436. if (this._instanceDataStorage.visibleInstances) {
  33437. var visibleInstances = this._instanceDataStorage.visibleInstances;
  33438. var currentRenderId = scene.getRenderId();
  33439. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  33440. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  33441. var selfRenderId = this._renderId;
  33442. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  33443. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  33444. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  33445. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  33446. }
  33447. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  33448. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  33449. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  33450. batchCache.mustReturn = true;
  33451. return batchCache;
  33452. }
  33453. if (currentRenderId !== selfRenderId) {
  33454. batchCache.renderSelf[subMeshId] = false;
  33455. }
  33456. }
  33457. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  33458. }
  33459. return batchCache;
  33460. };
  33461. /** @hidden */
  33462. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  33463. var visibleInstances = batch.visibleInstances[subMesh._id];
  33464. if (!visibleInstances) {
  33465. return this;
  33466. }
  33467. var matricesCount = visibleInstances.length + 1;
  33468. var bufferSize = matricesCount * 16 * 4;
  33469. var instanceStorage = this._instanceDataStorage;
  33470. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  33471. var instancesBuffer = instanceStorage.instancesBuffer;
  33472. while (instanceStorage.instancesBufferSize < bufferSize) {
  33473. instanceStorage.instancesBufferSize *= 2;
  33474. }
  33475. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33476. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  33477. }
  33478. var offset = 0;
  33479. var instancesCount = 0;
  33480. var world = this.getWorldMatrix();
  33481. if (batch.renderSelf[subMesh._id]) {
  33482. world.copyToArray(instanceStorage.instancesData, offset);
  33483. offset += 16;
  33484. instancesCount++;
  33485. }
  33486. if (visibleInstances) {
  33487. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  33488. var instance = visibleInstances[instanceIndex];
  33489. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  33490. offset += 16;
  33491. instancesCount++;
  33492. }
  33493. }
  33494. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33495. if (instancesBuffer) {
  33496. instancesBuffer.dispose();
  33497. }
  33498. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  33499. instanceStorage.instancesBuffer = instancesBuffer;
  33500. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  33501. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  33502. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  33503. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  33504. }
  33505. else {
  33506. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  33507. }
  33508. this._bind(subMesh, effect, fillMode);
  33509. this._draw(subMesh, fillMode, instancesCount);
  33510. engine.unbindInstanceAttributes();
  33511. return this;
  33512. };
  33513. /** @hidden */
  33514. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  33515. var scene = this.getScene();
  33516. var engine = scene.getEngine();
  33517. if (hardwareInstancedRendering) {
  33518. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  33519. }
  33520. else {
  33521. if (batch.renderSelf[subMesh._id]) {
  33522. // Draw
  33523. if (onBeforeDraw) {
  33524. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  33525. }
  33526. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  33527. }
  33528. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  33529. if (visibleInstancesForSubMesh) {
  33530. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  33531. var instance = visibleInstancesForSubMesh[instanceIndex];
  33532. // World
  33533. var world = instance.getWorldMatrix();
  33534. if (onBeforeDraw) {
  33535. onBeforeDraw(true, world, effectiveMaterial);
  33536. }
  33537. // Draw
  33538. this._draw(subMesh, fillMode);
  33539. }
  33540. }
  33541. }
  33542. return this;
  33543. };
  33544. /**
  33545. * 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
  33546. * @param subMesh defines the subMesh to render
  33547. * @param enableAlphaMode defines if alpha mode can be changed
  33548. * @returns the current mesh
  33549. */
  33550. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  33551. if (this._checkOcclusionQuery()) {
  33552. return this;
  33553. }
  33554. var scene = this.getScene();
  33555. // Managing instances
  33556. var batch = this._getInstancesRenderList(subMesh._id);
  33557. if (batch.mustReturn) {
  33558. return this;
  33559. }
  33560. // Checking geometry state
  33561. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33562. return this;
  33563. }
  33564. if (this._onBeforeRenderObservable) {
  33565. this._onBeforeRenderObservable.notifyObservers(this);
  33566. }
  33567. var engine = scene.getEngine();
  33568. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33569. // Material
  33570. var material = subMesh.getMaterial();
  33571. if (!material) {
  33572. return this;
  33573. }
  33574. this._effectiveMaterial = material;
  33575. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33576. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33577. return this;
  33578. }
  33579. }
  33580. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33581. return this;
  33582. }
  33583. // Alpha mode
  33584. if (enableAlphaMode) {
  33585. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  33586. }
  33587. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  33588. var step = _a[_i];
  33589. step.action(this, subMesh, batch);
  33590. }
  33591. var effect;
  33592. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33593. effect = subMesh.effect;
  33594. }
  33595. else {
  33596. effect = this._effectiveMaterial.getEffect();
  33597. }
  33598. if (!effect) {
  33599. return this;
  33600. }
  33601. var sideOrientation = this.overrideMaterialSideOrientation;
  33602. if (sideOrientation == null) {
  33603. sideOrientation = this._effectiveMaterial.sideOrientation;
  33604. if (this._getWorldMatrixDeterminant() < 0) {
  33605. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  33606. }
  33607. }
  33608. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  33609. if (this._effectiveMaterial.forceDepthWrite) {
  33610. engine.setDepthWrite(true);
  33611. }
  33612. // Bind
  33613. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33614. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33615. this._bind(subMesh, effect, fillMode);
  33616. }
  33617. var world = this.getWorldMatrix();
  33618. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33619. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33620. }
  33621. else {
  33622. this._effectiveMaterial.bind(world, this);
  33623. }
  33624. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33625. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33626. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33627. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33628. }
  33629. // Draw
  33630. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33631. // Unbind
  33632. this._effectiveMaterial.unbind();
  33633. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33634. var step = _c[_b];
  33635. step.action(this, subMesh, batch);
  33636. }
  33637. if (this._onAfterRenderObservable) {
  33638. this._onAfterRenderObservable.notifyObservers(this);
  33639. }
  33640. return this;
  33641. };
  33642. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33643. if (isInstance && effectiveMaterial) {
  33644. effectiveMaterial.bindOnlyWorldMatrix(world);
  33645. }
  33646. };
  33647. /**
  33648. * Renormalize the mesh and patch it up if there are no weights
  33649. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  33650. * However in the case of zero weights then we set just a single influence to 1.
  33651. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  33652. */
  33653. Mesh.prototype.cleanMatrixWeights = function () {
  33654. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33655. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33656. this.normalizeSkinWeightsAndExtra();
  33657. }
  33658. else {
  33659. this.normalizeSkinFourWeights();
  33660. }
  33661. }
  33662. };
  33663. // faster 4 weight version.
  33664. Mesh.prototype.normalizeSkinFourWeights = function () {
  33665. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33666. var numWeights = matricesWeights.length;
  33667. for (var a = 0; a < numWeights; a += 4) {
  33668. // accumulate weights
  33669. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33670. // check for invalid weight and just set it to 1.
  33671. if (t === 0) {
  33672. matricesWeights[a] = 1;
  33673. }
  33674. else {
  33675. // renormalize so everything adds to 1 use reciprical
  33676. var recip = 1 / t;
  33677. matricesWeights[a] *= recip;
  33678. matricesWeights[a + 1] *= recip;
  33679. matricesWeights[a + 2] *= recip;
  33680. matricesWeights[a + 3] *= recip;
  33681. }
  33682. }
  33683. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33684. };
  33685. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  33686. Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
  33687. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33688. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33689. var numWeights = matricesWeights.length;
  33690. for (var a = 0; a < numWeights; a += 4) {
  33691. // accumulate weights
  33692. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33693. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  33694. // check for invalid weight and just set it to 1.
  33695. if (t === 0) {
  33696. matricesWeights[a] = 1;
  33697. }
  33698. else {
  33699. // renormalize so everything adds to 1 use reciprical
  33700. var recip = 1 / t;
  33701. matricesWeights[a] *= recip;
  33702. matricesWeights[a + 1] *= recip;
  33703. matricesWeights[a + 2] *= recip;
  33704. matricesWeights[a + 3] *= recip;
  33705. // same goes for extras
  33706. matricesWeightsExtra[a] *= recip;
  33707. matricesWeightsExtra[a + 1] *= recip;
  33708. matricesWeightsExtra[a + 2] *= recip;
  33709. matricesWeightsExtra[a + 3] *= recip;
  33710. }
  33711. }
  33712. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33713. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  33714. };
  33715. /**
  33716. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  33717. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  33718. * the user know there was an issue with importing the mesh
  33719. * @returns a validation object with skinned, valid and report string
  33720. */
  33721. Mesh.prototype.validateSkinning = function () {
  33722. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33723. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33724. if (matricesWeights === null || this.skeleton == null) {
  33725. return { skinned: false, valid: true, report: "not skinned" };
  33726. }
  33727. var numWeights = matricesWeights.length;
  33728. var numberNotSorted = 0;
  33729. var missingWeights = 0;
  33730. var maxUsedWeights = 0;
  33731. var numberNotNormalized = 0;
  33732. var numInfluences = matricesWeightsExtra === null ? 4 : 8;
  33733. var usedWeightCounts = new Array();
  33734. for (var a = 0; a <= numInfluences; a++) {
  33735. usedWeightCounts[a] = 0;
  33736. }
  33737. var toleranceEpsilon = 0.001;
  33738. for (var a = 0; a < numWeights; a += 4) {
  33739. var lastWeight = matricesWeights[a];
  33740. var t = lastWeight;
  33741. var usedWeights = t === 0 ? 0 : 1;
  33742. for (var b = 1; b < numInfluences; b++) {
  33743. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  33744. if (d > lastWeight) {
  33745. numberNotSorted++;
  33746. }
  33747. if (d !== 0) {
  33748. usedWeights++;
  33749. }
  33750. t += d;
  33751. lastWeight = d;
  33752. }
  33753. // count the buffer weights usage
  33754. usedWeightCounts[usedWeights]++;
  33755. // max influences
  33756. if (usedWeights > maxUsedWeights) {
  33757. maxUsedWeights = usedWeights;
  33758. }
  33759. // check for invalid weight and just set it to 1.
  33760. if (t === 0) {
  33761. missingWeights++;
  33762. }
  33763. else {
  33764. // renormalize so everything adds to 1 use reciprical
  33765. var recip = 1 / t;
  33766. var tolerance = 0;
  33767. for (b = 0; b < numInfluences; b++) {
  33768. if (b < 4) {
  33769. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  33770. }
  33771. else {
  33772. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  33773. }
  33774. }
  33775. // arbitary epsilon value for dicdating not normalized
  33776. if (tolerance > toleranceEpsilon) {
  33777. numberNotNormalized++;
  33778. }
  33779. }
  33780. }
  33781. // validate bone indices are in range of the skeleton
  33782. var numBones = this.skeleton.bones.length;
  33783. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33784. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33785. var numBadBoneIndices = 0;
  33786. for (var a = 0; a < numWeights; a++) {
  33787. for (var b = 0; b < numInfluences; b++) {
  33788. var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  33789. if (index >= numBones || index < 0) {
  33790. numBadBoneIndices++;
  33791. }
  33792. }
  33793. }
  33794. // log mesh stats
  33795. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  33796. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  33797. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  33798. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  33799. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  33800. };
  33801. /** @hidden */
  33802. Mesh.prototype._checkDelayState = function () {
  33803. var scene = this.getScene();
  33804. if (this._geometry) {
  33805. this._geometry.load(scene);
  33806. }
  33807. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33808. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33809. this._queueLoad(scene);
  33810. }
  33811. return this;
  33812. };
  33813. Mesh.prototype._queueLoad = function (scene) {
  33814. var _this = this;
  33815. scene._addPendingData(this);
  33816. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33817. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33818. if (data instanceof ArrayBuffer) {
  33819. _this._delayLoadingFunction(data, _this);
  33820. }
  33821. else {
  33822. _this._delayLoadingFunction(JSON.parse(data), _this);
  33823. }
  33824. _this.instances.forEach(function (instance) {
  33825. instance._syncSubMeshes();
  33826. });
  33827. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33828. scene._removePendingData(_this);
  33829. }, function () { }, scene.offlineProvider, getBinaryData);
  33830. return this;
  33831. };
  33832. /**
  33833. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33834. * A mesh is in the frustum if its bounding box intersects the frustum
  33835. * @param frustumPlanes defines the frustum to test
  33836. * @returns true if the mesh is in the frustum planes
  33837. */
  33838. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33839. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33840. return false;
  33841. }
  33842. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33843. return false;
  33844. }
  33845. this._checkDelayState();
  33846. return true;
  33847. };
  33848. /**
  33849. * Sets the mesh material by the material or multiMaterial `id` property
  33850. * @param id is a string identifying the material or the multiMaterial
  33851. * @returns the current mesh
  33852. */
  33853. Mesh.prototype.setMaterialByID = function (id) {
  33854. var materials = this.getScene().materials;
  33855. var index;
  33856. for (index = materials.length - 1; index > -1; index--) {
  33857. if (materials[index].id === id) {
  33858. this.material = materials[index];
  33859. return this;
  33860. }
  33861. }
  33862. // Multi
  33863. var multiMaterials = this.getScene().multiMaterials;
  33864. for (index = multiMaterials.length - 1; index > -1; index--) {
  33865. if (multiMaterials[index].id === id) {
  33866. this.material = multiMaterials[index];
  33867. return this;
  33868. }
  33869. }
  33870. return this;
  33871. };
  33872. /**
  33873. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33874. * @returns an array of IAnimatable
  33875. */
  33876. Mesh.prototype.getAnimatables = function () {
  33877. var results = new Array();
  33878. if (this.material) {
  33879. results.push(this.material);
  33880. }
  33881. if (this.skeleton) {
  33882. results.push(this.skeleton);
  33883. }
  33884. return results;
  33885. };
  33886. /**
  33887. * Modifies the mesh geometry according to the passed transformation matrix.
  33888. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33889. * The mesh normals are modified using the same transformation.
  33890. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33891. * @param transform defines the transform matrix to use
  33892. * @see http://doc.babylonjs.com/resources/baking_transformations
  33893. * @returns the current mesh
  33894. */
  33895. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33896. // Position
  33897. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33898. return this;
  33899. }
  33900. var submeshes = this.subMeshes.splice(0);
  33901. this._resetPointsArrayCache();
  33902. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33903. var temp = new Array();
  33904. var index;
  33905. for (index = 0; index < data.length; index += 3) {
  33906. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33907. }
  33908. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33909. // Normals
  33910. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33911. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33912. temp = [];
  33913. for (index = 0; index < data.length; index += 3) {
  33914. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33915. }
  33916. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33917. }
  33918. // flip faces?
  33919. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33920. this.flipFaces();
  33921. }
  33922. // Restore submeshes
  33923. this.releaseSubMeshes();
  33924. this.subMeshes = submeshes;
  33925. return this;
  33926. };
  33927. /**
  33928. * Modifies the mesh geometry according to its own current World Matrix.
  33929. * The mesh World Matrix is then reset.
  33930. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33931. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33932. * @see http://doc.babylonjs.com/resources/baking_transformations
  33933. * @returns the current mesh
  33934. */
  33935. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33936. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33937. this.scaling.copyFromFloats(1, 1, 1);
  33938. this.position.copyFromFloats(0, 0, 0);
  33939. this.rotation.copyFromFloats(0, 0, 0);
  33940. //only if quaternion is already set
  33941. if (this.rotationQuaternion) {
  33942. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33943. }
  33944. this._worldMatrix = BABYLON.Matrix.Identity();
  33945. return this;
  33946. };
  33947. Object.defineProperty(Mesh.prototype, "_positions", {
  33948. // Cache
  33949. /** @hidden */
  33950. get: function () {
  33951. if (this._geometry) {
  33952. return this._geometry._positions;
  33953. }
  33954. return null;
  33955. },
  33956. enumerable: true,
  33957. configurable: true
  33958. });
  33959. /** @hidden */
  33960. Mesh.prototype._resetPointsArrayCache = function () {
  33961. if (this._geometry) {
  33962. this._geometry._resetPointsArrayCache();
  33963. }
  33964. return this;
  33965. };
  33966. /** @hidden */
  33967. Mesh.prototype._generatePointsArray = function () {
  33968. if (this._geometry) {
  33969. return this._geometry._generatePointsArray();
  33970. }
  33971. return false;
  33972. };
  33973. /**
  33974. * Returns a new Mesh object generated from the current mesh properties.
  33975. * This method must not get confused with createInstance()
  33976. * @param name is a string, the name given to the new mesh
  33977. * @param newParent can be any Node object (default `null`)
  33978. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  33979. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  33980. * @returns a new mesh
  33981. */
  33982. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33983. if (name === void 0) { name = ""; }
  33984. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33985. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33986. };
  33987. /**
  33988. * Releases resources associated with this mesh.
  33989. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33990. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33991. */
  33992. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33993. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33994. this.morphTargetManager = null;
  33995. if (this._geometry) {
  33996. this._geometry.releaseForMesh(this, true);
  33997. }
  33998. if (this._onBeforeDrawObservable) {
  33999. this._onBeforeDrawObservable.clear();
  34000. }
  34001. if (this._onBeforeRenderObservable) {
  34002. this._onBeforeRenderObservable.clear();
  34003. }
  34004. if (this._onAfterRenderObservable) {
  34005. this._onAfterRenderObservable.clear();
  34006. }
  34007. // Sources
  34008. if (this._scene.useClonedMeshhMap) {
  34009. if (this.meshMap) {
  34010. for (var uniqueId in this.meshMap) {
  34011. var mesh = this.meshMap[uniqueId];
  34012. if (mesh) {
  34013. mesh._source = null;
  34014. this.meshMap[uniqueId] = undefined;
  34015. }
  34016. }
  34017. }
  34018. if (this._source && this._source.meshMap) {
  34019. this._source.meshMap[this.uniqueId] = undefined;
  34020. }
  34021. }
  34022. else {
  34023. var meshes = this.getScene().meshes;
  34024. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  34025. var abstractMesh = meshes_1[_i];
  34026. var mesh = abstractMesh;
  34027. if (mesh._source && mesh._source === this) {
  34028. mesh._source = null;
  34029. }
  34030. }
  34031. }
  34032. this._source = null;
  34033. // Instances
  34034. if (this._instanceDataStorage.instancesBuffer) {
  34035. this._instanceDataStorage.instancesBuffer.dispose();
  34036. this._instanceDataStorage.instancesBuffer = null;
  34037. }
  34038. while (this.instances.length) {
  34039. this.instances[0].dispose();
  34040. }
  34041. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  34042. };
  34043. /**
  34044. * Modifies the mesh geometry according to a displacement map.
  34045. * 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.
  34046. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  34047. * @param url is a string, the URL from the image file is to be downloaded.
  34048. * @param minHeight is the lower limit of the displacement.
  34049. * @param maxHeight is the upper limit of the displacement.
  34050. * @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.
  34051. * @param uvOffset is an optional vector2 used to offset UV.
  34052. * @param uvScale is an optional vector2 used to scale UV.
  34053. * @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.
  34054. * @returns the Mesh.
  34055. */
  34056. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  34057. var _this = this;
  34058. if (forceUpdate === void 0) { forceUpdate = false; }
  34059. var scene = this.getScene();
  34060. var onload = function (img) {
  34061. // Getting height map data
  34062. var canvas = document.createElement("canvas");
  34063. var context = canvas.getContext("2d");
  34064. var heightMapWidth = img.width;
  34065. var heightMapHeight = img.height;
  34066. canvas.width = heightMapWidth;
  34067. canvas.height = heightMapHeight;
  34068. context.drawImage(img, 0, 0);
  34069. // Create VertexData from map data
  34070. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  34071. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  34072. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  34073. //execute success callback, if set
  34074. if (onSuccess) {
  34075. onSuccess(_this);
  34076. }
  34077. };
  34078. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.offlineProvider);
  34079. return this;
  34080. };
  34081. /**
  34082. * Modifies the mesh geometry according to a displacementMap buffer.
  34083. * 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.
  34084. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  34085. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  34086. * @param heightMapWidth is the width of the buffer image.
  34087. * @param heightMapHeight is the height of the buffer image.
  34088. * @param minHeight is the lower limit of the displacement.
  34089. * @param maxHeight is the upper limit of the displacement.
  34090. * @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.
  34091. * @param uvOffset is an optional vector2 used to offset UV.
  34092. * @param uvScale is an optional vector2 used to scale UV.
  34093. * @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.
  34094. * @returns the Mesh.
  34095. */
  34096. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  34097. if (forceUpdate === void 0) { forceUpdate = false; }
  34098. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  34099. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  34100. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34101. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  34102. return this;
  34103. }
  34104. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  34105. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34106. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34107. var position = BABYLON.Vector3.Zero();
  34108. var normal = BABYLON.Vector3.Zero();
  34109. var uv = BABYLON.Vector2.Zero();
  34110. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  34111. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  34112. for (var index = 0; index < positions.length; index += 3) {
  34113. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  34114. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  34115. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  34116. // Compute height
  34117. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  34118. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  34119. var pos = (u + v * heightMapWidth) * 4;
  34120. var r = buffer[pos] / 255.0;
  34121. var g = buffer[pos + 1] / 255.0;
  34122. var b = buffer[pos + 2] / 255.0;
  34123. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  34124. normal.normalize();
  34125. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  34126. position = position.add(normal);
  34127. position.toArray(positions, index);
  34128. }
  34129. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  34130. if (forceUpdate) {
  34131. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34132. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34133. }
  34134. else {
  34135. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34136. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34137. }
  34138. return this;
  34139. };
  34140. /**
  34141. * Modify the mesh to get a flat shading rendering.
  34142. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  34143. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  34144. * @returns current mesh
  34145. */
  34146. Mesh.prototype.convertToFlatShadedMesh = function () {
  34147. var kinds = this.getVerticesDataKinds();
  34148. var vbs = {};
  34149. var data = {};
  34150. var newdata = {};
  34151. var updatableNormals = false;
  34152. var kindIndex;
  34153. var kind;
  34154. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34155. kind = kinds[kindIndex];
  34156. var vertexBuffer = this.getVertexBuffer(kind);
  34157. if (kind === BABYLON.VertexBuffer.NormalKind) {
  34158. updatableNormals = vertexBuffer.isUpdatable();
  34159. kinds.splice(kindIndex, 1);
  34160. kindIndex--;
  34161. continue;
  34162. }
  34163. vbs[kind] = vertexBuffer;
  34164. data[kind] = vbs[kind].getData();
  34165. newdata[kind] = [];
  34166. }
  34167. // Save previous submeshes
  34168. var previousSubmeshes = this.subMeshes.slice(0);
  34169. var indices = this.getIndices();
  34170. var totalIndices = this.getTotalIndices();
  34171. // Generating unique vertices per face
  34172. var index;
  34173. for (index = 0; index < totalIndices; index++) {
  34174. var vertexIndex = indices[index];
  34175. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34176. kind = kinds[kindIndex];
  34177. var stride = vbs[kind].getStrideSize();
  34178. for (var offset = 0; offset < stride; offset++) {
  34179. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34180. }
  34181. }
  34182. }
  34183. // Updating faces & normal
  34184. var normals = [];
  34185. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  34186. for (index = 0; index < totalIndices; index += 3) {
  34187. indices[index] = index;
  34188. indices[index + 1] = index + 1;
  34189. indices[index + 2] = index + 2;
  34190. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  34191. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  34192. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  34193. var p1p2 = p1.subtract(p2);
  34194. var p3p2 = p3.subtract(p2);
  34195. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  34196. // Store same normals for every vertex
  34197. for (var localIndex = 0; localIndex < 3; localIndex++) {
  34198. normals.push(normal.x);
  34199. normals.push(normal.y);
  34200. normals.push(normal.z);
  34201. }
  34202. }
  34203. this.setIndices(indices);
  34204. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  34205. // Updating vertex buffers
  34206. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34207. kind = kinds[kindIndex];
  34208. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34209. }
  34210. // Updating submeshes
  34211. this.releaseSubMeshes();
  34212. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34213. var previousOne = previousSubmeshes[submeshIndex];
  34214. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34215. }
  34216. this.synchronizeInstances();
  34217. return this;
  34218. };
  34219. /**
  34220. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  34221. * In other words, more vertices, no more indices and a single bigger VBO.
  34222. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  34223. * @returns current mesh
  34224. */
  34225. Mesh.prototype.convertToUnIndexedMesh = function () {
  34226. var kinds = this.getVerticesDataKinds();
  34227. var vbs = {};
  34228. var data = {};
  34229. var newdata = {};
  34230. var kindIndex;
  34231. var kind;
  34232. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34233. kind = kinds[kindIndex];
  34234. var vertexBuffer = this.getVertexBuffer(kind);
  34235. vbs[kind] = vertexBuffer;
  34236. data[kind] = vbs[kind].getData();
  34237. newdata[kind] = [];
  34238. }
  34239. // Save previous submeshes
  34240. var previousSubmeshes = this.subMeshes.slice(0);
  34241. var indices = this.getIndices();
  34242. var totalIndices = this.getTotalIndices();
  34243. // Generating unique vertices per face
  34244. var index;
  34245. for (index = 0; index < totalIndices; index++) {
  34246. var vertexIndex = indices[index];
  34247. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34248. kind = kinds[kindIndex];
  34249. var stride = vbs[kind].getStrideSize();
  34250. for (var offset = 0; offset < stride; offset++) {
  34251. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34252. }
  34253. }
  34254. }
  34255. // Updating indices
  34256. for (index = 0; index < totalIndices; index += 3) {
  34257. indices[index] = index;
  34258. indices[index + 1] = index + 1;
  34259. indices[index + 2] = index + 2;
  34260. }
  34261. this.setIndices(indices);
  34262. // Updating vertex buffers
  34263. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34264. kind = kinds[kindIndex];
  34265. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34266. }
  34267. // Updating submeshes
  34268. this.releaseSubMeshes();
  34269. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34270. var previousOne = previousSubmeshes[submeshIndex];
  34271. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34272. }
  34273. this._unIndexed = true;
  34274. this.synchronizeInstances();
  34275. return this;
  34276. };
  34277. /**
  34278. * Inverses facet orientations.
  34279. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  34280. * @param flipNormals will also inverts the normals
  34281. * @returns current mesh
  34282. */
  34283. Mesh.prototype.flipFaces = function (flipNormals) {
  34284. if (flipNormals === void 0) { flipNormals = false; }
  34285. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  34286. var i;
  34287. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  34288. for (i = 0; i < vertex_data.normals.length; i++) {
  34289. vertex_data.normals[i] *= -1;
  34290. }
  34291. }
  34292. if (vertex_data.indices) {
  34293. var temp;
  34294. for (i = 0; i < vertex_data.indices.length; i += 3) {
  34295. // reassign indices
  34296. temp = vertex_data.indices[i + 1];
  34297. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  34298. vertex_data.indices[i + 2] = temp;
  34299. }
  34300. }
  34301. vertex_data.applyToMesh(this);
  34302. return this;
  34303. };
  34304. // Instances
  34305. /**
  34306. * Creates a new InstancedMesh object from the mesh model.
  34307. * Warning : this method is not supported for Line mesh and LineSystem
  34308. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  34309. * @param name defines the name of the new instance
  34310. * @returns a new InstancedMesh
  34311. */
  34312. Mesh.prototype.createInstance = function (name) {
  34313. return new BABYLON.InstancedMesh(name, this);
  34314. };
  34315. /**
  34316. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  34317. * After this call, all the mesh instances have the same submeshes than the current mesh.
  34318. * @returns the current mesh
  34319. */
  34320. Mesh.prototype.synchronizeInstances = function () {
  34321. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  34322. var instance = this.instances[instanceIndex];
  34323. instance._syncSubMeshes();
  34324. }
  34325. return this;
  34326. };
  34327. /**
  34328. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  34329. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  34330. * This should be used together with the simplification to avoid disappearing triangles.
  34331. * @param successCallback an optional success callback to be called after the optimization finished.
  34332. * @returns the current mesh
  34333. */
  34334. Mesh.prototype.optimizeIndices = function (successCallback) {
  34335. var _this = this;
  34336. var indices = this.getIndices();
  34337. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34338. if (!positions || !indices) {
  34339. return this;
  34340. }
  34341. var vectorPositions = new Array();
  34342. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  34343. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  34344. }
  34345. var dupes = new Array();
  34346. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  34347. var realPos = vectorPositions.length - 1 - iteration;
  34348. var testedPosition = vectorPositions[realPos];
  34349. for (var j = 0; j < realPos; ++j) {
  34350. var againstPosition = vectorPositions[j];
  34351. if (testedPosition.equals(againstPosition)) {
  34352. dupes[realPos] = j;
  34353. break;
  34354. }
  34355. }
  34356. }, function () {
  34357. for (var i = 0; i < indices.length; ++i) {
  34358. indices[i] = dupes[indices[i]] || indices[i];
  34359. }
  34360. //indices are now reordered
  34361. var originalSubMeshes = _this.subMeshes.slice(0);
  34362. _this.setIndices(indices);
  34363. _this.subMeshes = originalSubMeshes;
  34364. if (successCallback) {
  34365. successCallback(_this);
  34366. }
  34367. });
  34368. return this;
  34369. };
  34370. /**
  34371. * Serialize current mesh
  34372. * @param serializationObject defines the object which will receive the serialization data
  34373. */
  34374. Mesh.prototype.serialize = function (serializationObject) {
  34375. serializationObject.name = this.name;
  34376. serializationObject.id = this.id;
  34377. serializationObject.type = this.getClassName();
  34378. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34379. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34380. }
  34381. serializationObject.position = this.position.asArray();
  34382. if (this.rotationQuaternion) {
  34383. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  34384. }
  34385. else if (this.rotation) {
  34386. serializationObject.rotation = this.rotation.asArray();
  34387. }
  34388. serializationObject.scaling = this.scaling.asArray();
  34389. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  34390. serializationObject.isEnabled = this.isEnabled(false);
  34391. serializationObject.isVisible = this.isVisible;
  34392. serializationObject.infiniteDistance = this.infiniteDistance;
  34393. serializationObject.pickable = this.isPickable;
  34394. serializationObject.receiveShadows = this.receiveShadows;
  34395. serializationObject.billboardMode = this.billboardMode;
  34396. serializationObject.visibility = this.visibility;
  34397. serializationObject.checkCollisions = this.checkCollisions;
  34398. serializationObject.isBlocker = this.isBlocker;
  34399. // Parent
  34400. if (this.parent) {
  34401. serializationObject.parentId = this.parent.id;
  34402. }
  34403. // Geometry
  34404. serializationObject.isUnIndexed = this.isUnIndexed;
  34405. var geometry = this._geometry;
  34406. if (geometry) {
  34407. var geometryId = geometry.id;
  34408. serializationObject.geometryId = geometryId;
  34409. // SubMeshes
  34410. serializationObject.subMeshes = [];
  34411. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  34412. var subMesh = this.subMeshes[subIndex];
  34413. serializationObject.subMeshes.push({
  34414. materialIndex: subMesh.materialIndex,
  34415. verticesStart: subMesh.verticesStart,
  34416. verticesCount: subMesh.verticesCount,
  34417. indexStart: subMesh.indexStart,
  34418. indexCount: subMesh.indexCount
  34419. });
  34420. }
  34421. }
  34422. // Material
  34423. if (this.material) {
  34424. serializationObject.materialId = this.material.id;
  34425. }
  34426. else {
  34427. this.material = null;
  34428. }
  34429. // Morph targets
  34430. if (this.morphTargetManager) {
  34431. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  34432. }
  34433. // Skeleton
  34434. if (this.skeleton) {
  34435. serializationObject.skeletonId = this.skeleton.id;
  34436. }
  34437. // Physics
  34438. //TODO implement correct serialization for physics impostors.
  34439. var impostor = this.getPhysicsImpostor();
  34440. if (impostor) {
  34441. serializationObject.physicsMass = impostor.getParam("mass");
  34442. serializationObject.physicsFriction = impostor.getParam("friction");
  34443. serializationObject.physicsRestitution = impostor.getParam("mass");
  34444. serializationObject.physicsImpostor = impostor.type;
  34445. }
  34446. // Metadata
  34447. if (this.metadata) {
  34448. serializationObject.metadata = this.metadata;
  34449. }
  34450. // Instances
  34451. serializationObject.instances = [];
  34452. for (var index = 0; index < this.instances.length; index++) {
  34453. var instance = this.instances[index];
  34454. if (instance.doNotSerialize) {
  34455. continue;
  34456. }
  34457. var serializationInstance = {
  34458. name: instance.name,
  34459. id: instance.id,
  34460. position: instance.position.asArray(),
  34461. scaling: instance.scaling.asArray()
  34462. };
  34463. if (instance.parent) {
  34464. serializationInstance.parentId = instance.parent.id;
  34465. }
  34466. if (instance.rotationQuaternion) {
  34467. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34468. }
  34469. else if (instance.rotation) {
  34470. serializationInstance.rotation = instance.rotation.asArray();
  34471. }
  34472. serializationObject.instances.push(serializationInstance);
  34473. // Animations
  34474. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34475. serializationInstance.ranges = instance.serializeAnimationRanges();
  34476. }
  34477. //
  34478. // Animations
  34479. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  34480. serializationObject.ranges = this.serializeAnimationRanges();
  34481. // Layer mask
  34482. serializationObject.layerMask = this.layerMask;
  34483. // Alpha
  34484. serializationObject.alphaIndex = this.alphaIndex;
  34485. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  34486. // Overlay
  34487. serializationObject.overlayAlpha = this.overlayAlpha;
  34488. serializationObject.overlayColor = this.overlayColor.asArray();
  34489. serializationObject.renderOverlay = this.renderOverlay;
  34490. // Fog
  34491. serializationObject.applyFog = this.applyFog;
  34492. // Action Manager
  34493. if (this.actionManager) {
  34494. serializationObject.actions = this.actionManager.serialize(this.name);
  34495. }
  34496. };
  34497. /** @hidden */
  34498. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  34499. if (!this.geometry) {
  34500. return;
  34501. }
  34502. this._markSubMeshesAsAttributesDirty();
  34503. var morphTargetManager = this._morphTargetManager;
  34504. if (morphTargetManager && morphTargetManager.vertexCount) {
  34505. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  34506. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  34507. this.morphTargetManager = null;
  34508. return;
  34509. }
  34510. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  34511. var morphTarget = morphTargetManager.getActiveTarget(index);
  34512. var positions = morphTarget.getPositions();
  34513. if (!positions) {
  34514. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  34515. return;
  34516. }
  34517. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  34518. var normals = morphTarget.getNormals();
  34519. if (normals) {
  34520. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  34521. }
  34522. var tangents = morphTarget.getTangents();
  34523. if (tangents) {
  34524. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  34525. }
  34526. }
  34527. }
  34528. else {
  34529. var index = 0;
  34530. // Positions
  34531. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  34532. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  34533. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  34534. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  34535. }
  34536. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  34537. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  34538. }
  34539. index++;
  34540. }
  34541. }
  34542. };
  34543. // Statics
  34544. /**
  34545. * Returns a new Mesh object parsed from the source provided.
  34546. * @param parsedMesh is the source
  34547. * @param scene defines the hosting scene
  34548. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  34549. * @returns a new Mesh
  34550. */
  34551. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  34552. var mesh;
  34553. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  34554. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  34555. }
  34556. else {
  34557. mesh = new Mesh(parsedMesh.name, scene);
  34558. }
  34559. mesh.id = parsedMesh.id;
  34560. if (BABYLON.Tags) {
  34561. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  34562. }
  34563. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  34564. if (parsedMesh.metadata !== undefined) {
  34565. mesh.metadata = parsedMesh.metadata;
  34566. }
  34567. if (parsedMesh.rotationQuaternion) {
  34568. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  34569. }
  34570. else if (parsedMesh.rotation) {
  34571. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  34572. }
  34573. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  34574. if (parsedMesh.localMatrix) {
  34575. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  34576. }
  34577. else if (parsedMesh.pivotMatrix) {
  34578. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  34579. }
  34580. mesh.setEnabled(parsedMesh.isEnabled);
  34581. mesh.isVisible = parsedMesh.isVisible;
  34582. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  34583. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  34584. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  34585. if (parsedMesh.applyFog !== undefined) {
  34586. mesh.applyFog = parsedMesh.applyFog;
  34587. }
  34588. if (parsedMesh.pickable !== undefined) {
  34589. mesh.isPickable = parsedMesh.pickable;
  34590. }
  34591. if (parsedMesh.alphaIndex !== undefined) {
  34592. mesh.alphaIndex = parsedMesh.alphaIndex;
  34593. }
  34594. mesh.receiveShadows = parsedMesh.receiveShadows;
  34595. mesh.billboardMode = parsedMesh.billboardMode;
  34596. if (parsedMesh.visibility !== undefined) {
  34597. mesh.visibility = parsedMesh.visibility;
  34598. }
  34599. mesh.checkCollisions = parsedMesh.checkCollisions;
  34600. if (parsedMesh.isBlocker !== undefined) {
  34601. mesh.isBlocker = parsedMesh.isBlocker;
  34602. }
  34603. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  34604. // freezeWorldMatrix
  34605. if (parsedMesh.freezeWorldMatrix) {
  34606. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  34607. }
  34608. // Parent
  34609. if (parsedMesh.parentId) {
  34610. mesh._waitingParentId = parsedMesh.parentId;
  34611. }
  34612. // Actions
  34613. if (parsedMesh.actions !== undefined) {
  34614. mesh._waitingActions = parsedMesh.actions;
  34615. }
  34616. // Overlay
  34617. if (parsedMesh.overlayAlpha !== undefined) {
  34618. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  34619. }
  34620. if (parsedMesh.overlayColor !== undefined) {
  34621. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  34622. }
  34623. if (parsedMesh.renderOverlay !== undefined) {
  34624. mesh.renderOverlay = parsedMesh.renderOverlay;
  34625. }
  34626. // Geometry
  34627. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  34628. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  34629. if (parsedMesh.delayLoadingFile) {
  34630. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34631. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  34632. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  34633. if (parsedMesh._binaryInfo) {
  34634. mesh._binaryInfo = parsedMesh._binaryInfo;
  34635. }
  34636. mesh._delayInfo = [];
  34637. if (parsedMesh.hasUVs) {
  34638. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34639. }
  34640. if (parsedMesh.hasUVs2) {
  34641. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34642. }
  34643. if (parsedMesh.hasUVs3) {
  34644. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34645. }
  34646. if (parsedMesh.hasUVs4) {
  34647. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34648. }
  34649. if (parsedMesh.hasUVs5) {
  34650. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34651. }
  34652. if (parsedMesh.hasUVs6) {
  34653. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34654. }
  34655. if (parsedMesh.hasColors) {
  34656. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34657. }
  34658. if (parsedMesh.hasMatricesIndices) {
  34659. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34660. }
  34661. if (parsedMesh.hasMatricesWeights) {
  34662. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34663. }
  34664. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  34665. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  34666. mesh._checkDelayState();
  34667. }
  34668. }
  34669. else {
  34670. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  34671. }
  34672. // Material
  34673. if (parsedMesh.materialId) {
  34674. mesh.setMaterialByID(parsedMesh.materialId);
  34675. }
  34676. else {
  34677. mesh.material = null;
  34678. }
  34679. // Morph targets
  34680. if (parsedMesh.morphTargetManagerId > -1) {
  34681. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  34682. }
  34683. // Skeleton
  34684. if (parsedMesh.skeletonId > -1) {
  34685. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  34686. if (parsedMesh.numBoneInfluencers) {
  34687. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  34688. }
  34689. }
  34690. // Animations
  34691. if (parsedMesh.animations) {
  34692. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  34693. var parsedAnimation = parsedMesh.animations[animationIndex];
  34694. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34695. }
  34696. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  34697. }
  34698. if (parsedMesh.autoAnimate) {
  34699. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  34700. }
  34701. // Layer Mask
  34702. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  34703. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  34704. }
  34705. else {
  34706. mesh.layerMask = 0x0FFFFFFF;
  34707. }
  34708. // Physics
  34709. if (parsedMesh.physicsImpostor) {
  34710. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34711. mass: parsedMesh.physicsMass,
  34712. friction: parsedMesh.physicsFriction,
  34713. restitution: parsedMesh.physicsRestitution
  34714. }, scene);
  34715. }
  34716. // Instances
  34717. if (parsedMesh.instances) {
  34718. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34719. var parsedInstance = parsedMesh.instances[index];
  34720. var instance = mesh.createInstance(parsedInstance.name);
  34721. if (parsedInstance.id) {
  34722. instance.id = parsedInstance.id;
  34723. }
  34724. if (BABYLON.Tags) {
  34725. if (parsedInstance.tags) {
  34726. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34727. }
  34728. else {
  34729. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34730. }
  34731. }
  34732. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34733. if (parsedInstance.parentId) {
  34734. instance._waitingParentId = parsedInstance.parentId;
  34735. }
  34736. if (parsedInstance.rotationQuaternion) {
  34737. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34738. }
  34739. else if (parsedInstance.rotation) {
  34740. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34741. }
  34742. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34743. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34744. instance.checkCollisions = parsedInstance.checkCollisions;
  34745. }
  34746. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34747. instance.isPickable = parsedInstance.pickable;
  34748. }
  34749. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34750. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34751. }
  34752. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34753. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34754. }
  34755. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34756. instance.alphaIndex = parsedInstance.alphaIndex;
  34757. }
  34758. // Physics
  34759. if (parsedInstance.physicsImpostor) {
  34760. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34761. mass: parsedInstance.physicsMass,
  34762. friction: parsedInstance.physicsFriction,
  34763. restitution: parsedInstance.physicsRestitution
  34764. }, scene);
  34765. }
  34766. // Animation
  34767. if (parsedInstance.animations) {
  34768. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34769. parsedAnimation = parsedInstance.animations[animationIndex];
  34770. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34771. }
  34772. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34773. if (parsedInstance.autoAnimate) {
  34774. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34775. }
  34776. }
  34777. }
  34778. }
  34779. return mesh;
  34780. };
  34781. /**
  34782. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34783. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34784. * @param name defines the name of the mesh to create
  34785. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34786. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34787. * @param closePath creates a seam between the first and the last points of each path of the path array
  34788. * @param offset is taken in account only if the `pathArray` is containing a single path
  34789. * @param scene defines the hosting scene
  34790. * @param updatable defines if the mesh must be flagged as updatable
  34791. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34792. * @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)
  34793. * @returns a new Mesh
  34794. */
  34795. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34796. if (closeArray === void 0) { closeArray = false; }
  34797. if (updatable === void 0) { updatable = false; }
  34798. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34799. pathArray: pathArray,
  34800. closeArray: closeArray,
  34801. closePath: closePath,
  34802. offset: offset,
  34803. updatable: updatable,
  34804. sideOrientation: sideOrientation,
  34805. instance: instance
  34806. }, scene);
  34807. };
  34808. /**
  34809. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34810. * @param name defines the name of the mesh to create
  34811. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34812. * @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
  34813. * @param scene defines the hosting scene
  34814. * @param updatable defines if the mesh must be flagged as updatable
  34815. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34816. * @returns a new Mesh
  34817. */
  34818. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34819. if (scene === void 0) { scene = null; }
  34820. var options = {
  34821. radius: radius,
  34822. tessellation: tessellation,
  34823. sideOrientation: sideOrientation,
  34824. updatable: updatable
  34825. };
  34826. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34827. };
  34828. /**
  34829. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34830. * @param name defines the name of the mesh to create
  34831. * @param size sets the size (float) of each box side (default 1)
  34832. * @param scene defines the hosting scene
  34833. * @param updatable defines if the mesh must be flagged as updatable
  34834. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34835. * @returns a new Mesh
  34836. */
  34837. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34838. if (scene === void 0) { scene = null; }
  34839. var options = {
  34840. size: size,
  34841. sideOrientation: sideOrientation,
  34842. updatable: updatable
  34843. };
  34844. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34845. };
  34846. /**
  34847. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34848. * @param name defines the name of the mesh to create
  34849. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34850. * @param diameter sets the diameter size (float) of the sphere (default 1)
  34851. * @param scene defines the hosting scene
  34852. * @param updatable defines if the mesh must be flagged as updatable
  34853. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34854. * @returns a new Mesh
  34855. */
  34856. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  34857. var options = {
  34858. segments: segments,
  34859. diameterX: diameter,
  34860. diameterY: diameter,
  34861. diameterZ: diameter,
  34862. sideOrientation: sideOrientation,
  34863. updatable: updatable
  34864. };
  34865. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  34866. };
  34867. /**
  34868. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  34869. * @param name defines the name of the mesh to create
  34870. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  34871. * @param diameterTop set the top cap diameter (floats, default 1)
  34872. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  34873. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  34874. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  34875. * @param scene defines the hosting scene
  34876. * @param updatable defines if the mesh must be flagged as updatable
  34877. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34878. * @returns a new Mesh
  34879. */
  34880. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  34881. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  34882. if (scene !== undefined) {
  34883. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  34884. updatable = scene;
  34885. }
  34886. scene = subdivisions;
  34887. subdivisions = 1;
  34888. }
  34889. var options = {
  34890. height: height,
  34891. diameterTop: diameterTop,
  34892. diameterBottom: diameterBottom,
  34893. tessellation: tessellation,
  34894. subdivisions: subdivisions,
  34895. sideOrientation: sideOrientation,
  34896. updatable: updatable
  34897. };
  34898. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34899. };
  34900. // Torus (Code from SharpDX.org)
  34901. /**
  34902. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34903. * @param name defines the name of the mesh to create
  34904. * @param diameter sets the diameter size (float) of the torus (default 1)
  34905. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34906. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34907. * @param scene defines the hosting scene
  34908. * @param updatable defines if the mesh must be flagged as updatable
  34909. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34910. * @returns a new Mesh
  34911. */
  34912. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34913. var options = {
  34914. diameter: diameter,
  34915. thickness: thickness,
  34916. tessellation: tessellation,
  34917. sideOrientation: sideOrientation,
  34918. updatable: updatable
  34919. };
  34920. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34921. };
  34922. /**
  34923. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  34924. * @param name defines the name of the mesh to create
  34925. * @param radius sets the global radius size (float) of the torus knot (default 2)
  34926. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  34927. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34928. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34929. * @param p the number of windings on X axis (positive integers, default 2)
  34930. * @param q the number of windings on Y axis (positive integers, default 3)
  34931. * @param scene defines the hosting scene
  34932. * @param updatable defines if the mesh must be flagged as updatable
  34933. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34934. * @returns a new Mesh
  34935. */
  34936. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34937. var options = {
  34938. radius: radius,
  34939. tube: tube,
  34940. radialSegments: radialSegments,
  34941. tubularSegments: tubularSegments,
  34942. p: p,
  34943. q: q,
  34944. sideOrientation: sideOrientation,
  34945. updatable: updatable
  34946. };
  34947. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34948. };
  34949. /**
  34950. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  34951. * @param name defines the name of the mesh to create
  34952. * @param points is an array successive Vector3
  34953. * @param scene defines the hosting scene
  34954. * @param updatable defines if the mesh must be flagged as updatable
  34955. * @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).
  34956. * @returns a new Mesh
  34957. */
  34958. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34959. if (scene === void 0) { scene = null; }
  34960. if (updatable === void 0) { updatable = false; }
  34961. if (instance === void 0) { instance = null; }
  34962. var options = {
  34963. points: points,
  34964. updatable: updatable,
  34965. instance: instance
  34966. };
  34967. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34968. };
  34969. /**
  34970. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  34971. * @param name defines the name of the mesh to create
  34972. * @param points is an array successive Vector3
  34973. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  34974. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  34975. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  34976. * @param scene defines the hosting scene
  34977. * @param updatable defines if the mesh must be flagged as updatable
  34978. * @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)
  34979. * @returns a new Mesh
  34980. */
  34981. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34982. if (scene === void 0) { scene = null; }
  34983. var options = {
  34984. points: points,
  34985. dashSize: dashSize,
  34986. gapSize: gapSize,
  34987. dashNb: dashNb,
  34988. updatable: updatable,
  34989. instance: instance
  34990. };
  34991. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34992. };
  34993. /**
  34994. * Creates a polygon mesh.
  34995. * Please consider using the same method from the MeshBuilder class instead.
  34996. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34997. * 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.
  34998. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34999. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  35000. * Remember you can only change the shape positions, not their number when updating a polygon.
  35001. */
  35002. /**
  35003. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  35004. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  35005. * @param name defines the name of the mesh to create
  35006. * @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
  35007. * @param scene defines the hosting scene
  35008. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  35009. * @param updatable defines if the mesh must be flagged as updatable
  35010. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35011. * @returns a new Mesh
  35012. */
  35013. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  35014. var options = {
  35015. shape: shape,
  35016. holes: holes,
  35017. updatable: updatable,
  35018. sideOrientation: sideOrientation
  35019. };
  35020. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  35021. };
  35022. /**
  35023. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  35024. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  35025. * @param name defines the name of the mesh to create
  35026. * @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
  35027. * @param depth defines the height of extrusion
  35028. * @param scene defines the hosting scene
  35029. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  35030. * @param updatable defines if the mesh must be flagged as updatable
  35031. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35032. * @returns a new Mesh
  35033. */
  35034. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  35035. var options = {
  35036. shape: shape,
  35037. holes: holes,
  35038. depth: depth,
  35039. updatable: updatable,
  35040. sideOrientation: sideOrientation
  35041. };
  35042. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  35043. };
  35044. /**
  35045. * Creates an extruded shape mesh.
  35046. * 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
  35047. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35048. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  35049. * @param name defines the name of the mesh to create
  35050. * @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
  35051. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  35052. * @param scale is the value to scale the shape
  35053. * @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
  35054. * @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
  35055. * @param scene defines the hosting scene
  35056. * @param updatable defines if the mesh must be flagged as updatable
  35057. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35058. * @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)
  35059. * @returns a new Mesh
  35060. */
  35061. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  35062. if (scene === void 0) { scene = null; }
  35063. var options = {
  35064. shape: shape,
  35065. path: path,
  35066. scale: scale,
  35067. rotation: rotation,
  35068. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  35069. sideOrientation: sideOrientation,
  35070. instance: instance,
  35071. updatable: updatable
  35072. };
  35073. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  35074. };
  35075. /**
  35076. * Creates an custom extruded shape mesh.
  35077. * The custom extrusion is a parametric shape.
  35078. * It has no predefined shape. Its final shape will depend on the input parameters.
  35079. * Please consider using the same method from the MeshBuilder class instead
  35080. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  35081. * @param name defines the name of the mesh to create
  35082. * @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
  35083. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  35084. * @param scaleFunction is a custom Javascript function called on each path point
  35085. * @param rotationFunction is a custom Javascript function called on each path point
  35086. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  35087. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  35088. * @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
  35089. * @param scene defines the hosting scene
  35090. * @param updatable defines if the mesh must be flagged as updatable
  35091. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35092. * @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)
  35093. * @returns a new Mesh
  35094. */
  35095. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  35096. var options = {
  35097. shape: shape,
  35098. path: path,
  35099. scaleFunction: scaleFunction,
  35100. rotationFunction: rotationFunction,
  35101. ribbonCloseArray: ribbonCloseArray,
  35102. ribbonClosePath: ribbonClosePath,
  35103. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  35104. sideOrientation: sideOrientation,
  35105. instance: instance,
  35106. updatable: updatable
  35107. };
  35108. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  35109. };
  35110. /**
  35111. * Creates lathe mesh.
  35112. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  35113. * Please consider using the same method from the MeshBuilder class instead
  35114. * @param name defines the name of the mesh to create
  35115. * @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
  35116. * @param radius is the radius value of the lathe
  35117. * @param tessellation is the side number of the lathe.
  35118. * @param scene defines the hosting scene
  35119. * @param updatable defines if the mesh must be flagged as updatable
  35120. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35121. * @returns a new Mesh
  35122. */
  35123. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  35124. var options = {
  35125. shape: shape,
  35126. radius: radius,
  35127. tessellation: tessellation,
  35128. sideOrientation: sideOrientation,
  35129. updatable: updatable
  35130. };
  35131. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  35132. };
  35133. /**
  35134. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  35135. * @param name defines the name of the mesh to create
  35136. * @param size sets the size (float) of both sides of the plane at once (default 1)
  35137. * @param scene defines the hosting scene
  35138. * @param updatable defines if the mesh must be flagged as updatable
  35139. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35140. * @returns a new Mesh
  35141. */
  35142. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  35143. var options = {
  35144. size: size,
  35145. width: size,
  35146. height: size,
  35147. sideOrientation: sideOrientation,
  35148. updatable: updatable
  35149. };
  35150. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  35151. };
  35152. /**
  35153. * Creates a ground mesh.
  35154. * Please consider using the same method from the MeshBuilder class instead
  35155. * @param name defines the name of the mesh to create
  35156. * @param width set the width of the ground
  35157. * @param height set the height of the ground
  35158. * @param subdivisions sets the number of subdivisions per side
  35159. * @param scene defines the hosting scene
  35160. * @param updatable defines if the mesh must be flagged as updatable
  35161. * @returns a new Mesh
  35162. */
  35163. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  35164. var options = {
  35165. width: width,
  35166. height: height,
  35167. subdivisions: subdivisions,
  35168. updatable: updatable
  35169. };
  35170. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  35171. };
  35172. /**
  35173. * Creates a tiled ground mesh.
  35174. * Please consider using the same method from the MeshBuilder class instead
  35175. * @param name defines the name of the mesh to create
  35176. * @param xmin set the ground minimum X coordinate
  35177. * @param zmin set the ground minimum Y coordinate
  35178. * @param xmax set the ground maximum X coordinate
  35179. * @param zmax set the ground maximum Z coordinate
  35180. * @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
  35181. * @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
  35182. * @param scene defines the hosting scene
  35183. * @param updatable defines if the mesh must be flagged as updatable
  35184. * @returns a new Mesh
  35185. */
  35186. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  35187. var options = {
  35188. xmin: xmin,
  35189. zmin: zmin,
  35190. xmax: xmax,
  35191. zmax: zmax,
  35192. subdivisions: subdivisions,
  35193. precision: precision,
  35194. updatable: updatable
  35195. };
  35196. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  35197. };
  35198. /**
  35199. * Creates a ground mesh from a height map.
  35200. * Please consider using the same method from the MeshBuilder class instead
  35201. * @see http://doc.babylonjs.com/babylon101/height_map
  35202. * @param name defines the name of the mesh to create
  35203. * @param url sets the URL of the height map image resource
  35204. * @param width set the ground width size
  35205. * @param height set the ground height size
  35206. * @param subdivisions sets the number of subdivision per side
  35207. * @param minHeight is the minimum altitude on the ground
  35208. * @param maxHeight is the maximum altitude on the ground
  35209. * @param scene defines the hosting scene
  35210. * @param updatable defines if the mesh must be flagged as updatable
  35211. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  35212. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  35213. * @returns a new Mesh
  35214. */
  35215. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  35216. var options = {
  35217. width: width,
  35218. height: height,
  35219. subdivisions: subdivisions,
  35220. minHeight: minHeight,
  35221. maxHeight: maxHeight,
  35222. updatable: updatable,
  35223. onReady: onReady,
  35224. alphaFilter: alphaFilter
  35225. };
  35226. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  35227. };
  35228. /**
  35229. * Creates a tube mesh.
  35230. * The tube is a parametric shape.
  35231. * It has no predefined shape. Its final shape will depend on the input parameters.
  35232. * Please consider using the same method from the MeshBuilder class instead
  35233. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35234. * @param name defines the name of the mesh to create
  35235. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  35236. * @param radius sets the tube radius size
  35237. * @param tessellation is the number of sides on the tubular surface
  35238. * @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
  35239. * @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
  35240. * @param scene defines the hosting scene
  35241. * @param updatable defines if the mesh must be flagged as updatable
  35242. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35243. * @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)
  35244. * @returns a new Mesh
  35245. */
  35246. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  35247. var options = {
  35248. path: path,
  35249. radius: radius,
  35250. tessellation: tessellation,
  35251. radiusFunction: radiusFunction,
  35252. arc: 1,
  35253. cap: cap,
  35254. updatable: updatable,
  35255. sideOrientation: sideOrientation,
  35256. instance: instance
  35257. };
  35258. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  35259. };
  35260. /**
  35261. * Creates a polyhedron mesh.
  35262. * Please consider using the same method from the MeshBuilder class instead.
  35263. * * 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
  35264. * * The parameter `size` (positive float, default 1) sets the polygon size
  35265. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  35266. * * 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`
  35267. * * 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
  35268. * * 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)`)
  35269. * * 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
  35270. * * 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
  35271. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35272. * * 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
  35273. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35274. * @param name defines the name of the mesh to create
  35275. * @param options defines the options used to create the mesh
  35276. * @param scene defines the hosting scene
  35277. * @returns a new Mesh
  35278. */
  35279. Mesh.CreatePolyhedron = function (name, options, scene) {
  35280. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  35281. };
  35282. /**
  35283. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  35284. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  35285. * * 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`)
  35286. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  35287. * * 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
  35288. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35289. * * 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
  35290. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35291. * @param name defines the name of the mesh
  35292. * @param options defines the options used to create the mesh
  35293. * @param scene defines the hosting scene
  35294. * @returns a new Mesh
  35295. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  35296. */
  35297. Mesh.CreateIcoSphere = function (name, options, scene) {
  35298. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  35299. };
  35300. /**
  35301. * Creates a decal mesh.
  35302. * Please consider using the same method from the MeshBuilder class instead.
  35303. * A decal is a mesh usually applied as a model onto the surface of another mesh
  35304. * @param name defines the name of the mesh
  35305. * @param sourceMesh defines the mesh receiving the decal
  35306. * @param position sets the position of the decal in world coordinates
  35307. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  35308. * @param size sets the decal scaling
  35309. * @param angle sets the angle to rotate the decal
  35310. * @returns a new Mesh
  35311. */
  35312. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  35313. var options = {
  35314. position: position,
  35315. normal: normal,
  35316. size: size,
  35317. angle: angle
  35318. };
  35319. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  35320. };
  35321. // Skeletons
  35322. /**
  35323. * Prepare internal position array for software CPU skinning
  35324. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  35325. */
  35326. Mesh.prototype.setPositionsForCPUSkinning = function () {
  35327. if (!this._sourcePositions) {
  35328. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35329. if (!source) {
  35330. return this._sourcePositions;
  35331. }
  35332. this._sourcePositions = new Float32Array(source);
  35333. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35334. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  35335. }
  35336. }
  35337. return this._sourcePositions;
  35338. };
  35339. /**
  35340. * Prepare internal normal array for software CPU skinning
  35341. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  35342. */
  35343. Mesh.prototype.setNormalsForCPUSkinning = function () {
  35344. if (!this._sourceNormals) {
  35345. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35346. if (!source) {
  35347. return this._sourceNormals;
  35348. }
  35349. this._sourceNormals = new Float32Array(source);
  35350. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35351. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  35352. }
  35353. }
  35354. return this._sourceNormals;
  35355. };
  35356. /**
  35357. * Updates the vertex buffer by applying transformation from the bones
  35358. * @param skeleton defines the skeleton to apply to current mesh
  35359. * @returns the current mesh
  35360. */
  35361. Mesh.prototype.applySkeleton = function (skeleton) {
  35362. if (!this.geometry) {
  35363. return this;
  35364. }
  35365. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  35366. return this;
  35367. }
  35368. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  35369. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35370. return this;
  35371. }
  35372. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35373. return this;
  35374. }
  35375. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35376. return this;
  35377. }
  35378. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35379. return this;
  35380. }
  35381. if (!this._sourcePositions) {
  35382. var submeshes = this.subMeshes.slice();
  35383. this.setPositionsForCPUSkinning();
  35384. this.subMeshes = submeshes;
  35385. }
  35386. if (!this._sourceNormals) {
  35387. this.setNormalsForCPUSkinning();
  35388. }
  35389. // positionsData checks for not being Float32Array will only pass at most once
  35390. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35391. if (!positionsData) {
  35392. return this;
  35393. }
  35394. if (!(positionsData instanceof Float32Array)) {
  35395. positionsData = new Float32Array(positionsData);
  35396. }
  35397. // normalsData checks for not being Float32Array will only pass at most once
  35398. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35399. if (!normalsData) {
  35400. return this;
  35401. }
  35402. if (!(normalsData instanceof Float32Array)) {
  35403. normalsData = new Float32Array(normalsData);
  35404. }
  35405. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35406. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35407. if (!matricesWeightsData || !matricesIndicesData) {
  35408. return this;
  35409. }
  35410. var needExtras = this.numBoneInfluencers > 4;
  35411. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  35412. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  35413. var skeletonMatrices = skeleton.getTransformMatrices(this);
  35414. var tempVector3 = BABYLON.Vector3.Zero();
  35415. var finalMatrix = new BABYLON.Matrix();
  35416. var tempMatrix = new BABYLON.Matrix();
  35417. var matWeightIdx = 0;
  35418. var inf;
  35419. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  35420. var weight;
  35421. for (inf = 0; inf < 4; inf++) {
  35422. weight = matricesWeightsData[matWeightIdx + inf];
  35423. if (weight > 0) {
  35424. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35425. finalMatrix.addToSelf(tempMatrix);
  35426. }
  35427. }
  35428. if (needExtras) {
  35429. for (inf = 0; inf < 4; inf++) {
  35430. weight = matricesWeightsExtraData[matWeightIdx + inf];
  35431. if (weight > 0) {
  35432. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35433. finalMatrix.addToSelf(tempMatrix);
  35434. }
  35435. }
  35436. }
  35437. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  35438. tempVector3.toArray(positionsData, index);
  35439. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  35440. tempVector3.toArray(normalsData, index);
  35441. finalMatrix.reset();
  35442. }
  35443. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  35444. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  35445. return this;
  35446. };
  35447. // Tools
  35448. /**
  35449. * 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
  35450. * @param meshes defines the list of meshes to scan
  35451. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  35452. */
  35453. Mesh.MinMax = function (meshes) {
  35454. var minVector = null;
  35455. var maxVector = null;
  35456. meshes.forEach(function (mesh, index, array) {
  35457. var boundingInfo = mesh.getBoundingInfo();
  35458. var boundingBox = boundingInfo.boundingBox;
  35459. if (!minVector || !maxVector) {
  35460. minVector = boundingBox.minimumWorld;
  35461. maxVector = boundingBox.maximumWorld;
  35462. }
  35463. else {
  35464. minVector.minimizeInPlace(boundingBox.minimumWorld);
  35465. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  35466. }
  35467. });
  35468. if (!minVector || !maxVector) {
  35469. return {
  35470. min: BABYLON.Vector3.Zero(),
  35471. max: BABYLON.Vector3.Zero()
  35472. };
  35473. }
  35474. return {
  35475. min: minVector,
  35476. max: maxVector
  35477. };
  35478. };
  35479. /**
  35480. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  35481. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  35482. * @returns a vector3
  35483. */
  35484. Mesh.Center = function (meshesOrMinMaxVector) {
  35485. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  35486. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  35487. };
  35488. /**
  35489. * Merge the array of meshes into a single mesh for performance reasons.
  35490. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  35491. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  35492. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  35493. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  35494. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  35495. * @returns a new mesh
  35496. */
  35497. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  35498. if (disposeSource === void 0) { disposeSource = true; }
  35499. var index;
  35500. if (!allow32BitsIndices) {
  35501. var totalVertices = 0;
  35502. // Counting vertices
  35503. for (index = 0; index < meshes.length; index++) {
  35504. if (meshes[index]) {
  35505. totalVertices += meshes[index].getTotalVertices();
  35506. if (totalVertices > 65536) {
  35507. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  35508. return null;
  35509. }
  35510. }
  35511. }
  35512. }
  35513. // Merge
  35514. var vertexData = null;
  35515. var otherVertexData;
  35516. var indiceArray = new Array();
  35517. var source = null;
  35518. for (index = 0; index < meshes.length; index++) {
  35519. if (meshes[index]) {
  35520. var wm = meshes[index].computeWorldMatrix(true);
  35521. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  35522. otherVertexData.transform(wm);
  35523. if (vertexData) {
  35524. vertexData.merge(otherVertexData, allow32BitsIndices);
  35525. }
  35526. else {
  35527. vertexData = otherVertexData;
  35528. source = meshes[index];
  35529. }
  35530. if (subdivideWithSubMeshes) {
  35531. indiceArray.push(meshes[index].getTotalIndices());
  35532. }
  35533. }
  35534. }
  35535. source = source;
  35536. if (!meshSubclass) {
  35537. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  35538. }
  35539. vertexData.applyToMesh(meshSubclass);
  35540. // Setting properties
  35541. meshSubclass.material = source.material;
  35542. meshSubclass.checkCollisions = source.checkCollisions;
  35543. // Cleaning
  35544. if (disposeSource) {
  35545. for (index = 0; index < meshes.length; index++) {
  35546. if (meshes[index]) {
  35547. meshes[index].dispose();
  35548. }
  35549. }
  35550. }
  35551. // Subdivide
  35552. if (subdivideWithSubMeshes) {
  35553. //-- removal of global submesh
  35554. meshSubclass.releaseSubMeshes();
  35555. index = 0;
  35556. var offset = 0;
  35557. //-- apply subdivision according to index table
  35558. while (index < indiceArray.length) {
  35559. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  35560. offset += indiceArray[index];
  35561. index++;
  35562. }
  35563. }
  35564. return meshSubclass;
  35565. };
  35566. /** @hidden */
  35567. Mesh.prototype.addInstance = function (instance) {
  35568. instance._indexInSourceMeshInstanceArray = this.instances.length;
  35569. this.instances.push(instance);
  35570. };
  35571. /** @hidden */
  35572. Mesh.prototype.removeInstance = function (instance) {
  35573. // Remove from mesh
  35574. var index = instance._indexInSourceMeshInstanceArray;
  35575. if (index != -1) {
  35576. if (index !== this.instances.length - 1) {
  35577. var last = this.instances[this.instances.length - 1];
  35578. this.instances[index] = last;
  35579. last._indexInSourceMeshInstanceArray = index;
  35580. }
  35581. instance._indexInSourceMeshInstanceArray = -1;
  35582. this.instances.pop();
  35583. }
  35584. };
  35585. // Consts
  35586. /**
  35587. * Mesh side orientation : usually the external or front surface
  35588. */
  35589. Mesh.FRONTSIDE = 0;
  35590. /**
  35591. * Mesh side orientation : usually the internal or back surface
  35592. */
  35593. Mesh.BACKSIDE = 1;
  35594. /**
  35595. * Mesh side orientation : both internal and external or front and back surfaces
  35596. */
  35597. Mesh.DOUBLESIDE = 2;
  35598. /**
  35599. * Mesh side orientation : by default, `FRONTSIDE`
  35600. */
  35601. Mesh.DEFAULTSIDE = 0;
  35602. /**
  35603. * Mesh cap setting : no cap
  35604. */
  35605. Mesh.NO_CAP = 0;
  35606. /**
  35607. * Mesh cap setting : one cap at the beginning of the mesh
  35608. */
  35609. Mesh.CAP_START = 1;
  35610. /**
  35611. * Mesh cap setting : one cap at the end of the mesh
  35612. */
  35613. Mesh.CAP_END = 2;
  35614. /**
  35615. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  35616. */
  35617. Mesh.CAP_ALL = 3;
  35618. return Mesh;
  35619. }(BABYLON.AbstractMesh));
  35620. BABYLON.Mesh = Mesh;
  35621. })(BABYLON || (BABYLON = {}));
  35622. //# sourceMappingURL=babylon.mesh.js.map
  35623. var BABYLON;
  35624. (function (BABYLON) {
  35625. /**
  35626. * Base class for submeshes
  35627. */
  35628. var BaseSubMesh = /** @class */ (function () {
  35629. function BaseSubMesh() {
  35630. }
  35631. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  35632. /**
  35633. * Gets associated effect
  35634. */
  35635. get: function () {
  35636. return this._materialEffect;
  35637. },
  35638. enumerable: true,
  35639. configurable: true
  35640. });
  35641. /**
  35642. * Sets associated effect (effect used to render this submesh)
  35643. * @param effect defines the effect to associate with
  35644. * @param defines defines the set of defines used to compile this effect
  35645. */
  35646. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  35647. if (defines === void 0) { defines = null; }
  35648. if (this._materialEffect === effect) {
  35649. if (!effect) {
  35650. this._materialDefines = null;
  35651. }
  35652. return;
  35653. }
  35654. this._materialDefines = defines;
  35655. this._materialEffect = effect;
  35656. };
  35657. return BaseSubMesh;
  35658. }());
  35659. BABYLON.BaseSubMesh = BaseSubMesh;
  35660. /**
  35661. * Defines a subdivision inside a mesh
  35662. */
  35663. var SubMesh = /** @class */ (function (_super) {
  35664. __extends(SubMesh, _super);
  35665. /**
  35666. * Creates a new submesh
  35667. * @param materialIndex defines the material index to use
  35668. * @param verticesStart defines vertex index start
  35669. * @param verticesCount defines vertices count
  35670. * @param indexStart defines index start
  35671. * @param indexCount defines indices count
  35672. * @param mesh defines the parent mesh
  35673. * @param renderingMesh defines an optional rendering mesh
  35674. * @param createBoundingBox defines if bounding box should be created for this submesh
  35675. */
  35676. function SubMesh(
  35677. /** the material index to use */
  35678. materialIndex,
  35679. /** vertex index start */
  35680. verticesStart,
  35681. /** vertices count */
  35682. verticesCount,
  35683. /** index start */
  35684. indexStart,
  35685. /** indices count */
  35686. indexCount, mesh, renderingMesh, createBoundingBox) {
  35687. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35688. var _this = _super.call(this) || this;
  35689. _this.materialIndex = materialIndex;
  35690. _this.verticesStart = verticesStart;
  35691. _this.verticesCount = verticesCount;
  35692. _this.indexStart = indexStart;
  35693. _this.indexCount = indexCount;
  35694. /** @hidden */
  35695. _this._renderId = 0;
  35696. _this._mesh = mesh;
  35697. _this._renderingMesh = renderingMesh || mesh;
  35698. mesh.subMeshes.push(_this);
  35699. _this._trianglePlanes = [];
  35700. _this._id = mesh.subMeshes.length - 1;
  35701. if (createBoundingBox) {
  35702. _this.refreshBoundingInfo();
  35703. mesh.computeWorldMatrix(true);
  35704. }
  35705. return _this;
  35706. }
  35707. /**
  35708. * Add a new submesh to a mesh
  35709. * @param materialIndex defines the material index to use
  35710. * @param verticesStart defines vertex index start
  35711. * @param verticesCount defines vertices count
  35712. * @param indexStart defines index start
  35713. * @param indexCount defines indices count
  35714. * @param mesh defines the parent mesh
  35715. * @param renderingMesh defines an optional rendering mesh
  35716. * @param createBoundingBox defines if bounding box should be created for this submesh
  35717. * @returns the new submesh
  35718. */
  35719. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  35720. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35721. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  35722. };
  35723. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  35724. /**
  35725. * Returns true if this submesh covers the entire parent mesh
  35726. * @ignorenaming
  35727. */
  35728. get: function () {
  35729. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35730. },
  35731. enumerable: true,
  35732. configurable: true
  35733. });
  35734. /**
  35735. * Returns the submesh BoudingInfo object
  35736. * @returns current bounding info (or mesh's one if the submesh is global)
  35737. */
  35738. SubMesh.prototype.getBoundingInfo = function () {
  35739. if (this.IsGlobal) {
  35740. return this._mesh.getBoundingInfo();
  35741. }
  35742. return this._boundingInfo;
  35743. };
  35744. /**
  35745. * Sets the submesh BoundingInfo
  35746. * @param boundingInfo defines the new bounding info to use
  35747. * @returns the SubMesh
  35748. */
  35749. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35750. this._boundingInfo = boundingInfo;
  35751. return this;
  35752. };
  35753. /**
  35754. * Returns the mesh of the current submesh
  35755. * @return the parent mesh
  35756. */
  35757. SubMesh.prototype.getMesh = function () {
  35758. return this._mesh;
  35759. };
  35760. /**
  35761. * Returns the rendering mesh of the submesh
  35762. * @returns the rendering mesh (could be different from parent mesh)
  35763. */
  35764. SubMesh.prototype.getRenderingMesh = function () {
  35765. return this._renderingMesh;
  35766. };
  35767. /**
  35768. * Returns the submesh material
  35769. * @returns null or the current material
  35770. */
  35771. SubMesh.prototype.getMaterial = function () {
  35772. var rootMaterial = this._renderingMesh.material;
  35773. if (rootMaterial === null || rootMaterial === undefined) {
  35774. return this._mesh.getScene().defaultMaterial;
  35775. }
  35776. else if (rootMaterial.getSubMaterial) {
  35777. var multiMaterial = rootMaterial;
  35778. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35779. if (this._currentMaterial !== effectiveMaterial) {
  35780. this._currentMaterial = effectiveMaterial;
  35781. this._materialDefines = null;
  35782. }
  35783. return effectiveMaterial;
  35784. }
  35785. return rootMaterial;
  35786. };
  35787. // Methods
  35788. /**
  35789. * Sets a new updated BoundingInfo object to the submesh
  35790. * @returns the SubMesh
  35791. */
  35792. SubMesh.prototype.refreshBoundingInfo = function () {
  35793. this._lastColliderWorldVertices = null;
  35794. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35795. return this;
  35796. }
  35797. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35798. if (!data) {
  35799. this._boundingInfo = this._mesh.getBoundingInfo();
  35800. return this;
  35801. }
  35802. var indices = this._renderingMesh.getIndices();
  35803. var extend;
  35804. //is this the only submesh?
  35805. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35806. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35807. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35808. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35809. }
  35810. else {
  35811. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35812. }
  35813. if (this._boundingInfo) {
  35814. this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
  35815. }
  35816. else {
  35817. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35818. }
  35819. return this;
  35820. };
  35821. /** @hidden */
  35822. SubMesh.prototype._checkCollision = function (collider) {
  35823. var boundingInfo = this.getBoundingInfo();
  35824. return boundingInfo._checkCollision(collider);
  35825. };
  35826. /**
  35827. * Updates the submesh BoundingInfo
  35828. * @param world defines the world matrix to use to update the bounding info
  35829. * @returns the submesh
  35830. */
  35831. SubMesh.prototype.updateBoundingInfo = function (world) {
  35832. var boundingInfo = this.getBoundingInfo();
  35833. if (!boundingInfo) {
  35834. this.refreshBoundingInfo();
  35835. boundingInfo = this.getBoundingInfo();
  35836. }
  35837. boundingInfo.update(world);
  35838. return this;
  35839. };
  35840. /**
  35841. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35842. * @param frustumPlanes defines the frustum planes
  35843. * @returns true if the submesh is intersecting with the frustum
  35844. */
  35845. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35846. var boundingInfo = this.getBoundingInfo();
  35847. if (!boundingInfo) {
  35848. return false;
  35849. }
  35850. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  35851. };
  35852. /**
  35853. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35854. * @param frustumPlanes defines the frustum planes
  35855. * @returns true if the submesh is inside the frustum
  35856. */
  35857. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  35858. var boundingInfo = this.getBoundingInfo();
  35859. if (!boundingInfo) {
  35860. return false;
  35861. }
  35862. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  35863. };
  35864. /**
  35865. * Renders the submesh
  35866. * @param enableAlphaMode defines if alpha needs to be used
  35867. * @returns the submesh
  35868. */
  35869. SubMesh.prototype.render = function (enableAlphaMode) {
  35870. this._renderingMesh.render(this, enableAlphaMode);
  35871. return this;
  35872. };
  35873. /**
  35874. * @hidden
  35875. */
  35876. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  35877. if (!this._linesIndexBuffer) {
  35878. var linesIndices = [];
  35879. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35880. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  35881. }
  35882. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  35883. this._linesIndexCount = linesIndices.length;
  35884. }
  35885. return this._linesIndexBuffer;
  35886. };
  35887. /**
  35888. * Checks if the submesh intersects with a ray
  35889. * @param ray defines the ray to test
  35890. * @returns true is the passed ray intersects the submesh bounding box
  35891. */
  35892. SubMesh.prototype.canIntersects = function (ray) {
  35893. var boundingInfo = this.getBoundingInfo();
  35894. if (!boundingInfo) {
  35895. return false;
  35896. }
  35897. return ray.intersectsBox(boundingInfo.boundingBox);
  35898. };
  35899. /**
  35900. * Intersects current submesh with a ray
  35901. * @param ray defines the ray to test
  35902. * @param positions defines mesh's positions array
  35903. * @param indices defines mesh's indices array
  35904. * @param fastCheck defines if only bounding info should be used
  35905. * @returns intersection info or null if no intersection
  35906. */
  35907. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  35908. var material = this.getMaterial();
  35909. if (!material) {
  35910. return null;
  35911. }
  35912. switch (material.fillMode) {
  35913. case BABYLON.Material.PointListDrawMode:
  35914. case BABYLON.Material.LineListDrawMode:
  35915. case BABYLON.Material.LineLoopDrawMode:
  35916. case BABYLON.Material.LineStripDrawMode:
  35917. case BABYLON.Material.TriangleFanDrawMode:
  35918. case BABYLON.Material.TriangleStripDrawMode:
  35919. return null;
  35920. }
  35921. // LineMesh first as it's also a Mesh...
  35922. if (BABYLON.LinesMesh) {
  35923. var mesh = this._mesh instanceof BABYLON.InstancedMesh ? this._mesh.sourceMesh : this._mesh;
  35924. if (mesh instanceof BABYLON.LinesMesh) {
  35925. var linesMesh = mesh;
  35926. return this._intersectLines(ray, positions, indices, linesMesh.intersectionThreshold, fastCheck);
  35927. }
  35928. }
  35929. return this._intersectTriangles(ray, positions, indices, fastCheck);
  35930. };
  35931. /** @hidden */
  35932. SubMesh.prototype._intersectLines = function (ray, positions, indices, intersectionThreshold, fastCheck) {
  35933. var intersectInfo = null;
  35934. // Line test
  35935. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  35936. var p0 = positions[indices[index]];
  35937. var p1 = positions[indices[index + 1]];
  35938. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  35939. if (length < 0) {
  35940. continue;
  35941. }
  35942. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  35943. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  35944. if (fastCheck) {
  35945. break;
  35946. }
  35947. }
  35948. }
  35949. return intersectInfo;
  35950. };
  35951. /** @hidden */
  35952. SubMesh.prototype._intersectTriangles = function (ray, positions, indices, fastCheck) {
  35953. var intersectInfo = null;
  35954. // Triangles test
  35955. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35956. var p0 = positions[indices[index]];
  35957. var p1 = positions[indices[index + 1]];
  35958. var p2 = positions[indices[index + 2]];
  35959. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  35960. if (currentIntersectInfo) {
  35961. if (currentIntersectInfo.distance < 0) {
  35962. continue;
  35963. }
  35964. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  35965. intersectInfo = currentIntersectInfo;
  35966. intersectInfo.faceId = index / 3;
  35967. if (fastCheck) {
  35968. break;
  35969. }
  35970. }
  35971. }
  35972. }
  35973. return intersectInfo;
  35974. };
  35975. /** @hidden */
  35976. SubMesh.prototype._rebuild = function () {
  35977. if (this._linesIndexBuffer) {
  35978. this._linesIndexBuffer = null;
  35979. }
  35980. };
  35981. // Clone
  35982. /**
  35983. * Creates a new submesh from the passed mesh
  35984. * @param newMesh defines the new hosting mesh
  35985. * @param newRenderingMesh defines an optional rendering mesh
  35986. * @returns the new submesh
  35987. */
  35988. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  35989. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  35990. if (!this.IsGlobal) {
  35991. var boundingInfo = this.getBoundingInfo();
  35992. if (!boundingInfo) {
  35993. return result;
  35994. }
  35995. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  35996. }
  35997. return result;
  35998. };
  35999. // Dispose
  36000. /**
  36001. * Release associated resources
  36002. */
  36003. SubMesh.prototype.dispose = function () {
  36004. if (this._linesIndexBuffer) {
  36005. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  36006. this._linesIndexBuffer = null;
  36007. }
  36008. // Remove from mesh
  36009. var index = this._mesh.subMeshes.indexOf(this);
  36010. this._mesh.subMeshes.splice(index, 1);
  36011. };
  36012. // Statics
  36013. /**
  36014. * Creates a new submesh from indices data
  36015. * @param materialIndex the index of the main mesh material
  36016. * @param startIndex the index where to start the copy in the mesh indices array
  36017. * @param indexCount the number of indices to copy then from the startIndex
  36018. * @param mesh the main mesh to create the submesh from
  36019. * @param renderingMesh the optional rendering mesh
  36020. * @returns a new submesh
  36021. */
  36022. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  36023. var minVertexIndex = Number.MAX_VALUE;
  36024. var maxVertexIndex = -Number.MAX_VALUE;
  36025. renderingMesh = (renderingMesh || mesh);
  36026. var indices = renderingMesh.getIndices();
  36027. for (var index = startIndex; index < startIndex + indexCount; index++) {
  36028. var vertexIndex = indices[index];
  36029. if (vertexIndex < minVertexIndex) {
  36030. minVertexIndex = vertexIndex;
  36031. }
  36032. if (vertexIndex > maxVertexIndex) {
  36033. maxVertexIndex = vertexIndex;
  36034. }
  36035. }
  36036. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  36037. };
  36038. return SubMesh;
  36039. }(BaseSubMesh));
  36040. BABYLON.SubMesh = SubMesh;
  36041. })(BABYLON || (BABYLON = {}));
  36042. //# sourceMappingURL=babylon.subMesh.js.map
  36043. var __assign = (this && this.__assign) || function () {
  36044. __assign = Object.assign || function(t) {
  36045. for (var s, i = 1, n = arguments.length; i < n; i++) {
  36046. s = arguments[i];
  36047. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  36048. t[p] = s[p];
  36049. }
  36050. return t;
  36051. };
  36052. return __assign.apply(this, arguments);
  36053. };
  36054. var BABYLON;
  36055. (function (BABYLON) {
  36056. /**
  36057. * Manages the defines for the Material
  36058. */
  36059. var MaterialDefines = /** @class */ (function () {
  36060. function MaterialDefines() {
  36061. this._isDirty = true;
  36062. /** @hidden */
  36063. this._areLightsDirty = true;
  36064. /** @hidden */
  36065. this._areAttributesDirty = true;
  36066. /** @hidden */
  36067. this._areTexturesDirty = true;
  36068. /** @hidden */
  36069. this._areFresnelDirty = true;
  36070. /** @hidden */
  36071. this._areMiscDirty = true;
  36072. /** @hidden */
  36073. this._areImageProcessingDirty = true;
  36074. /** @hidden */
  36075. this._normals = false;
  36076. /** @hidden */
  36077. this._uvs = false;
  36078. /** @hidden */
  36079. this._needNormals = false;
  36080. /** @hidden */
  36081. this._needUVs = false;
  36082. }
  36083. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  36084. /**
  36085. * Specifies if the material needs to be re-calculated
  36086. */
  36087. get: function () {
  36088. return this._isDirty;
  36089. },
  36090. enumerable: true,
  36091. configurable: true
  36092. });
  36093. /**
  36094. * Marks the material to indicate that it has been re-calculated
  36095. */
  36096. MaterialDefines.prototype.markAsProcessed = function () {
  36097. this._isDirty = false;
  36098. this._areAttributesDirty = false;
  36099. this._areTexturesDirty = false;
  36100. this._areFresnelDirty = false;
  36101. this._areLightsDirty = false;
  36102. this._areMiscDirty = false;
  36103. this._areImageProcessingDirty = false;
  36104. };
  36105. /**
  36106. * Marks the material to indicate that it needs to be re-calculated
  36107. */
  36108. MaterialDefines.prototype.markAsUnprocessed = function () {
  36109. this._isDirty = true;
  36110. };
  36111. /**
  36112. * Marks the material to indicate all of its defines need to be re-calculated
  36113. */
  36114. MaterialDefines.prototype.markAllAsDirty = function () {
  36115. this._areTexturesDirty = true;
  36116. this._areAttributesDirty = true;
  36117. this._areLightsDirty = true;
  36118. this._areFresnelDirty = true;
  36119. this._areMiscDirty = true;
  36120. this._areImageProcessingDirty = true;
  36121. this._isDirty = true;
  36122. };
  36123. /**
  36124. * Marks the material to indicate that image processing needs to be re-calculated
  36125. */
  36126. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  36127. this._areImageProcessingDirty = true;
  36128. this._isDirty = true;
  36129. };
  36130. /**
  36131. * Marks the material to indicate the lights need to be re-calculated
  36132. */
  36133. MaterialDefines.prototype.markAsLightDirty = function () {
  36134. this._areLightsDirty = true;
  36135. this._isDirty = true;
  36136. };
  36137. /**
  36138. * Marks the attribute state as changed
  36139. */
  36140. MaterialDefines.prototype.markAsAttributesDirty = function () {
  36141. this._areAttributesDirty = true;
  36142. this._isDirty = true;
  36143. };
  36144. /**
  36145. * Marks the texture state as changed
  36146. */
  36147. MaterialDefines.prototype.markAsTexturesDirty = function () {
  36148. this._areTexturesDirty = true;
  36149. this._isDirty = true;
  36150. };
  36151. /**
  36152. * Marks the fresnel state as changed
  36153. */
  36154. MaterialDefines.prototype.markAsFresnelDirty = function () {
  36155. this._areFresnelDirty = true;
  36156. this._isDirty = true;
  36157. };
  36158. /**
  36159. * Marks the misc state as changed
  36160. */
  36161. MaterialDefines.prototype.markAsMiscDirty = function () {
  36162. this._areMiscDirty = true;
  36163. this._isDirty = true;
  36164. };
  36165. /**
  36166. * Rebuilds the material defines
  36167. */
  36168. MaterialDefines.prototype.rebuild = function () {
  36169. if (this._keys) {
  36170. delete this._keys;
  36171. }
  36172. this._keys = [];
  36173. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  36174. var key = _a[_i];
  36175. if (key[0] === "_") {
  36176. continue;
  36177. }
  36178. this._keys.push(key);
  36179. }
  36180. };
  36181. /**
  36182. * Specifies if two material defines are equal
  36183. * @param other - A material define instance to compare to
  36184. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  36185. */
  36186. MaterialDefines.prototype.isEqual = function (other) {
  36187. if (this._keys.length !== other._keys.length) {
  36188. return false;
  36189. }
  36190. for (var index = 0; index < this._keys.length; index++) {
  36191. var prop = this._keys[index];
  36192. if (this[prop] !== other[prop]) {
  36193. return false;
  36194. }
  36195. }
  36196. return true;
  36197. };
  36198. /**
  36199. * Clones this instance's defines to another instance
  36200. * @param other - material defines to clone values to
  36201. */
  36202. MaterialDefines.prototype.cloneTo = function (other) {
  36203. if (this._keys.length !== other._keys.length) {
  36204. other._keys = this._keys.slice(0);
  36205. }
  36206. for (var index = 0; index < this._keys.length; index++) {
  36207. var prop = this._keys[index];
  36208. other[prop] = this[prop];
  36209. }
  36210. };
  36211. /**
  36212. * Resets the material define values
  36213. */
  36214. MaterialDefines.prototype.reset = function () {
  36215. for (var index = 0; index < this._keys.length; index++) {
  36216. var prop = this._keys[index];
  36217. var type = typeof this[prop];
  36218. switch (type) {
  36219. case "number":
  36220. this[prop] = 0;
  36221. break;
  36222. case "string":
  36223. this[prop] = "";
  36224. break;
  36225. default:
  36226. this[prop] = false;
  36227. break;
  36228. }
  36229. }
  36230. };
  36231. /**
  36232. * Converts the material define values to a string
  36233. * @returns - String of material define information
  36234. */
  36235. MaterialDefines.prototype.toString = function () {
  36236. var result = "";
  36237. for (var index = 0; index < this._keys.length; index++) {
  36238. var prop = this._keys[index];
  36239. var value = this[prop];
  36240. var type = typeof value;
  36241. switch (type) {
  36242. case "number":
  36243. case "string":
  36244. result += "#define " + prop + " " + value + "\n";
  36245. break;
  36246. default:
  36247. if (value) {
  36248. result += "#define " + prop + "\n";
  36249. }
  36250. break;
  36251. }
  36252. }
  36253. return result;
  36254. };
  36255. return MaterialDefines;
  36256. }());
  36257. BABYLON.MaterialDefines = MaterialDefines;
  36258. /**
  36259. * Base class for the main features of a material in Babylon.js
  36260. */
  36261. var Material = /** @class */ (function () {
  36262. /**
  36263. * Creates a material instance
  36264. * @param name defines the name of the material
  36265. * @param scene defines the scene to reference
  36266. * @param doNotAdd specifies if the material should be added to the scene
  36267. */
  36268. function Material(name, scene, doNotAdd) {
  36269. /**
  36270. * Specifies if the ready state should be checked on each call
  36271. */
  36272. this.checkReadyOnEveryCall = false;
  36273. /**
  36274. * Specifies if the ready state should be checked once
  36275. */
  36276. this.checkReadyOnlyOnce = false;
  36277. /**
  36278. * The state of the material
  36279. */
  36280. this.state = "";
  36281. /**
  36282. * The alpha value of the material
  36283. */
  36284. this._alpha = 1.0;
  36285. /**
  36286. * Specifies if back face culling is enabled
  36287. */
  36288. this._backFaceCulling = true;
  36289. /**
  36290. * Specifies if the material should be serialized
  36291. */
  36292. this.doNotSerialize = false;
  36293. /**
  36294. * @hidden
  36295. */
  36296. this._storeEffectOnSubMeshes = false;
  36297. /**
  36298. * An event triggered when the material is disposed
  36299. */
  36300. this.onDisposeObservable = new BABYLON.Observable();
  36301. /**
  36302. * Stores the value of the alpha mode
  36303. */
  36304. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  36305. /**
  36306. * Stores the state of the need depth pre-pass value
  36307. */
  36308. this._needDepthPrePass = false;
  36309. /**
  36310. * Specifies if depth writing should be disabled
  36311. */
  36312. this.disableDepthWrite = false;
  36313. /**
  36314. * Specifies if depth writing should be forced
  36315. */
  36316. this.forceDepthWrite = false;
  36317. /**
  36318. * Specifies if there should be a separate pass for culling
  36319. */
  36320. this.separateCullingPass = false;
  36321. /**
  36322. * Stores the state specifing if fog should be enabled
  36323. */
  36324. this._fogEnabled = true;
  36325. /**
  36326. * Stores the size of points
  36327. */
  36328. this.pointSize = 1.0;
  36329. /**
  36330. * Stores the z offset value
  36331. */
  36332. this.zOffset = 0;
  36333. /**
  36334. * @hidden
  36335. * Specifies if the material was previously ready
  36336. */
  36337. this._wasPreviouslyReady = false;
  36338. /**
  36339. * Stores the fill mode state
  36340. */
  36341. this._fillMode = Material.TriangleFillMode;
  36342. /** @hidden */
  36343. this._indexInSceneMaterialArray = -1;
  36344. this.name = name;
  36345. this.id = name || BABYLON.Tools.RandomId();
  36346. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36347. this.uniqueId = this._scene.getUniqueId();
  36348. if (this._scene.useRightHandedSystem) {
  36349. this.sideOrientation = Material.ClockWiseSideOrientation;
  36350. }
  36351. else {
  36352. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  36353. }
  36354. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  36355. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  36356. if (!doNotAdd) {
  36357. this._scene.addMaterial(this);
  36358. }
  36359. if (this._scene.useMaterialMeshMap) {
  36360. this.meshMap = {};
  36361. }
  36362. }
  36363. Object.defineProperty(Material, "TriangleFillMode", {
  36364. /**
  36365. * Returns the triangle fill mode
  36366. */
  36367. get: function () {
  36368. return Material._TriangleFillMode;
  36369. },
  36370. enumerable: true,
  36371. configurable: true
  36372. });
  36373. Object.defineProperty(Material, "WireFrameFillMode", {
  36374. /**
  36375. * Returns the wireframe mode
  36376. */
  36377. get: function () {
  36378. return Material._WireFrameFillMode;
  36379. },
  36380. enumerable: true,
  36381. configurable: true
  36382. });
  36383. Object.defineProperty(Material, "PointFillMode", {
  36384. /**
  36385. * Returns the point fill mode
  36386. */
  36387. get: function () {
  36388. return Material._PointFillMode;
  36389. },
  36390. enumerable: true,
  36391. configurable: true
  36392. });
  36393. Object.defineProperty(Material, "PointListDrawMode", {
  36394. /**
  36395. * Returns the point list draw mode
  36396. */
  36397. get: function () {
  36398. return Material._PointListDrawMode;
  36399. },
  36400. enumerable: true,
  36401. configurable: true
  36402. });
  36403. Object.defineProperty(Material, "LineListDrawMode", {
  36404. /**
  36405. * Returns the line list draw mode
  36406. */
  36407. get: function () {
  36408. return Material._LineListDrawMode;
  36409. },
  36410. enumerable: true,
  36411. configurable: true
  36412. });
  36413. Object.defineProperty(Material, "LineLoopDrawMode", {
  36414. /**
  36415. * Returns the line loop draw mode
  36416. */
  36417. get: function () {
  36418. return Material._LineLoopDrawMode;
  36419. },
  36420. enumerable: true,
  36421. configurable: true
  36422. });
  36423. Object.defineProperty(Material, "LineStripDrawMode", {
  36424. /**
  36425. * Returns the line strip draw mode
  36426. */
  36427. get: function () {
  36428. return Material._LineStripDrawMode;
  36429. },
  36430. enumerable: true,
  36431. configurable: true
  36432. });
  36433. Object.defineProperty(Material, "TriangleStripDrawMode", {
  36434. /**
  36435. * Returns the triangle strip draw mode
  36436. */
  36437. get: function () {
  36438. return Material._TriangleStripDrawMode;
  36439. },
  36440. enumerable: true,
  36441. configurable: true
  36442. });
  36443. Object.defineProperty(Material, "TriangleFanDrawMode", {
  36444. /**
  36445. * Returns the triangle fan draw mode
  36446. */
  36447. get: function () {
  36448. return Material._TriangleFanDrawMode;
  36449. },
  36450. enumerable: true,
  36451. configurable: true
  36452. });
  36453. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  36454. /**
  36455. * Returns the clock-wise side orientation
  36456. */
  36457. get: function () {
  36458. return Material._ClockWiseSideOrientation;
  36459. },
  36460. enumerable: true,
  36461. configurable: true
  36462. });
  36463. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  36464. /**
  36465. * Returns the counter clock-wise side orientation
  36466. */
  36467. get: function () {
  36468. return Material._CounterClockWiseSideOrientation;
  36469. },
  36470. enumerable: true,
  36471. configurable: true
  36472. });
  36473. Object.defineProperty(Material.prototype, "alpha", {
  36474. /**
  36475. * Gets the alpha value of the material
  36476. */
  36477. get: function () {
  36478. return this._alpha;
  36479. },
  36480. /**
  36481. * Sets the alpha value of the material
  36482. */
  36483. set: function (value) {
  36484. if (this._alpha === value) {
  36485. return;
  36486. }
  36487. this._alpha = value;
  36488. this.markAsDirty(Material.MiscDirtyFlag);
  36489. },
  36490. enumerable: true,
  36491. configurable: true
  36492. });
  36493. Object.defineProperty(Material.prototype, "backFaceCulling", {
  36494. /**
  36495. * Gets the back-face culling state
  36496. */
  36497. get: function () {
  36498. return this._backFaceCulling;
  36499. },
  36500. /**
  36501. * Sets the back-face culling state
  36502. */
  36503. set: function (value) {
  36504. if (this._backFaceCulling === value) {
  36505. return;
  36506. }
  36507. this._backFaceCulling = value;
  36508. this.markAsDirty(Material.TextureDirtyFlag);
  36509. },
  36510. enumerable: true,
  36511. configurable: true
  36512. });
  36513. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  36514. /**
  36515. * Gets a boolean indicating that current material needs to register RTT
  36516. */
  36517. get: function () {
  36518. return false;
  36519. },
  36520. enumerable: true,
  36521. configurable: true
  36522. });
  36523. Object.defineProperty(Material.prototype, "onDispose", {
  36524. /**
  36525. * Called during a dispose event
  36526. */
  36527. set: function (callback) {
  36528. if (this._onDisposeObserver) {
  36529. this.onDisposeObservable.remove(this._onDisposeObserver);
  36530. }
  36531. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36532. },
  36533. enumerable: true,
  36534. configurable: true
  36535. });
  36536. Object.defineProperty(Material.prototype, "onBindObservable", {
  36537. /**
  36538. * An event triggered when the material is bound
  36539. */
  36540. get: function () {
  36541. if (!this._onBindObservable) {
  36542. this._onBindObservable = new BABYLON.Observable();
  36543. }
  36544. return this._onBindObservable;
  36545. },
  36546. enumerable: true,
  36547. configurable: true
  36548. });
  36549. Object.defineProperty(Material.prototype, "onBind", {
  36550. /**
  36551. * Called during a bind event
  36552. */
  36553. set: function (callback) {
  36554. if (this._onBindObserver) {
  36555. this.onBindObservable.remove(this._onBindObserver);
  36556. }
  36557. this._onBindObserver = this.onBindObservable.add(callback);
  36558. },
  36559. enumerable: true,
  36560. configurable: true
  36561. });
  36562. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  36563. /**
  36564. * An event triggered when the material is unbound
  36565. */
  36566. get: function () {
  36567. if (!this._onUnBindObservable) {
  36568. this._onUnBindObservable = new BABYLON.Observable();
  36569. }
  36570. return this._onUnBindObservable;
  36571. },
  36572. enumerable: true,
  36573. configurable: true
  36574. });
  36575. Object.defineProperty(Material.prototype, "alphaMode", {
  36576. /**
  36577. * Gets the value of the alpha mode
  36578. */
  36579. get: function () {
  36580. return this._alphaMode;
  36581. },
  36582. /**
  36583. * Sets the value of the alpha mode.
  36584. *
  36585. * | Value | Type | Description |
  36586. * | --- | --- | --- |
  36587. * | 0 | ALPHA_DISABLE | |
  36588. * | 1 | ALPHA_ADD | |
  36589. * | 2 | ALPHA_COMBINE | |
  36590. * | 3 | ALPHA_SUBTRACT | |
  36591. * | 4 | ALPHA_MULTIPLY | |
  36592. * | 5 | ALPHA_MAXIMIZED | |
  36593. * | 6 | ALPHA_ONEONE | |
  36594. * | 7 | ALPHA_PREMULTIPLIED | |
  36595. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  36596. * | 9 | ALPHA_INTERPOLATE | |
  36597. * | 10 | ALPHA_SCREENMODE | |
  36598. *
  36599. */
  36600. set: function (value) {
  36601. if (this._alphaMode === value) {
  36602. return;
  36603. }
  36604. this._alphaMode = value;
  36605. this.markAsDirty(Material.TextureDirtyFlag);
  36606. },
  36607. enumerable: true,
  36608. configurable: true
  36609. });
  36610. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  36611. /**
  36612. * Gets the depth pre-pass value
  36613. */
  36614. get: function () {
  36615. return this._needDepthPrePass;
  36616. },
  36617. /**
  36618. * Sets the need depth pre-pass value
  36619. */
  36620. set: function (value) {
  36621. if (this._needDepthPrePass === value) {
  36622. return;
  36623. }
  36624. this._needDepthPrePass = value;
  36625. if (this._needDepthPrePass) {
  36626. this.checkReadyOnEveryCall = true;
  36627. }
  36628. },
  36629. enumerable: true,
  36630. configurable: true
  36631. });
  36632. Object.defineProperty(Material.prototype, "fogEnabled", {
  36633. /**
  36634. * Gets the value of the fog enabled state
  36635. */
  36636. get: function () {
  36637. return this._fogEnabled;
  36638. },
  36639. /**
  36640. * Sets the state for enabling fog
  36641. */
  36642. set: function (value) {
  36643. if (this._fogEnabled === value) {
  36644. return;
  36645. }
  36646. this._fogEnabled = value;
  36647. this.markAsDirty(Material.MiscDirtyFlag);
  36648. },
  36649. enumerable: true,
  36650. configurable: true
  36651. });
  36652. Object.defineProperty(Material.prototype, "wireframe", {
  36653. /**
  36654. * Gets a value specifying if wireframe mode is enabled
  36655. */
  36656. get: function () {
  36657. switch (this._fillMode) {
  36658. case Material.WireFrameFillMode:
  36659. case Material.LineListDrawMode:
  36660. case Material.LineLoopDrawMode:
  36661. case Material.LineStripDrawMode:
  36662. return true;
  36663. }
  36664. return this._scene.forceWireframe;
  36665. },
  36666. /**
  36667. * Sets the state of wireframe mode
  36668. */
  36669. set: function (value) {
  36670. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  36671. },
  36672. enumerable: true,
  36673. configurable: true
  36674. });
  36675. Object.defineProperty(Material.prototype, "pointsCloud", {
  36676. /**
  36677. * Gets the value specifying if point clouds are enabled
  36678. */
  36679. get: function () {
  36680. switch (this._fillMode) {
  36681. case Material.PointFillMode:
  36682. case Material.PointListDrawMode:
  36683. return true;
  36684. }
  36685. return this._scene.forcePointsCloud;
  36686. },
  36687. /**
  36688. * Sets the state of point cloud mode
  36689. */
  36690. set: function (value) {
  36691. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  36692. },
  36693. enumerable: true,
  36694. configurable: true
  36695. });
  36696. Object.defineProperty(Material.prototype, "fillMode", {
  36697. /**
  36698. * Gets the material fill mode
  36699. */
  36700. get: function () {
  36701. return this._fillMode;
  36702. },
  36703. /**
  36704. * Sets the material fill mode
  36705. */
  36706. set: function (value) {
  36707. if (this._fillMode === value) {
  36708. return;
  36709. }
  36710. this._fillMode = value;
  36711. this.markAsDirty(Material.MiscDirtyFlag);
  36712. },
  36713. enumerable: true,
  36714. configurable: true
  36715. });
  36716. /**
  36717. * Returns a string representation of the current material
  36718. * @param fullDetails defines a boolean indicating which levels of logging is desired
  36719. * @returns a string with material information
  36720. */
  36721. Material.prototype.toString = function (fullDetails) {
  36722. var ret = "Name: " + this.name;
  36723. if (fullDetails) {
  36724. }
  36725. return ret;
  36726. };
  36727. /**
  36728. * Gets the class name of the material
  36729. * @returns a string with the class name of the material
  36730. */
  36731. Material.prototype.getClassName = function () {
  36732. return "Material";
  36733. };
  36734. Object.defineProperty(Material.prototype, "isFrozen", {
  36735. /**
  36736. * Specifies if updates for the material been locked
  36737. */
  36738. get: function () {
  36739. return this.checkReadyOnlyOnce;
  36740. },
  36741. enumerable: true,
  36742. configurable: true
  36743. });
  36744. /**
  36745. * Locks updates for the material
  36746. */
  36747. Material.prototype.freeze = function () {
  36748. this.checkReadyOnlyOnce = true;
  36749. };
  36750. /**
  36751. * Unlocks updates for the material
  36752. */
  36753. Material.prototype.unfreeze = function () {
  36754. this.checkReadyOnlyOnce = false;
  36755. };
  36756. /**
  36757. * Specifies if the material is ready to be used
  36758. * @param mesh defines the mesh to check
  36759. * @param useInstances specifies if instances should be used
  36760. * @returns a boolean indicating if the material is ready to be used
  36761. */
  36762. Material.prototype.isReady = function (mesh, useInstances) {
  36763. return true;
  36764. };
  36765. /**
  36766. * Specifies that the submesh is ready to be used
  36767. * @param mesh defines the mesh to check
  36768. * @param subMesh defines which submesh to check
  36769. * @param useInstances specifies that instances should be used
  36770. * @returns a boolean indicating that the submesh is ready or not
  36771. */
  36772. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36773. return false;
  36774. };
  36775. /**
  36776. * Returns the material effect
  36777. * @returns the effect associated with the material
  36778. */
  36779. Material.prototype.getEffect = function () {
  36780. return this._effect;
  36781. };
  36782. /**
  36783. * Returns the current scene
  36784. * @returns a Scene
  36785. */
  36786. Material.prototype.getScene = function () {
  36787. return this._scene;
  36788. };
  36789. /**
  36790. * Specifies if the material will require alpha blending
  36791. * @returns a boolean specifying if alpha blending is needed
  36792. */
  36793. Material.prototype.needAlphaBlending = function () {
  36794. return (this.alpha < 1.0);
  36795. };
  36796. /**
  36797. * Specifies if the mesh will require alpha blending
  36798. * @param mesh defines the mesh to check
  36799. * @returns a boolean specifying if alpha blending is needed for the mesh
  36800. */
  36801. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36802. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36803. };
  36804. /**
  36805. * Specifies if this material should be rendered in alpha test mode
  36806. * @returns a boolean specifying if an alpha test is needed.
  36807. */
  36808. Material.prototype.needAlphaTesting = function () {
  36809. return false;
  36810. };
  36811. /**
  36812. * Gets the texture used for the alpha test
  36813. * @returns the texture to use for alpha testing
  36814. */
  36815. Material.prototype.getAlphaTestTexture = function () {
  36816. return null;
  36817. };
  36818. /**
  36819. * Marks the material to indicate that it needs to be re-calculated
  36820. */
  36821. Material.prototype.markDirty = function () {
  36822. this._wasPreviouslyReady = false;
  36823. };
  36824. /** @hidden */
  36825. Material.prototype._preBind = function (effect, overrideOrientation) {
  36826. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36827. var engine = this._scene.getEngine();
  36828. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36829. var reverse = orientation === Material.ClockWiseSideOrientation;
  36830. engine.enableEffect(effect ? effect : this._effect);
  36831. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36832. return reverse;
  36833. };
  36834. /**
  36835. * Binds the material to the mesh
  36836. * @param world defines the world transformation matrix
  36837. * @param mesh defines the mesh to bind the material to
  36838. */
  36839. Material.prototype.bind = function (world, mesh) {
  36840. };
  36841. /**
  36842. * Binds the submesh to the material
  36843. * @param world defines the world transformation matrix
  36844. * @param mesh defines the mesh containing the submesh
  36845. * @param subMesh defines the submesh to bind the material to
  36846. */
  36847. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36848. };
  36849. /**
  36850. * Binds the world matrix to the material
  36851. * @param world defines the world transformation matrix
  36852. */
  36853. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36854. };
  36855. /**
  36856. * Binds the scene's uniform buffer to the effect.
  36857. * @param effect defines the effect to bind to the scene uniform buffer
  36858. * @param sceneUbo defines the uniform buffer storing scene data
  36859. */
  36860. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  36861. sceneUbo.bindToEffect(effect, "Scene");
  36862. };
  36863. /**
  36864. * Binds the view matrix to the effect
  36865. * @param effect defines the effect to bind the view matrix to
  36866. */
  36867. Material.prototype.bindView = function (effect) {
  36868. if (!this._useUBO) {
  36869. effect.setMatrix("view", this.getScene().getViewMatrix());
  36870. }
  36871. else {
  36872. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36873. }
  36874. };
  36875. /**
  36876. * Binds the view projection matrix to the effect
  36877. * @param effect defines the effect to bind the view projection matrix to
  36878. */
  36879. Material.prototype.bindViewProjection = function (effect) {
  36880. if (!this._useUBO) {
  36881. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36882. }
  36883. else {
  36884. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36885. }
  36886. };
  36887. /**
  36888. * Specifies if material alpha testing should be turned on for the mesh
  36889. * @param mesh defines the mesh to check
  36890. */
  36891. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  36892. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  36893. };
  36894. /**
  36895. * Processes to execute after binding the material to a mesh
  36896. * @param mesh defines the rendered mesh
  36897. */
  36898. Material.prototype._afterBind = function (mesh) {
  36899. this._scene._cachedMaterial = this;
  36900. if (mesh) {
  36901. this._scene._cachedVisibility = mesh.visibility;
  36902. }
  36903. else {
  36904. this._scene._cachedVisibility = 1;
  36905. }
  36906. if (this._onBindObservable && mesh) {
  36907. this._onBindObservable.notifyObservers(mesh);
  36908. }
  36909. if (this.disableDepthWrite) {
  36910. var engine = this._scene.getEngine();
  36911. this._cachedDepthWriteState = engine.getDepthWrite();
  36912. engine.setDepthWrite(false);
  36913. }
  36914. };
  36915. /**
  36916. * Unbinds the material from the mesh
  36917. */
  36918. Material.prototype.unbind = function () {
  36919. if (this._onUnBindObservable) {
  36920. this._onUnBindObservable.notifyObservers(this);
  36921. }
  36922. if (this.disableDepthWrite) {
  36923. var engine = this._scene.getEngine();
  36924. engine.setDepthWrite(this._cachedDepthWriteState);
  36925. }
  36926. };
  36927. /**
  36928. * Gets the active textures from the material
  36929. * @returns an array of textures
  36930. */
  36931. Material.prototype.getActiveTextures = function () {
  36932. return [];
  36933. };
  36934. /**
  36935. * Specifies if the material uses a texture
  36936. * @param texture defines the texture to check against the material
  36937. * @returns a boolean specifying if the material uses the texture
  36938. */
  36939. Material.prototype.hasTexture = function (texture) {
  36940. return false;
  36941. };
  36942. /**
  36943. * Makes a duplicate of the material, and gives it a new name
  36944. * @param name defines the new name for the duplicated material
  36945. * @returns the cloned material
  36946. */
  36947. Material.prototype.clone = function (name) {
  36948. return null;
  36949. };
  36950. /**
  36951. * Gets the meshes bound to the material
  36952. * @returns an array of meshes bound to the material
  36953. */
  36954. Material.prototype.getBindedMeshes = function () {
  36955. var _this = this;
  36956. if (this.meshMap) {
  36957. var result = new Array();
  36958. for (var meshId in this.meshMap) {
  36959. var mesh = this.meshMap[meshId];
  36960. if (mesh) {
  36961. result.push(mesh);
  36962. }
  36963. }
  36964. return result;
  36965. }
  36966. else {
  36967. var meshes = this._scene.meshes;
  36968. return meshes.filter(function (mesh) { return mesh.material === _this; });
  36969. }
  36970. };
  36971. /**
  36972. * Force shader compilation
  36973. * @param mesh defines the mesh associated with this material
  36974. * @param onCompiled defines a function to execute once the material is compiled
  36975. * @param options defines the options to configure the compilation
  36976. */
  36977. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  36978. var _this = this;
  36979. var localOptions = __assign({ clipPlane: false }, options);
  36980. var subMesh = new BABYLON.BaseSubMesh();
  36981. var scene = this.getScene();
  36982. var checkReady = function () {
  36983. if (!_this._scene || !_this._scene.getEngine()) {
  36984. return;
  36985. }
  36986. if (subMesh._materialDefines) {
  36987. subMesh._materialDefines._renderId = -1;
  36988. }
  36989. var clipPlaneState = scene.clipPlane;
  36990. if (localOptions.clipPlane) {
  36991. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  36992. }
  36993. if (_this._storeEffectOnSubMeshes) {
  36994. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  36995. if (onCompiled) {
  36996. onCompiled(_this);
  36997. }
  36998. }
  36999. else {
  37000. setTimeout(checkReady, 16);
  37001. }
  37002. }
  37003. else {
  37004. if (_this.isReady(mesh)) {
  37005. if (onCompiled) {
  37006. onCompiled(_this);
  37007. }
  37008. }
  37009. else {
  37010. setTimeout(checkReady, 16);
  37011. }
  37012. }
  37013. if (localOptions.clipPlane) {
  37014. scene.clipPlane = clipPlaneState;
  37015. }
  37016. };
  37017. checkReady();
  37018. };
  37019. /**
  37020. * Force shader compilation
  37021. * @param mesh defines the mesh that will use this material
  37022. * @param options defines additional options for compiling the shaders
  37023. * @returns a promise that resolves when the compilation completes
  37024. */
  37025. Material.prototype.forceCompilationAsync = function (mesh, options) {
  37026. var _this = this;
  37027. return new Promise(function (resolve) {
  37028. _this.forceCompilation(mesh, function () {
  37029. resolve();
  37030. }, options);
  37031. });
  37032. };
  37033. /**
  37034. * Marks a define in the material to indicate that it needs to be re-computed
  37035. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  37036. */
  37037. Material.prototype.markAsDirty = function (flag) {
  37038. if (this.getScene().blockMaterialDirtyMechanism) {
  37039. return;
  37040. }
  37041. Material._DirtyCallbackArray.length = 0;
  37042. if (flag & Material.TextureDirtyFlag) {
  37043. Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack);
  37044. }
  37045. if (flag & Material.LightDirtyFlag) {
  37046. Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack);
  37047. }
  37048. if (flag & Material.FresnelDirtyFlag) {
  37049. Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack);
  37050. }
  37051. if (flag & Material.AttributesDirtyFlag) {
  37052. Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack);
  37053. }
  37054. if (flag & Material.MiscDirtyFlag) {
  37055. Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack);
  37056. }
  37057. if (Material._DirtyCallbackArray.length) {
  37058. this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks);
  37059. }
  37060. this.getScene().resetCachedMaterial();
  37061. };
  37062. /**
  37063. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  37064. * @param func defines a function which checks material defines against the submeshes
  37065. */
  37066. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  37067. if (this.getScene().blockMaterialDirtyMechanism) {
  37068. return;
  37069. }
  37070. var meshes = this.getScene().meshes;
  37071. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  37072. var mesh = meshes_1[_i];
  37073. if (!mesh.subMeshes) {
  37074. continue;
  37075. }
  37076. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  37077. var subMesh = _b[_a];
  37078. if (subMesh.getMaterial() !== this) {
  37079. continue;
  37080. }
  37081. if (!subMesh._materialDefines) {
  37082. continue;
  37083. }
  37084. func(subMesh._materialDefines);
  37085. }
  37086. }
  37087. };
  37088. /**
  37089. * Indicates that image processing needs to be re-calculated for all submeshes
  37090. */
  37091. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  37092. this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack);
  37093. };
  37094. /**
  37095. * Indicates that textures need to be re-calculated for all submeshes
  37096. */
  37097. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  37098. this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack);
  37099. };
  37100. /**
  37101. * Indicates that fresnel needs to be re-calculated for all submeshes
  37102. */
  37103. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  37104. this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack);
  37105. };
  37106. /**
  37107. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  37108. */
  37109. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  37110. this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack);
  37111. };
  37112. /**
  37113. * Indicates that lights need to be re-calculated for all submeshes
  37114. */
  37115. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  37116. this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack);
  37117. };
  37118. /**
  37119. * Indicates that attributes need to be re-calculated for all submeshes
  37120. */
  37121. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  37122. this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack);
  37123. };
  37124. /**
  37125. * Indicates that misc needs to be re-calculated for all submeshes
  37126. */
  37127. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  37128. this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);
  37129. };
  37130. /**
  37131. * Indicates that textures and misc need to be re-calculated for all submeshes
  37132. */
  37133. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  37134. this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack);
  37135. };
  37136. /**
  37137. * Disposes the material
  37138. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  37139. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  37140. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  37141. */
  37142. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
  37143. var scene = this.getScene();
  37144. // Animations
  37145. scene.stopAnimation(this);
  37146. scene.freeProcessedMaterials();
  37147. // Remove from scene
  37148. scene.removeMaterial(this);
  37149. if (notBoundToMesh !== true) {
  37150. // Remove from meshes
  37151. if (this.meshMap) {
  37152. for (var meshId in this.meshMap) {
  37153. var mesh = this.meshMap[meshId];
  37154. if (mesh) {
  37155. mesh.material = null; // will set the entry in the map to undefined
  37156. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  37157. }
  37158. }
  37159. }
  37160. else {
  37161. var meshes = scene.meshes;
  37162. for (var _i = 0, meshes_2 = meshes; _i < meshes_2.length; _i++) {
  37163. var mesh = meshes_2[_i];
  37164. if (mesh.material === this) {
  37165. mesh.material = null;
  37166. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  37167. }
  37168. }
  37169. }
  37170. }
  37171. this._uniformBuffer.dispose();
  37172. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  37173. if (forceDisposeEffect && this._effect) {
  37174. if (!this._storeEffectOnSubMeshes) {
  37175. scene.getEngine()._releaseEffect(this._effect);
  37176. }
  37177. this._effect = null;
  37178. }
  37179. // Callback
  37180. this.onDisposeObservable.notifyObservers(this);
  37181. this.onDisposeObservable.clear();
  37182. if (this._onBindObservable) {
  37183. this._onBindObservable.clear();
  37184. }
  37185. if (this._onUnBindObservable) {
  37186. this._onUnBindObservable.clear();
  37187. }
  37188. };
  37189. /** @hidden */
  37190. Material.prototype.releaseVertexArrayObject = function (mesh, forceDisposeEffect) {
  37191. if (mesh.geometry) {
  37192. var geometry = (mesh.geometry);
  37193. var scene = this.getScene();
  37194. if (this._storeEffectOnSubMeshes) {
  37195. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  37196. var subMesh = _a[_i];
  37197. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  37198. if (forceDisposeEffect && subMesh._materialEffect) {
  37199. scene.getEngine()._releaseEffect(subMesh._materialEffect);
  37200. }
  37201. }
  37202. }
  37203. else {
  37204. geometry._releaseVertexArrayObject(this._effect);
  37205. }
  37206. }
  37207. };
  37208. /**
  37209. * Serializes this material
  37210. * @returns the serialized material object
  37211. */
  37212. Material.prototype.serialize = function () {
  37213. return BABYLON.SerializationHelper.Serialize(this);
  37214. };
  37215. /**
  37216. * Creates a MultiMaterial from parsed MultiMaterial data.
  37217. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  37218. * @param scene defines the hosting scene
  37219. * @returns a new MultiMaterial
  37220. */
  37221. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  37222. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  37223. multiMaterial.id = parsedMultiMaterial.id;
  37224. if (BABYLON.Tags) {
  37225. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  37226. }
  37227. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  37228. var subMatId = parsedMultiMaterial.materials[matIndex];
  37229. if (subMatId) {
  37230. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  37231. }
  37232. else {
  37233. multiMaterial.subMaterials.push(null);
  37234. }
  37235. }
  37236. return multiMaterial;
  37237. };
  37238. /**
  37239. * Creates a material from parsed material data
  37240. * @param parsedMaterial defines parsed material data
  37241. * @param scene defines the hosting scene
  37242. * @param rootUrl defines the root URL to use to load textures
  37243. * @returns a new material
  37244. */
  37245. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  37246. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  37247. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  37248. }
  37249. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  37250. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  37251. if (!BABYLON.LegacyPBRMaterial) {
  37252. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  37253. return;
  37254. }
  37255. }
  37256. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  37257. return materialType.Parse(parsedMaterial, scene, rootUrl);
  37258. };
  37259. // Triangle views
  37260. Material._TriangleFillMode = 0;
  37261. Material._WireFrameFillMode = 1;
  37262. Material._PointFillMode = 2;
  37263. // Draw modes
  37264. Material._PointListDrawMode = 3;
  37265. Material._LineListDrawMode = 4;
  37266. Material._LineLoopDrawMode = 5;
  37267. Material._LineStripDrawMode = 6;
  37268. Material._TriangleStripDrawMode = 7;
  37269. Material._TriangleFanDrawMode = 8;
  37270. /**
  37271. * Stores the clock-wise side orientation
  37272. */
  37273. Material._ClockWiseSideOrientation = 0;
  37274. /**
  37275. * Stores the counter clock-wise side orientation
  37276. */
  37277. Material._CounterClockWiseSideOrientation = 1;
  37278. /**
  37279. * The dirty texture flag value
  37280. */
  37281. Material.TextureDirtyFlag = 1;
  37282. /**
  37283. * The dirty light flag value
  37284. */
  37285. Material.LightDirtyFlag = 2;
  37286. /**
  37287. * The dirty fresnel flag value
  37288. */
  37289. Material.FresnelDirtyFlag = 4;
  37290. /**
  37291. * The dirty attribute flag value
  37292. */
  37293. Material.AttributesDirtyFlag = 8;
  37294. /**
  37295. * The dirty misc flag value
  37296. */
  37297. Material.MiscDirtyFlag = 16;
  37298. /**
  37299. * The all dirty flag value
  37300. */
  37301. Material.AllDirtyFlag = 31;
  37302. Material._ImageProcessingDirtyCallBack = function (defines) { return defines.markAsImageProcessingDirty(); };
  37303. Material._TextureDirtyCallBack = function (defines) { return defines.markAsTexturesDirty(); };
  37304. Material._FresnelDirtyCallBack = function (defines) { return defines.markAsFresnelDirty(); };
  37305. Material._MiscDirtyCallBack = function (defines) { return defines.markAsMiscDirty(); };
  37306. Material._LightsDirtyCallBack = function (defines) { return defines.markAsLightDirty(); };
  37307. Material._AttributeDirtyCallBack = function (defines) { return defines.markAsAttributesDirty(); };
  37308. Material._FresnelAndMiscDirtyCallBack = function (defines) {
  37309. Material._FresnelDirtyCallBack(defines);
  37310. Material._MiscDirtyCallBack(defines);
  37311. };
  37312. Material._TextureAndMiscDirtyCallBack = function (defines) {
  37313. Material._TextureDirtyCallBack(defines);
  37314. Material._MiscDirtyCallBack(defines);
  37315. };
  37316. Material._DirtyCallbackArray = [];
  37317. Material._RunDirtyCallBacks = function (defines) {
  37318. for (var _i = 0, _a = Material._DirtyCallbackArray; _i < _a.length; _i++) {
  37319. var cb = _a[_i];
  37320. cb(defines);
  37321. }
  37322. };
  37323. __decorate([
  37324. BABYLON.serialize()
  37325. ], Material.prototype, "id", void 0);
  37326. __decorate([
  37327. BABYLON.serialize()
  37328. ], Material.prototype, "uniqueId", void 0);
  37329. __decorate([
  37330. BABYLON.serialize()
  37331. ], Material.prototype, "name", void 0);
  37332. __decorate([
  37333. BABYLON.serialize()
  37334. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  37335. __decorate([
  37336. BABYLON.serialize()
  37337. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  37338. __decorate([
  37339. BABYLON.serialize()
  37340. ], Material.prototype, "state", void 0);
  37341. __decorate([
  37342. BABYLON.serialize("alpha")
  37343. ], Material.prototype, "_alpha", void 0);
  37344. __decorate([
  37345. BABYLON.serialize("backFaceCulling")
  37346. ], Material.prototype, "_backFaceCulling", void 0);
  37347. __decorate([
  37348. BABYLON.serialize()
  37349. ], Material.prototype, "sideOrientation", void 0);
  37350. __decorate([
  37351. BABYLON.serialize("alphaMode")
  37352. ], Material.prototype, "_alphaMode", void 0);
  37353. __decorate([
  37354. BABYLON.serialize()
  37355. ], Material.prototype, "_needDepthPrePass", void 0);
  37356. __decorate([
  37357. BABYLON.serialize()
  37358. ], Material.prototype, "disableDepthWrite", void 0);
  37359. __decorate([
  37360. BABYLON.serialize()
  37361. ], Material.prototype, "forceDepthWrite", void 0);
  37362. __decorate([
  37363. BABYLON.serialize()
  37364. ], Material.prototype, "separateCullingPass", void 0);
  37365. __decorate([
  37366. BABYLON.serialize("fogEnabled")
  37367. ], Material.prototype, "_fogEnabled", void 0);
  37368. __decorate([
  37369. BABYLON.serialize()
  37370. ], Material.prototype, "pointSize", void 0);
  37371. __decorate([
  37372. BABYLON.serialize()
  37373. ], Material.prototype, "zOffset", void 0);
  37374. __decorate([
  37375. BABYLON.serialize()
  37376. ], Material.prototype, "wireframe", null);
  37377. __decorate([
  37378. BABYLON.serialize()
  37379. ], Material.prototype, "pointsCloud", null);
  37380. __decorate([
  37381. BABYLON.serialize()
  37382. ], Material.prototype, "fillMode", null);
  37383. return Material;
  37384. }());
  37385. BABYLON.Material = Material;
  37386. })(BABYLON || (BABYLON = {}));
  37387. //# sourceMappingURL=babylon.material.js.map
  37388. var BABYLON;
  37389. (function (BABYLON) {
  37390. /**
  37391. * Uniform buffer objects.
  37392. *
  37393. * Handles blocks of uniform on the GPU.
  37394. *
  37395. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37396. *
  37397. * For more information, please refer to :
  37398. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37399. */
  37400. var UniformBuffer = /** @class */ (function () {
  37401. /**
  37402. * Instantiates a new Uniform buffer objects.
  37403. *
  37404. * Handles blocks of uniform on the GPU.
  37405. *
  37406. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37407. *
  37408. * For more information, please refer to :
  37409. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37410. * @param engine Define the engine the buffer is associated with
  37411. * @param data Define the data contained in the buffer
  37412. * @param dynamic Define if the buffer is updatable
  37413. */
  37414. function UniformBuffer(engine, data, dynamic) {
  37415. this._engine = engine;
  37416. this._noUBO = !engine.supportsUniformBuffers;
  37417. this._dynamic = dynamic;
  37418. this._data = data || [];
  37419. this._uniformLocations = {};
  37420. this._uniformSizes = {};
  37421. this._uniformLocationPointer = 0;
  37422. this._needSync = false;
  37423. if (this._noUBO) {
  37424. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  37425. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  37426. this.updateFloat = this._updateFloatForEffect;
  37427. this.updateFloat2 = this._updateFloat2ForEffect;
  37428. this.updateFloat3 = this._updateFloat3ForEffect;
  37429. this.updateFloat4 = this._updateFloat4ForEffect;
  37430. this.updateMatrix = this._updateMatrixForEffect;
  37431. this.updateVector3 = this._updateVector3ForEffect;
  37432. this.updateVector4 = this._updateVector4ForEffect;
  37433. this.updateColor3 = this._updateColor3ForEffect;
  37434. this.updateColor4 = this._updateColor4ForEffect;
  37435. }
  37436. else {
  37437. this._engine._uniformBuffers.push(this);
  37438. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  37439. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  37440. this.updateFloat = this._updateFloatForUniform;
  37441. this.updateFloat2 = this._updateFloat2ForUniform;
  37442. this.updateFloat3 = this._updateFloat3ForUniform;
  37443. this.updateFloat4 = this._updateFloat4ForUniform;
  37444. this.updateMatrix = this._updateMatrixForUniform;
  37445. this.updateVector3 = this._updateVector3ForUniform;
  37446. this.updateVector4 = this._updateVector4ForUniform;
  37447. this.updateColor3 = this._updateColor3ForUniform;
  37448. this.updateColor4 = this._updateColor4ForUniform;
  37449. }
  37450. }
  37451. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  37452. /**
  37453. * Indicates if the buffer is using the WebGL2 UBO implementation,
  37454. * or just falling back on setUniformXXX calls.
  37455. */
  37456. get: function () {
  37457. return !this._noUBO;
  37458. },
  37459. enumerable: true,
  37460. configurable: true
  37461. });
  37462. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  37463. /**
  37464. * Indicates if the WebGL underlying uniform buffer is in sync
  37465. * with the javascript cache data.
  37466. */
  37467. get: function () {
  37468. return !this._needSync;
  37469. },
  37470. enumerable: true,
  37471. configurable: true
  37472. });
  37473. /**
  37474. * Indicates if the WebGL underlying uniform buffer is dynamic.
  37475. * Also, a dynamic UniformBuffer will disable cache verification and always
  37476. * update the underlying WebGL uniform buffer to the GPU.
  37477. * @returns if Dynamic, otherwise false
  37478. */
  37479. UniformBuffer.prototype.isDynamic = function () {
  37480. return this._dynamic !== undefined;
  37481. };
  37482. /**
  37483. * The data cache on JS side.
  37484. * @returns the underlying data as a float array
  37485. */
  37486. UniformBuffer.prototype.getData = function () {
  37487. return this._bufferData;
  37488. };
  37489. /**
  37490. * The underlying WebGL Uniform buffer.
  37491. * @returns the webgl buffer
  37492. */
  37493. UniformBuffer.prototype.getBuffer = function () {
  37494. return this._buffer;
  37495. };
  37496. /**
  37497. * std140 layout specifies how to align data within an UBO structure.
  37498. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  37499. * for specs.
  37500. */
  37501. UniformBuffer.prototype._fillAlignment = function (size) {
  37502. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  37503. // and 4x4 matrices
  37504. // TODO : change if other types are used
  37505. var alignment;
  37506. if (size <= 2) {
  37507. alignment = size;
  37508. }
  37509. else {
  37510. alignment = 4;
  37511. }
  37512. if ((this._uniformLocationPointer % alignment) !== 0) {
  37513. var oldPointer = this._uniformLocationPointer;
  37514. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  37515. var diff = this._uniformLocationPointer - oldPointer;
  37516. for (var i = 0; i < diff; i++) {
  37517. this._data.push(0);
  37518. }
  37519. }
  37520. };
  37521. /**
  37522. * Adds an uniform in the buffer.
  37523. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  37524. * for the layout to be correct !
  37525. * @param name Name of the uniform, as used in the uniform block in the shader.
  37526. * @param size Data size, or data directly.
  37527. */
  37528. UniformBuffer.prototype.addUniform = function (name, size) {
  37529. if (this._noUBO) {
  37530. return;
  37531. }
  37532. if (this._uniformLocations[name] !== undefined) {
  37533. // Already existing uniform
  37534. return;
  37535. }
  37536. // This function must be called in the order of the shader layout !
  37537. // size can be the size of the uniform, or data directly
  37538. var data;
  37539. if (size instanceof Array) {
  37540. data = size;
  37541. size = data.length;
  37542. }
  37543. else {
  37544. size = size;
  37545. data = [];
  37546. // Fill with zeros
  37547. for (var i = 0; i < size; i++) {
  37548. data.push(0);
  37549. }
  37550. }
  37551. this._fillAlignment(size);
  37552. this._uniformSizes[name] = size;
  37553. this._uniformLocations[name] = this._uniformLocationPointer;
  37554. this._uniformLocationPointer += size;
  37555. for (var i = 0; i < size; i++) {
  37556. this._data.push(data[i]);
  37557. }
  37558. this._needSync = true;
  37559. };
  37560. /**
  37561. * Adds a Matrix 4x4 to the uniform buffer.
  37562. * @param name Name of the uniform, as used in the uniform block in the shader.
  37563. * @param mat A 4x4 matrix.
  37564. */
  37565. UniformBuffer.prototype.addMatrix = function (name, mat) {
  37566. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  37567. };
  37568. /**
  37569. * Adds a vec2 to the uniform buffer.
  37570. * @param name Name of the uniform, as used in the uniform block in the shader.
  37571. * @param x Define the x component value of the vec2
  37572. * @param y Define the y component value of the vec2
  37573. */
  37574. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  37575. var temp = [x, y];
  37576. this.addUniform(name, temp);
  37577. };
  37578. /**
  37579. * Adds a vec3 to the uniform buffer.
  37580. * @param name Name of the uniform, as used in the uniform block in the shader.
  37581. * @param x Define the x component value of the vec3
  37582. * @param y Define the y component value of the vec3
  37583. * @param z Define the z component value of the vec3
  37584. */
  37585. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  37586. var temp = [x, y, z];
  37587. this.addUniform(name, temp);
  37588. };
  37589. /**
  37590. * Adds a vec3 to the uniform buffer.
  37591. * @param name Name of the uniform, as used in the uniform block in the shader.
  37592. * @param color Define the vec3 from a Color
  37593. */
  37594. UniformBuffer.prototype.addColor3 = function (name, color) {
  37595. var temp = new Array();
  37596. color.toArray(temp);
  37597. this.addUniform(name, temp);
  37598. };
  37599. /**
  37600. * Adds a vec4 to the uniform buffer.
  37601. * @param name Name of the uniform, as used in the uniform block in the shader.
  37602. * @param color Define the rgb components from a Color
  37603. * @param alpha Define the a component of the vec4
  37604. */
  37605. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  37606. var temp = new Array();
  37607. color.toArray(temp);
  37608. temp.push(alpha);
  37609. this.addUniform(name, temp);
  37610. };
  37611. /**
  37612. * Adds a vec3 to the uniform buffer.
  37613. * @param name Name of the uniform, as used in the uniform block in the shader.
  37614. * @param vector Define the vec3 components from a Vector
  37615. */
  37616. UniformBuffer.prototype.addVector3 = function (name, vector) {
  37617. var temp = new Array();
  37618. vector.toArray(temp);
  37619. this.addUniform(name, temp);
  37620. };
  37621. /**
  37622. * Adds a Matrix 3x3 to the uniform buffer.
  37623. * @param name Name of the uniform, as used in the uniform block in the shader.
  37624. */
  37625. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  37626. this.addUniform(name, 12);
  37627. };
  37628. /**
  37629. * Adds a Matrix 2x2 to the uniform buffer.
  37630. * @param name Name of the uniform, as used in the uniform block in the shader.
  37631. */
  37632. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  37633. this.addUniform(name, 8);
  37634. };
  37635. /**
  37636. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  37637. */
  37638. UniformBuffer.prototype.create = function () {
  37639. if (this._noUBO) {
  37640. return;
  37641. }
  37642. if (this._buffer) {
  37643. return; // nothing to do
  37644. }
  37645. // See spec, alignment must be filled as a vec4
  37646. this._fillAlignment(4);
  37647. this._bufferData = new Float32Array(this._data);
  37648. this._rebuild();
  37649. this._needSync = true;
  37650. };
  37651. /** @hidden */
  37652. UniformBuffer.prototype._rebuild = function () {
  37653. if (this._noUBO) {
  37654. return;
  37655. }
  37656. if (this._dynamic) {
  37657. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  37658. }
  37659. else {
  37660. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  37661. }
  37662. };
  37663. /**
  37664. * Updates the WebGL Uniform Buffer on the GPU.
  37665. * If the `dynamic` flag is set to true, no cache comparison is done.
  37666. * Otherwise, the buffer will be updated only if the cache differs.
  37667. */
  37668. UniformBuffer.prototype.update = function () {
  37669. if (!this._buffer) {
  37670. this.create();
  37671. return;
  37672. }
  37673. if (!this._dynamic && !this._needSync) {
  37674. return;
  37675. }
  37676. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  37677. this._needSync = false;
  37678. };
  37679. /**
  37680. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  37681. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37682. * @param data Define the flattened data
  37683. * @param size Define the size of the data.
  37684. */
  37685. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  37686. var location = this._uniformLocations[uniformName];
  37687. if (location === undefined) {
  37688. if (this._buffer) {
  37689. // Cannot add an uniform if the buffer is already created
  37690. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  37691. return;
  37692. }
  37693. this.addUniform(uniformName, size);
  37694. location = this._uniformLocations[uniformName];
  37695. }
  37696. if (!this._buffer) {
  37697. this.create();
  37698. }
  37699. if (!this._dynamic) {
  37700. // Cache for static uniform buffers
  37701. var changed = false;
  37702. for (var i = 0; i < size; i++) {
  37703. if (this._bufferData[location + i] !== data[i]) {
  37704. changed = true;
  37705. this._bufferData[location + i] = data[i];
  37706. }
  37707. }
  37708. this._needSync = this._needSync || changed;
  37709. }
  37710. else {
  37711. // No cache for dynamic
  37712. for (var i = 0; i < size; i++) {
  37713. this._bufferData[location + i] = data[i];
  37714. }
  37715. }
  37716. };
  37717. // Update methods
  37718. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  37719. // To match std140, matrix must be realigned
  37720. for (var i = 0; i < 3; i++) {
  37721. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  37722. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  37723. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  37724. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37725. }
  37726. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  37727. };
  37728. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  37729. this._currentEffect.setMatrix3x3(name, matrix);
  37730. };
  37731. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  37732. this._currentEffect.setMatrix2x2(name, matrix);
  37733. };
  37734. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  37735. // To match std140, matrix must be realigned
  37736. for (var i = 0; i < 2; i++) {
  37737. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  37738. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  37739. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  37740. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37741. }
  37742. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  37743. };
  37744. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  37745. this._currentEffect.setFloat(name, x);
  37746. };
  37747. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  37748. UniformBuffer._tempBuffer[0] = x;
  37749. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  37750. };
  37751. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  37752. if (suffix === void 0) { suffix = ""; }
  37753. this._currentEffect.setFloat2(name + suffix, x, y);
  37754. };
  37755. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  37756. if (suffix === void 0) { suffix = ""; }
  37757. UniformBuffer._tempBuffer[0] = x;
  37758. UniformBuffer._tempBuffer[1] = y;
  37759. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  37760. };
  37761. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  37762. if (suffix === void 0) { suffix = ""; }
  37763. this._currentEffect.setFloat3(name + suffix, x, y, z);
  37764. };
  37765. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  37766. if (suffix === void 0) { suffix = ""; }
  37767. UniformBuffer._tempBuffer[0] = x;
  37768. UniformBuffer._tempBuffer[1] = y;
  37769. UniformBuffer._tempBuffer[2] = z;
  37770. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37771. };
  37772. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  37773. if (suffix === void 0) { suffix = ""; }
  37774. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  37775. };
  37776. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  37777. if (suffix === void 0) { suffix = ""; }
  37778. UniformBuffer._tempBuffer[0] = x;
  37779. UniformBuffer._tempBuffer[1] = y;
  37780. UniformBuffer._tempBuffer[2] = z;
  37781. UniformBuffer._tempBuffer[3] = w;
  37782. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37783. };
  37784. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  37785. this._currentEffect.setMatrix(name, mat);
  37786. };
  37787. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  37788. this.updateUniform(name, mat.toArray(), 16);
  37789. };
  37790. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  37791. this._currentEffect.setVector3(name, vector);
  37792. };
  37793. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  37794. vector.toArray(UniformBuffer._tempBuffer);
  37795. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37796. };
  37797. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  37798. this._currentEffect.setVector4(name, vector);
  37799. };
  37800. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37801. vector.toArray(UniformBuffer._tempBuffer);
  37802. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37803. };
  37804. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37805. if (suffix === void 0) { suffix = ""; }
  37806. this._currentEffect.setColor3(name + suffix, color);
  37807. };
  37808. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37809. if (suffix === void 0) { suffix = ""; }
  37810. color.toArray(UniformBuffer._tempBuffer);
  37811. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37812. };
  37813. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37814. if (suffix === void 0) { suffix = ""; }
  37815. this._currentEffect.setColor4(name + suffix, color, alpha);
  37816. };
  37817. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37818. if (suffix === void 0) { suffix = ""; }
  37819. color.toArray(UniformBuffer._tempBuffer);
  37820. UniformBuffer._tempBuffer[3] = alpha;
  37821. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37822. };
  37823. /**
  37824. * Sets a sampler uniform on the effect.
  37825. * @param name Define the name of the sampler.
  37826. * @param texture Define the texture to set in the sampler
  37827. */
  37828. UniformBuffer.prototype.setTexture = function (name, texture) {
  37829. this._currentEffect.setTexture(name, texture);
  37830. };
  37831. /**
  37832. * Directly updates the value of the uniform in the cache AND on the GPU.
  37833. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37834. * @param data Define the flattened data
  37835. */
  37836. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37837. this.updateUniform(uniformName, data, data.length);
  37838. this.update();
  37839. };
  37840. /**
  37841. * Binds this uniform buffer to an effect.
  37842. * @param effect Define the effect to bind the buffer to
  37843. * @param name Name of the uniform block in the shader.
  37844. */
  37845. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37846. this._currentEffect = effect;
  37847. if (this._noUBO || !this._buffer) {
  37848. return;
  37849. }
  37850. effect.bindUniformBuffer(this._buffer, name);
  37851. };
  37852. /**
  37853. * Disposes the uniform buffer.
  37854. */
  37855. UniformBuffer.prototype.dispose = function () {
  37856. if (this._noUBO) {
  37857. return;
  37858. }
  37859. var uniformBuffers = this._engine._uniformBuffers;
  37860. var index = uniformBuffers.indexOf(this);
  37861. if (index !== -1) {
  37862. uniformBuffers[index] = uniformBuffers[uniformBuffers.length - 1];
  37863. uniformBuffers.pop();
  37864. }
  37865. if (!this._buffer) {
  37866. return;
  37867. }
  37868. if (this._engine._releaseBuffer(this._buffer)) {
  37869. this._buffer = null;
  37870. }
  37871. };
  37872. // Pool for avoiding memory leaks
  37873. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37874. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37875. return UniformBuffer;
  37876. }());
  37877. BABYLON.UniformBuffer = UniformBuffer;
  37878. })(BABYLON || (BABYLON = {}));
  37879. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37880. var BABYLON;
  37881. (function (BABYLON) {
  37882. /**
  37883. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  37884. */
  37885. var VertexData = /** @class */ (function () {
  37886. function VertexData() {
  37887. }
  37888. /**
  37889. * Uses the passed data array to set the set the values for the specified kind of data
  37890. * @param data a linear array of floating numbers
  37891. * @param kind the type of data that is being set, eg positions, colors etc
  37892. */
  37893. VertexData.prototype.set = function (data, kind) {
  37894. switch (kind) {
  37895. case BABYLON.VertexBuffer.PositionKind:
  37896. this.positions = data;
  37897. break;
  37898. case BABYLON.VertexBuffer.NormalKind:
  37899. this.normals = data;
  37900. break;
  37901. case BABYLON.VertexBuffer.TangentKind:
  37902. this.tangents = data;
  37903. break;
  37904. case BABYLON.VertexBuffer.UVKind:
  37905. this.uvs = data;
  37906. break;
  37907. case BABYLON.VertexBuffer.UV2Kind:
  37908. this.uvs2 = data;
  37909. break;
  37910. case BABYLON.VertexBuffer.UV3Kind:
  37911. this.uvs3 = data;
  37912. break;
  37913. case BABYLON.VertexBuffer.UV4Kind:
  37914. this.uvs4 = data;
  37915. break;
  37916. case BABYLON.VertexBuffer.UV5Kind:
  37917. this.uvs5 = data;
  37918. break;
  37919. case BABYLON.VertexBuffer.UV6Kind:
  37920. this.uvs6 = data;
  37921. break;
  37922. case BABYLON.VertexBuffer.ColorKind:
  37923. this.colors = data;
  37924. break;
  37925. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37926. this.matricesIndices = data;
  37927. break;
  37928. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37929. this.matricesWeights = data;
  37930. break;
  37931. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37932. this.matricesIndicesExtra = data;
  37933. break;
  37934. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37935. this.matricesWeightsExtra = data;
  37936. break;
  37937. }
  37938. };
  37939. /**
  37940. * Associates the vertexData to the passed Mesh.
  37941. * Sets it as updatable or not (default `false`)
  37942. * @param mesh the mesh the vertexData is applied to
  37943. * @param updatable when used and having the value true allows new data to update the vertexData
  37944. * @returns the VertexData
  37945. */
  37946. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37947. this._applyTo(mesh, updatable);
  37948. return this;
  37949. };
  37950. /**
  37951. * Associates the vertexData to the passed Geometry.
  37952. * Sets it as updatable or not (default `false`)
  37953. * @param geometry the geometry the vertexData is applied to
  37954. * @param updatable when used and having the value true allows new data to update the vertexData
  37955. * @returns VertexData
  37956. */
  37957. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  37958. this._applyTo(geometry, updatable);
  37959. return this;
  37960. };
  37961. /**
  37962. * Updates the associated mesh
  37963. * @param mesh the mesh to be updated
  37964. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37965. * @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
  37966. * @returns VertexData
  37967. */
  37968. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  37969. this._update(mesh);
  37970. return this;
  37971. };
  37972. /**
  37973. * Updates the associated geometry
  37974. * @param geometry the geometry to be updated
  37975. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37976. * @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
  37977. * @returns VertexData.
  37978. */
  37979. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  37980. this._update(geometry);
  37981. return this;
  37982. };
  37983. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  37984. if (updatable === void 0) { updatable = false; }
  37985. if (this.positions) {
  37986. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  37987. }
  37988. if (this.normals) {
  37989. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  37990. }
  37991. if (this.tangents) {
  37992. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  37993. }
  37994. if (this.uvs) {
  37995. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  37996. }
  37997. if (this.uvs2) {
  37998. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  37999. }
  38000. if (this.uvs3) {
  38001. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  38002. }
  38003. if (this.uvs4) {
  38004. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  38005. }
  38006. if (this.uvs5) {
  38007. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  38008. }
  38009. if (this.uvs6) {
  38010. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  38011. }
  38012. if (this.colors) {
  38013. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  38014. }
  38015. if (this.matricesIndices) {
  38016. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  38017. }
  38018. if (this.matricesWeights) {
  38019. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  38020. }
  38021. if (this.matricesIndicesExtra) {
  38022. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  38023. }
  38024. if (this.matricesWeightsExtra) {
  38025. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  38026. }
  38027. if (this.indices) {
  38028. meshOrGeometry.setIndices(this.indices, null, updatable);
  38029. }
  38030. else {
  38031. meshOrGeometry.setIndices([], null);
  38032. }
  38033. return this;
  38034. };
  38035. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  38036. if (this.positions) {
  38037. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  38038. }
  38039. if (this.normals) {
  38040. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  38041. }
  38042. if (this.tangents) {
  38043. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  38044. }
  38045. if (this.uvs) {
  38046. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  38047. }
  38048. if (this.uvs2) {
  38049. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  38050. }
  38051. if (this.uvs3) {
  38052. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  38053. }
  38054. if (this.uvs4) {
  38055. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  38056. }
  38057. if (this.uvs5) {
  38058. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  38059. }
  38060. if (this.uvs6) {
  38061. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  38062. }
  38063. if (this.colors) {
  38064. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  38065. }
  38066. if (this.matricesIndices) {
  38067. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  38068. }
  38069. if (this.matricesWeights) {
  38070. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  38071. }
  38072. if (this.matricesIndicesExtra) {
  38073. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  38074. }
  38075. if (this.matricesWeightsExtra) {
  38076. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  38077. }
  38078. if (this.indices) {
  38079. meshOrGeometry.setIndices(this.indices, null);
  38080. }
  38081. return this;
  38082. };
  38083. /**
  38084. * Transforms each position and each normal of the vertexData according to the passed Matrix
  38085. * @param matrix the transforming matrix
  38086. * @returns the VertexData
  38087. */
  38088. VertexData.prototype.transform = function (matrix) {
  38089. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  38090. var transformed = BABYLON.Vector3.Zero();
  38091. var index;
  38092. if (this.positions) {
  38093. var position = BABYLON.Vector3.Zero();
  38094. for (index = 0; index < this.positions.length; index += 3) {
  38095. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  38096. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  38097. this.positions[index] = transformed.x;
  38098. this.positions[index + 1] = transformed.y;
  38099. this.positions[index + 2] = transformed.z;
  38100. }
  38101. }
  38102. if (this.normals) {
  38103. var normal = BABYLON.Vector3.Zero();
  38104. for (index = 0; index < this.normals.length; index += 3) {
  38105. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  38106. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  38107. this.normals[index] = transformed.x;
  38108. this.normals[index + 1] = transformed.y;
  38109. this.normals[index + 2] = transformed.z;
  38110. }
  38111. }
  38112. if (this.tangents) {
  38113. var tangent = BABYLON.Vector4.Zero();
  38114. var tangentTransformed = BABYLON.Vector4.Zero();
  38115. for (index = 0; index < this.tangents.length; index += 4) {
  38116. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  38117. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  38118. this.tangents[index] = tangentTransformed.x;
  38119. this.tangents[index + 1] = tangentTransformed.y;
  38120. this.tangents[index + 2] = tangentTransformed.z;
  38121. this.tangents[index + 3] = tangentTransformed.w;
  38122. }
  38123. }
  38124. if (flip && this.indices) {
  38125. for (index = 0; index < this.indices.length; index += 3) {
  38126. var tmp = this.indices[index + 1];
  38127. this.indices[index + 1] = this.indices[index + 2];
  38128. this.indices[index + 2] = tmp;
  38129. }
  38130. }
  38131. return this;
  38132. };
  38133. /**
  38134. * Merges the passed VertexData into the current one
  38135. * @param other the VertexData to be merged into the current one
  38136. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  38137. * @returns the modified VertexData
  38138. */
  38139. VertexData.prototype.merge = function (other, use32BitsIndices) {
  38140. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  38141. this._validate();
  38142. other._validate();
  38143. if (!this.normals !== !other.normals ||
  38144. !this.tangents !== !other.tangents ||
  38145. !this.uvs !== !other.uvs ||
  38146. !this.uvs2 !== !other.uvs2 ||
  38147. !this.uvs3 !== !other.uvs3 ||
  38148. !this.uvs4 !== !other.uvs4 ||
  38149. !this.uvs5 !== !other.uvs5 ||
  38150. !this.uvs6 !== !other.uvs6 ||
  38151. !this.colors !== !other.colors ||
  38152. !this.matricesIndices !== !other.matricesIndices ||
  38153. !this.matricesWeights !== !other.matricesWeights ||
  38154. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  38155. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  38156. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  38157. }
  38158. if (other.indices) {
  38159. if (!this.indices) {
  38160. this.indices = [];
  38161. }
  38162. var offset = this.positions ? this.positions.length / 3 : 0;
  38163. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  38164. if (isSrcTypedArray) {
  38165. var len = this.indices.length + other.indices.length;
  38166. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  38167. temp.set(this.indices);
  38168. var decal = this.indices.length;
  38169. for (var index = 0; index < other.indices.length; index++) {
  38170. temp[decal + index] = other.indices[index] + offset;
  38171. }
  38172. this.indices = temp;
  38173. }
  38174. else {
  38175. for (var index = 0; index < other.indices.length; index++) {
  38176. this.indices.push(other.indices[index] + offset);
  38177. }
  38178. }
  38179. }
  38180. this.positions = this._mergeElement(this.positions, other.positions);
  38181. this.normals = this._mergeElement(this.normals, other.normals);
  38182. this.tangents = this._mergeElement(this.tangents, other.tangents);
  38183. this.uvs = this._mergeElement(this.uvs, other.uvs);
  38184. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  38185. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  38186. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  38187. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  38188. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  38189. this.colors = this._mergeElement(this.colors, other.colors);
  38190. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  38191. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  38192. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  38193. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  38194. return this;
  38195. };
  38196. VertexData.prototype._mergeElement = function (source, other) {
  38197. if (!source) {
  38198. return other;
  38199. }
  38200. if (!other) {
  38201. return source;
  38202. }
  38203. var len = other.length + source.length;
  38204. var isSrcTypedArray = source instanceof Float32Array;
  38205. var isOthTypedArray = other instanceof Float32Array;
  38206. // use non-loop method when the source is Float32Array
  38207. if (isSrcTypedArray) {
  38208. var ret32 = new Float32Array(len);
  38209. ret32.set(source);
  38210. ret32.set(other, source.length);
  38211. return ret32;
  38212. // source is number[], when other is also use concat
  38213. }
  38214. else if (!isOthTypedArray) {
  38215. return source.concat(other);
  38216. // source is a number[], but other is a Float32Array, loop required
  38217. }
  38218. else {
  38219. var ret = source.slice(0); // copy source to a separate array
  38220. for (var i = 0, len = other.length; i < len; i++) {
  38221. ret.push(other[i]);
  38222. }
  38223. return ret;
  38224. }
  38225. };
  38226. VertexData.prototype._validate = function () {
  38227. if (!this.positions) {
  38228. throw new Error("Positions are required");
  38229. }
  38230. var getElementCount = function (kind, values) {
  38231. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  38232. if ((values.length % stride) !== 0) {
  38233. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  38234. }
  38235. return values.length / stride;
  38236. };
  38237. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  38238. var validateElementCount = function (kind, values) {
  38239. var elementCount = getElementCount(kind, values);
  38240. if (elementCount !== positionsElementCount) {
  38241. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  38242. }
  38243. };
  38244. if (this.normals) {
  38245. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  38246. }
  38247. if (this.tangents) {
  38248. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  38249. }
  38250. if (this.uvs) {
  38251. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  38252. }
  38253. if (this.uvs2) {
  38254. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  38255. }
  38256. if (this.uvs3) {
  38257. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  38258. }
  38259. if (this.uvs4) {
  38260. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  38261. }
  38262. if (this.uvs5) {
  38263. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  38264. }
  38265. if (this.uvs6) {
  38266. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  38267. }
  38268. if (this.colors) {
  38269. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  38270. }
  38271. if (this.matricesIndices) {
  38272. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  38273. }
  38274. if (this.matricesWeights) {
  38275. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  38276. }
  38277. if (this.matricesIndicesExtra) {
  38278. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  38279. }
  38280. if (this.matricesWeightsExtra) {
  38281. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  38282. }
  38283. };
  38284. /**
  38285. * Serializes the VertexData
  38286. * @returns a serialized object
  38287. */
  38288. VertexData.prototype.serialize = function () {
  38289. var serializationObject = this.serialize();
  38290. if (this.positions) {
  38291. serializationObject.positions = this.positions;
  38292. }
  38293. if (this.normals) {
  38294. serializationObject.normals = this.normals;
  38295. }
  38296. if (this.tangents) {
  38297. serializationObject.tangents = this.tangents;
  38298. }
  38299. if (this.uvs) {
  38300. serializationObject.uvs = this.uvs;
  38301. }
  38302. if (this.uvs2) {
  38303. serializationObject.uvs2 = this.uvs2;
  38304. }
  38305. if (this.uvs3) {
  38306. serializationObject.uvs3 = this.uvs3;
  38307. }
  38308. if (this.uvs4) {
  38309. serializationObject.uvs4 = this.uvs4;
  38310. }
  38311. if (this.uvs5) {
  38312. serializationObject.uvs5 = this.uvs5;
  38313. }
  38314. if (this.uvs6) {
  38315. serializationObject.uvs6 = this.uvs6;
  38316. }
  38317. if (this.colors) {
  38318. serializationObject.colors = this.colors;
  38319. }
  38320. if (this.matricesIndices) {
  38321. serializationObject.matricesIndices = this.matricesIndices;
  38322. serializationObject.matricesIndices._isExpanded = true;
  38323. }
  38324. if (this.matricesWeights) {
  38325. serializationObject.matricesWeights = this.matricesWeights;
  38326. }
  38327. if (this.matricesIndicesExtra) {
  38328. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  38329. serializationObject.matricesIndicesExtra._isExpanded = true;
  38330. }
  38331. if (this.matricesWeightsExtra) {
  38332. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  38333. }
  38334. serializationObject.indices = this.indices;
  38335. return serializationObject;
  38336. };
  38337. // Statics
  38338. /**
  38339. * Extracts the vertexData from a mesh
  38340. * @param mesh the mesh from which to extract the VertexData
  38341. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  38342. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38343. * @returns the object VertexData associated to the passed mesh
  38344. */
  38345. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  38346. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  38347. };
  38348. /**
  38349. * Extracts the vertexData from the geometry
  38350. * @param geometry the geometry from which to extract the VertexData
  38351. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  38352. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38353. * @returns the object VertexData associated to the passed mesh
  38354. */
  38355. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  38356. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  38357. };
  38358. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  38359. var result = new VertexData();
  38360. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38361. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  38362. }
  38363. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38364. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  38365. }
  38366. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38367. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  38368. }
  38369. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38370. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  38371. }
  38372. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38373. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  38374. }
  38375. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38376. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  38377. }
  38378. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38379. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  38380. }
  38381. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38382. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  38383. }
  38384. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38385. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  38386. }
  38387. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38388. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  38389. }
  38390. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38391. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  38392. }
  38393. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38394. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  38395. }
  38396. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38397. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  38398. }
  38399. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38400. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  38401. }
  38402. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  38403. return result;
  38404. };
  38405. /**
  38406. * Creates the VertexData for a Ribbon
  38407. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  38408. * * pathArray array of paths, each of which an array of successive Vector3
  38409. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  38410. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  38411. * * 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
  38412. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38413. * * 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)
  38414. * * 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)
  38415. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  38416. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  38417. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  38418. * @returns the VertexData of the ribbon
  38419. */
  38420. VertexData.CreateRibbon = function (options) {
  38421. var pathArray = options.pathArray;
  38422. var closeArray = options.closeArray || false;
  38423. var closePath = options.closePath || false;
  38424. var invertUV = options.invertUV || false;
  38425. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38426. var offset = options.offset || defaultOffset;
  38427. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38428. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38429. var customUV = options.uvs;
  38430. var customColors = options.colors;
  38431. var positions = [];
  38432. var indices = [];
  38433. var normals = [];
  38434. var uvs = [];
  38435. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38436. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38437. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38438. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38439. var minlg; // minimal length among all paths from pathArray
  38440. var lg = []; // array of path lengths : nb of vertex per path
  38441. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38442. var p; // path iterator
  38443. var i; // point iterator
  38444. var j; // point iterator
  38445. // if single path in pathArray
  38446. if (pathArray.length < 2) {
  38447. var ar1 = [];
  38448. var ar2 = [];
  38449. for (i = 0; i < pathArray[0].length - offset; i++) {
  38450. ar1.push(pathArray[0][i]);
  38451. ar2.push(pathArray[0][i + offset]);
  38452. }
  38453. pathArray = [ar1, ar2];
  38454. }
  38455. // positions and horizontal distances (u)
  38456. var idc = 0;
  38457. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38458. var path;
  38459. var l;
  38460. minlg = pathArray[0].length;
  38461. var vectlg;
  38462. var dist;
  38463. for (p = 0; p < pathArray.length; p++) {
  38464. uTotalDistance[p] = 0;
  38465. us[p] = [0];
  38466. path = pathArray[p];
  38467. l = path.length;
  38468. minlg = (minlg < l) ? minlg : l;
  38469. j = 0;
  38470. while (j < l) {
  38471. positions.push(path[j].x, path[j].y, path[j].z);
  38472. if (j > 0) {
  38473. vectlg = path[j].subtract(path[j - 1]).length();
  38474. dist = vectlg + uTotalDistance[p];
  38475. us[p].push(dist);
  38476. uTotalDistance[p] = dist;
  38477. }
  38478. j++;
  38479. }
  38480. if (closePath) { // an extra hidden vertex is added in the "positions" array
  38481. j--;
  38482. positions.push(path[0].x, path[0].y, path[0].z);
  38483. vectlg = path[j].subtract(path[0]).length();
  38484. dist = vectlg + uTotalDistance[p];
  38485. us[p].push(dist);
  38486. uTotalDistance[p] = dist;
  38487. }
  38488. lg[p] = l + closePathCorr;
  38489. idx[p] = idc;
  38490. idc += (l + closePathCorr);
  38491. }
  38492. // vertical distances (v)
  38493. var path1;
  38494. var path2;
  38495. var vertex1 = null;
  38496. var vertex2 = null;
  38497. for (i = 0; i < minlg + closePathCorr; i++) {
  38498. vTotalDistance[i] = 0;
  38499. vs[i] = [0];
  38500. for (p = 0; p < pathArray.length - 1; p++) {
  38501. path1 = pathArray[p];
  38502. path2 = pathArray[p + 1];
  38503. if (i === minlg) { // closePath
  38504. vertex1 = path1[0];
  38505. vertex2 = path2[0];
  38506. }
  38507. else {
  38508. vertex1 = path1[i];
  38509. vertex2 = path2[i];
  38510. }
  38511. vectlg = vertex2.subtract(vertex1).length();
  38512. dist = vectlg + vTotalDistance[i];
  38513. vs[i].push(dist);
  38514. vTotalDistance[i] = dist;
  38515. }
  38516. if (closeArray && vertex2 && vertex1) {
  38517. path1 = pathArray[p];
  38518. path2 = pathArray[0];
  38519. if (i === minlg) { // closePath
  38520. vertex2 = path2[0];
  38521. }
  38522. vectlg = vertex2.subtract(vertex1).length();
  38523. dist = vectlg + vTotalDistance[i];
  38524. vTotalDistance[i] = dist;
  38525. }
  38526. }
  38527. // uvs
  38528. var u;
  38529. var v;
  38530. if (customUV) {
  38531. for (p = 0; p < customUV.length; p++) {
  38532. uvs.push(customUV[p].x, customUV[p].y);
  38533. }
  38534. }
  38535. else {
  38536. for (p = 0; p < pathArray.length; p++) {
  38537. for (i = 0; i < minlg + closePathCorr; i++) {
  38538. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38539. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38540. if (invertUV) {
  38541. uvs.push(v, u);
  38542. }
  38543. else {
  38544. uvs.push(u, v);
  38545. }
  38546. }
  38547. }
  38548. }
  38549. // indices
  38550. p = 0; // path index
  38551. var pi = 0; // positions array index
  38552. var l1 = lg[p] - 1; // path1 length
  38553. var l2 = lg[p + 1] - 1; // path2 length
  38554. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38555. var shft = idx[1] - idx[0]; // shift
  38556. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38557. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  38558. // 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
  38559. indices.push(pi, pi + shft, pi + 1);
  38560. indices.push(pi + shft + 1, pi + 1, pi + shft);
  38561. pi += 1;
  38562. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  38563. p++;
  38564. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  38565. shft = idx[0] - idx[p];
  38566. l1 = lg[p] - 1;
  38567. l2 = lg[0] - 1;
  38568. }
  38569. else {
  38570. shft = idx[p + 1] - idx[p];
  38571. l1 = lg[p] - 1;
  38572. l2 = lg[p + 1] - 1;
  38573. }
  38574. pi = idx[p];
  38575. min = (l1 < l2) ? l1 + pi : l2 + pi;
  38576. }
  38577. }
  38578. // normals
  38579. VertexData.ComputeNormals(positions, indices, normals);
  38580. if (closePath) { // update both the first and last vertex normals to their average value
  38581. var indexFirst = 0;
  38582. var indexLast = 0;
  38583. for (p = 0; p < pathArray.length; p++) {
  38584. indexFirst = idx[p] * 3;
  38585. if (p + 1 < pathArray.length) {
  38586. indexLast = (idx[p + 1] - 1) * 3;
  38587. }
  38588. else {
  38589. indexLast = normals.length - 3;
  38590. }
  38591. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38592. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38593. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38594. normals[indexLast] = normals[indexFirst];
  38595. normals[indexLast + 1] = normals[indexFirst + 1];
  38596. normals[indexLast + 2] = normals[indexFirst + 2];
  38597. }
  38598. }
  38599. // sides
  38600. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38601. // Colors
  38602. var colors = null;
  38603. if (customColors) {
  38604. colors = new Float32Array(customColors.length * 4);
  38605. for (var c = 0; c < customColors.length; c++) {
  38606. colors[c * 4] = customColors[c].r;
  38607. colors[c * 4 + 1] = customColors[c].g;
  38608. colors[c * 4 + 2] = customColors[c].b;
  38609. colors[c * 4 + 3] = customColors[c].a;
  38610. }
  38611. }
  38612. // Result
  38613. var vertexData = new VertexData();
  38614. var positions32 = new Float32Array(positions);
  38615. var normals32 = new Float32Array(normals);
  38616. var uvs32 = new Float32Array(uvs);
  38617. vertexData.indices = indices;
  38618. vertexData.positions = positions32;
  38619. vertexData.normals = normals32;
  38620. vertexData.uvs = uvs32;
  38621. if (colors) {
  38622. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  38623. }
  38624. if (closePath) {
  38625. vertexData._idx = idx;
  38626. }
  38627. return vertexData;
  38628. };
  38629. /**
  38630. * Creates the VertexData for a box
  38631. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38632. * * size sets the width, height and depth of the box to the value of size, optional default 1
  38633. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  38634. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  38635. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  38636. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  38637. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  38638. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38639. * * 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)
  38640. * * 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)
  38641. * @returns the VertexData of the box
  38642. */
  38643. VertexData.CreateBox = function (options) {
  38644. var normalsSource = [
  38645. new BABYLON.Vector3(0, 0, 1),
  38646. new BABYLON.Vector3(0, 0, -1),
  38647. new BABYLON.Vector3(1, 0, 0),
  38648. new BABYLON.Vector3(-1, 0, 0),
  38649. new BABYLON.Vector3(0, 1, 0),
  38650. new BABYLON.Vector3(0, -1, 0)
  38651. ];
  38652. var indices = [];
  38653. var positions = [];
  38654. var normals = [];
  38655. var uvs = [];
  38656. var width = options.width || options.size || 1;
  38657. var height = options.height || options.size || 1;
  38658. var depth = options.depth || options.size || 1;
  38659. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38660. var faceUV = options.faceUV || new Array(6);
  38661. var faceColors = options.faceColors;
  38662. var colors = [];
  38663. // default face colors and UV if undefined
  38664. for (var f = 0; f < 6; f++) {
  38665. if (faceUV[f] === undefined) {
  38666. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38667. }
  38668. if (faceColors && faceColors[f] === undefined) {
  38669. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38670. }
  38671. }
  38672. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  38673. // Create each face in turn.
  38674. for (var index = 0; index < normalsSource.length; index++) {
  38675. var normal = normalsSource[index];
  38676. // Get two vectors perpendicular to the face normal and to each other.
  38677. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  38678. var side2 = BABYLON.Vector3.Cross(normal, side1);
  38679. // Six indices (two triangles) per face.
  38680. var verticesLength = positions.length / 3;
  38681. indices.push(verticesLength);
  38682. indices.push(verticesLength + 1);
  38683. indices.push(verticesLength + 2);
  38684. indices.push(verticesLength);
  38685. indices.push(verticesLength + 2);
  38686. indices.push(verticesLength + 3);
  38687. // Four vertices per face.
  38688. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  38689. positions.push(vertex.x, vertex.y, vertex.z);
  38690. normals.push(normal.x, normal.y, normal.z);
  38691. uvs.push(faceUV[index].z, faceUV[index].w);
  38692. if (faceColors) {
  38693. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38694. }
  38695. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  38696. positions.push(vertex.x, vertex.y, vertex.z);
  38697. normals.push(normal.x, normal.y, normal.z);
  38698. uvs.push(faceUV[index].x, faceUV[index].w);
  38699. if (faceColors) {
  38700. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38701. }
  38702. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  38703. positions.push(vertex.x, vertex.y, vertex.z);
  38704. normals.push(normal.x, normal.y, normal.z);
  38705. uvs.push(faceUV[index].x, faceUV[index].y);
  38706. if (faceColors) {
  38707. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38708. }
  38709. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  38710. positions.push(vertex.x, vertex.y, vertex.z);
  38711. normals.push(normal.x, normal.y, normal.z);
  38712. uvs.push(faceUV[index].z, faceUV[index].y);
  38713. if (faceColors) {
  38714. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38715. }
  38716. }
  38717. // sides
  38718. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38719. // Result
  38720. var vertexData = new VertexData();
  38721. vertexData.indices = indices;
  38722. vertexData.positions = positions;
  38723. vertexData.normals = normals;
  38724. vertexData.uvs = uvs;
  38725. if (faceColors) {
  38726. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38727. vertexData.colors = totalColors;
  38728. }
  38729. return vertexData;
  38730. };
  38731. /**
  38732. * Creates the VertexData for an ellipsoid, defaults to a sphere
  38733. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38734. * * segments sets the number of horizontal strips optional, default 32
  38735. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  38736. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  38737. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  38738. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  38739. * * 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
  38740. * * 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
  38741. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38742. * * 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)
  38743. * * 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)
  38744. * @returns the VertexData of the ellipsoid
  38745. */
  38746. VertexData.CreateSphere = function (options) {
  38747. var segments = options.segments || 32;
  38748. var diameterX = options.diameterX || options.diameter || 1;
  38749. var diameterY = options.diameterY || options.diameter || 1;
  38750. var diameterZ = options.diameterZ || options.diameter || 1;
  38751. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38752. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  38753. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38754. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  38755. var totalZRotationSteps = 2 + segments;
  38756. var totalYRotationSteps = 2 * totalZRotationSteps;
  38757. var indices = [];
  38758. var positions = [];
  38759. var normals = [];
  38760. var uvs = [];
  38761. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38762. var normalizedZ = zRotationStep / totalZRotationSteps;
  38763. var angleZ = normalizedZ * Math.PI * slice;
  38764. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38765. var normalizedY = yRotationStep / totalYRotationSteps;
  38766. var angleY = normalizedY * Math.PI * 2 * arc;
  38767. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38768. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38769. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38770. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38771. var vertex = complete.multiply(radius);
  38772. var normal = complete.divide(radius).normalize();
  38773. positions.push(vertex.x, vertex.y, vertex.z);
  38774. normals.push(normal.x, normal.y, normal.z);
  38775. uvs.push(normalizedY, normalizedZ);
  38776. }
  38777. if (zRotationStep > 0) {
  38778. var verticesCount = positions.length / 3;
  38779. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38780. indices.push((firstIndex));
  38781. indices.push((firstIndex + 1));
  38782. indices.push(firstIndex + totalYRotationSteps + 1);
  38783. indices.push((firstIndex + totalYRotationSteps + 1));
  38784. indices.push((firstIndex + 1));
  38785. indices.push((firstIndex + totalYRotationSteps + 2));
  38786. }
  38787. }
  38788. }
  38789. // Sides
  38790. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38791. // Result
  38792. var vertexData = new VertexData();
  38793. vertexData.indices = indices;
  38794. vertexData.positions = positions;
  38795. vertexData.normals = normals;
  38796. vertexData.uvs = uvs;
  38797. return vertexData;
  38798. };
  38799. /**
  38800. * Creates the VertexData for a cylinder, cone or prism
  38801. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38802. * * height sets the height (y direction) of the cylinder, optional, default 2
  38803. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  38804. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  38805. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  38806. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38807. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  38808. * * 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
  38809. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38810. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38811. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  38812. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  38813. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38814. * * 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)
  38815. * * 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)
  38816. * @returns the VertexData of the cylinder, cone or prism
  38817. */
  38818. VertexData.CreateCylinder = function (options) {
  38819. var height = options.height || 2;
  38820. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38821. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38822. var tessellation = options.tessellation || 24;
  38823. var subdivisions = options.subdivisions || 1;
  38824. var hasRings = options.hasRings ? true : false;
  38825. var enclose = options.enclose ? true : false;
  38826. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38827. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38828. var faceUV = options.faceUV || new Array(3);
  38829. var faceColors = options.faceColors;
  38830. // default face colors and UV if undefined
  38831. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38832. var ringNb = (hasRings) ? subdivisions : 1;
  38833. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38834. var f;
  38835. for (f = 0; f < surfaceNb; f++) {
  38836. if (faceColors && faceColors[f] === undefined) {
  38837. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38838. }
  38839. }
  38840. for (f = 0; f < surfaceNb; f++) {
  38841. if (faceUV && faceUV[f] === undefined) {
  38842. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38843. }
  38844. }
  38845. var indices = new Array();
  38846. var positions = new Array();
  38847. var normals = new Array();
  38848. var uvs = new Array();
  38849. var colors = new Array();
  38850. var angle_step = Math.PI * 2 * arc / tessellation;
  38851. var angle;
  38852. var h;
  38853. var radius;
  38854. var tan = (diameterBottom - diameterTop) / 2 / height;
  38855. var ringVertex = BABYLON.Vector3.Zero();
  38856. var ringNormal = BABYLON.Vector3.Zero();
  38857. var ringFirstVertex = BABYLON.Vector3.Zero();
  38858. var ringFirstNormal = BABYLON.Vector3.Zero();
  38859. var quadNormal = BABYLON.Vector3.Zero();
  38860. var Y = BABYLON.Axis.Y;
  38861. // positions, normals, uvs
  38862. var i;
  38863. var j;
  38864. var r;
  38865. var ringIdx = 1;
  38866. var s = 1; // surface index
  38867. var cs = 0;
  38868. var v = 0;
  38869. for (i = 0; i <= subdivisions; i++) {
  38870. h = i / subdivisions;
  38871. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38872. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38873. for (r = 0; r < ringIdx; r++) {
  38874. if (hasRings) {
  38875. s += r;
  38876. }
  38877. if (enclose) {
  38878. s += 2 * r;
  38879. }
  38880. for (j = 0; j <= tessellation; j++) {
  38881. angle = j * angle_step;
  38882. // position
  38883. ringVertex.x = Math.cos(-angle) * radius;
  38884. ringVertex.y = -height / 2 + h * height;
  38885. ringVertex.z = Math.sin(-angle) * radius;
  38886. // normal
  38887. if (diameterTop === 0 && i === subdivisions) {
  38888. // if no top cap, reuse former normals
  38889. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38890. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38891. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38892. }
  38893. else {
  38894. ringNormal.x = ringVertex.x;
  38895. ringNormal.z = ringVertex.z;
  38896. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38897. ringNormal.normalize();
  38898. }
  38899. // keep first ring vertex values for enclose
  38900. if (j === 0) {
  38901. ringFirstVertex.copyFrom(ringVertex);
  38902. ringFirstNormal.copyFrom(ringNormal);
  38903. }
  38904. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38905. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38906. if (hasRings) {
  38907. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38908. }
  38909. else {
  38910. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38911. }
  38912. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38913. if (faceColors) {
  38914. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38915. }
  38916. }
  38917. // if enclose, add four vertices and their dedicated normals
  38918. if (arc !== 1 && enclose) {
  38919. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38920. positions.push(0, ringVertex.y, 0);
  38921. positions.push(0, ringVertex.y, 0);
  38922. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38923. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38924. quadNormal.normalize();
  38925. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38926. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38927. quadNormal.normalize();
  38928. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38929. if (hasRings) {
  38930. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38931. }
  38932. else {
  38933. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38934. }
  38935. uvs.push(faceUV[s + 1].x, v);
  38936. uvs.push(faceUV[s + 1].z, v);
  38937. if (hasRings) {
  38938. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38939. }
  38940. else {
  38941. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38942. }
  38943. uvs.push(faceUV[s + 2].x, v);
  38944. uvs.push(faceUV[s + 2].z, v);
  38945. if (faceColors) {
  38946. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38947. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38948. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38949. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38950. }
  38951. }
  38952. if (cs !== s) {
  38953. cs = s;
  38954. }
  38955. }
  38956. }
  38957. // indices
  38958. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  38959. var s;
  38960. i = 0;
  38961. for (s = 0; s < subdivisions; s++) {
  38962. var i0 = 0;
  38963. var i1 = 0;
  38964. var i2 = 0;
  38965. var i3 = 0;
  38966. for (j = 0; j < tessellation; j++) {
  38967. i0 = i * (e + 1) + j;
  38968. i1 = (i + 1) * (e + 1) + j;
  38969. i2 = i * (e + 1) + (j + 1);
  38970. i3 = (i + 1) * (e + 1) + (j + 1);
  38971. indices.push(i0, i1, i2);
  38972. indices.push(i3, i2, i1);
  38973. }
  38974. if (arc !== 1 && enclose) { // if enclose, add two quads
  38975. indices.push(i0 + 2, i1 + 2, i2 + 2);
  38976. indices.push(i3 + 2, i2 + 2, i1 + 2);
  38977. indices.push(i0 + 4, i1 + 4, i2 + 4);
  38978. indices.push(i3 + 4, i2 + 4, i1 + 4);
  38979. }
  38980. i = (hasRings) ? (i + 2) : (i + 1);
  38981. }
  38982. // Caps
  38983. var createCylinderCap = function (isTop) {
  38984. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  38985. if (radius === 0) {
  38986. return;
  38987. }
  38988. // Cap positions, normals & uvs
  38989. var angle;
  38990. var circleVector;
  38991. var i;
  38992. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  38993. var c = null;
  38994. if (faceColors) {
  38995. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  38996. }
  38997. // cap center
  38998. var vbase = positions.length / 3;
  38999. var offset = isTop ? height / 2 : -height / 2;
  39000. var center = new BABYLON.Vector3(0, offset, 0);
  39001. positions.push(center.x, center.y, center.z);
  39002. normals.push(0, isTop ? 1 : -1, 0);
  39003. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  39004. if (c) {
  39005. colors.push(c.r, c.g, c.b, c.a);
  39006. }
  39007. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  39008. for (i = 0; i <= tessellation; i++) {
  39009. angle = Math.PI * 2 * i * arc / tessellation;
  39010. var cos = Math.cos(-angle);
  39011. var sin = Math.sin(-angle);
  39012. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  39013. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  39014. positions.push(circleVector.x, circleVector.y, circleVector.z);
  39015. normals.push(0, isTop ? 1 : -1, 0);
  39016. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  39017. if (c) {
  39018. colors.push(c.r, c.g, c.b, c.a);
  39019. }
  39020. }
  39021. // Cap indices
  39022. for (i = 0; i < tessellation; i++) {
  39023. if (!isTop) {
  39024. indices.push(vbase);
  39025. indices.push(vbase + (i + 1));
  39026. indices.push(vbase + (i + 2));
  39027. }
  39028. else {
  39029. indices.push(vbase);
  39030. indices.push(vbase + (i + 2));
  39031. indices.push(vbase + (i + 1));
  39032. }
  39033. }
  39034. };
  39035. // add caps to geometry
  39036. createCylinderCap(false);
  39037. createCylinderCap(true);
  39038. // Sides
  39039. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39040. var vertexData = new VertexData();
  39041. vertexData.indices = indices;
  39042. vertexData.positions = positions;
  39043. vertexData.normals = normals;
  39044. vertexData.uvs = uvs;
  39045. if (faceColors) {
  39046. vertexData.colors = colors;
  39047. }
  39048. return vertexData;
  39049. };
  39050. /**
  39051. * Creates the VertexData for a torus
  39052. * @param options an object used to set the following optional parameters for the box, required but can be empty
  39053. * * diameter the diameter of the torus, optional default 1
  39054. * * thickness the diameter of the tube forming the torus, optional default 0.5
  39055. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  39056. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39057. * * 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)
  39058. * * 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)
  39059. * @returns the VertexData of the torus
  39060. */
  39061. VertexData.CreateTorus = function (options) {
  39062. var indices = [];
  39063. var positions = [];
  39064. var normals = [];
  39065. var uvs = [];
  39066. var diameter = options.diameter || 1;
  39067. var thickness = options.thickness || 0.5;
  39068. var tessellation = options.tessellation || 16;
  39069. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39070. var stride = tessellation + 1;
  39071. for (var i = 0; i <= tessellation; i++) {
  39072. var u = i / tessellation;
  39073. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  39074. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  39075. for (var j = 0; j <= tessellation; j++) {
  39076. var v = 1 - j / tessellation;
  39077. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  39078. var dx = Math.cos(innerAngle);
  39079. var dy = Math.sin(innerAngle);
  39080. // Create a vertex.
  39081. var normal = new BABYLON.Vector3(dx, dy, 0);
  39082. var position = normal.scale(thickness / 2);
  39083. var textureCoordinate = new BABYLON.Vector2(u, v);
  39084. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  39085. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  39086. positions.push(position.x, position.y, position.z);
  39087. normals.push(normal.x, normal.y, normal.z);
  39088. uvs.push(textureCoordinate.x, textureCoordinate.y);
  39089. // And create indices for two triangles.
  39090. var nextI = (i + 1) % stride;
  39091. var nextJ = (j + 1) % stride;
  39092. indices.push(i * stride + j);
  39093. indices.push(i * stride + nextJ);
  39094. indices.push(nextI * stride + j);
  39095. indices.push(i * stride + nextJ);
  39096. indices.push(nextI * stride + nextJ);
  39097. indices.push(nextI * stride + j);
  39098. }
  39099. }
  39100. // Sides
  39101. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39102. // Result
  39103. var vertexData = new VertexData();
  39104. vertexData.indices = indices;
  39105. vertexData.positions = positions;
  39106. vertexData.normals = normals;
  39107. vertexData.uvs = uvs;
  39108. return vertexData;
  39109. };
  39110. /**
  39111. * Creates the VertexData of the LineSystem
  39112. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  39113. * - lines an array of lines, each line being an array of successive Vector3
  39114. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  39115. * @returns the VertexData of the LineSystem
  39116. */
  39117. VertexData.CreateLineSystem = function (options) {
  39118. var indices = [];
  39119. var positions = [];
  39120. var lines = options.lines;
  39121. var colors = options.colors;
  39122. var vertexColors = [];
  39123. var idx = 0;
  39124. for (var l = 0; l < lines.length; l++) {
  39125. var points = lines[l];
  39126. for (var index = 0; index < points.length; index++) {
  39127. positions.push(points[index].x, points[index].y, points[index].z);
  39128. if (colors) {
  39129. var color = colors[l];
  39130. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  39131. }
  39132. if (index > 0) {
  39133. indices.push(idx - 1);
  39134. indices.push(idx);
  39135. }
  39136. idx++;
  39137. }
  39138. }
  39139. var vertexData = new VertexData();
  39140. vertexData.indices = indices;
  39141. vertexData.positions = positions;
  39142. if (colors) {
  39143. vertexData.colors = vertexColors;
  39144. }
  39145. return vertexData;
  39146. };
  39147. /**
  39148. * Create the VertexData for a DashedLines
  39149. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  39150. * - points an array successive Vector3
  39151. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  39152. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  39153. * - dashNb the intended total number of dashes, optional, default 200
  39154. * @returns the VertexData for the DashedLines
  39155. */
  39156. VertexData.CreateDashedLines = function (options) {
  39157. var dashSize = options.dashSize || 3;
  39158. var gapSize = options.gapSize || 1;
  39159. var dashNb = options.dashNb || 200;
  39160. var points = options.points;
  39161. var positions = new Array();
  39162. var indices = new Array();
  39163. var curvect = BABYLON.Vector3.Zero();
  39164. var lg = 0;
  39165. var nb = 0;
  39166. var shft = 0;
  39167. var dashshft = 0;
  39168. var curshft = 0;
  39169. var idx = 0;
  39170. var i = 0;
  39171. for (i = 0; i < points.length - 1; i++) {
  39172. points[i + 1].subtractToRef(points[i], curvect);
  39173. lg += curvect.length();
  39174. }
  39175. shft = lg / dashNb;
  39176. dashshft = dashSize * shft / (dashSize + gapSize);
  39177. for (i = 0; i < points.length - 1; i++) {
  39178. points[i + 1].subtractToRef(points[i], curvect);
  39179. nb = Math.floor(curvect.length() / shft);
  39180. curvect.normalize();
  39181. for (var j = 0; j < nb; j++) {
  39182. curshft = shft * j;
  39183. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  39184. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  39185. indices.push(idx, idx + 1);
  39186. idx += 2;
  39187. }
  39188. }
  39189. // Result
  39190. var vertexData = new VertexData();
  39191. vertexData.positions = positions;
  39192. vertexData.indices = indices;
  39193. return vertexData;
  39194. };
  39195. /**
  39196. * Creates the VertexData for a Ground
  39197. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39198. * - width the width (x direction) of the ground, optional, default 1
  39199. * - height the height (z direction) of the ground, optional, default 1
  39200. * - subdivisions the number of subdivisions per side, optional, default 1
  39201. * @returns the VertexData of the Ground
  39202. */
  39203. VertexData.CreateGround = function (options) {
  39204. var indices = [];
  39205. var positions = [];
  39206. var normals = [];
  39207. var uvs = [];
  39208. var row, col;
  39209. var width = options.width || 1;
  39210. var height = options.height || 1;
  39211. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39212. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39213. for (row = 0; row <= subdivisionsY; row++) {
  39214. for (col = 0; col <= subdivisionsX; col++) {
  39215. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  39216. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39217. positions.push(position.x, position.y, position.z);
  39218. normals.push(normal.x, normal.y, normal.z);
  39219. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  39220. }
  39221. }
  39222. for (row = 0; row < subdivisionsY; row++) {
  39223. for (col = 0; col < subdivisionsX; col++) {
  39224. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39225. indices.push(col + 1 + row * (subdivisionsX + 1));
  39226. indices.push(col + row * (subdivisionsX + 1));
  39227. indices.push(col + (row + 1) * (subdivisionsX + 1));
  39228. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39229. indices.push(col + row * (subdivisionsX + 1));
  39230. }
  39231. }
  39232. // Result
  39233. var vertexData = new VertexData();
  39234. vertexData.indices = indices;
  39235. vertexData.positions = positions;
  39236. vertexData.normals = normals;
  39237. vertexData.uvs = uvs;
  39238. return vertexData;
  39239. };
  39240. /**
  39241. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  39242. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39243. * * xmin the ground minimum X coordinate, optional, default -1
  39244. * * zmin the ground minimum Z coordinate, optional, default -1
  39245. * * xmax the ground maximum X coordinate, optional, default 1
  39246. * * zmax the ground maximum Z coordinate, optional, default 1
  39247. * * 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}
  39248. * * 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}
  39249. * @returns the VertexData of the TiledGround
  39250. */
  39251. VertexData.CreateTiledGround = function (options) {
  39252. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  39253. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  39254. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  39255. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  39256. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  39257. var precision = options.precision || { w: 1, h: 1 };
  39258. var indices = new Array();
  39259. var positions = new Array();
  39260. var normals = new Array();
  39261. var uvs = new Array();
  39262. var row, col, tileRow, tileCol;
  39263. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  39264. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  39265. precision.w = (precision.w < 1) ? 1 : precision.w;
  39266. precision.h = (precision.h < 1) ? 1 : precision.h;
  39267. var tileSize = {
  39268. 'w': (xmax - xmin) / subdivisions.w,
  39269. 'h': (zmax - zmin) / subdivisions.h
  39270. };
  39271. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  39272. // Indices
  39273. var base = positions.length / 3;
  39274. var rowLength = precision.w + 1;
  39275. for (row = 0; row < precision.h; row++) {
  39276. for (col = 0; col < precision.w; col++) {
  39277. var square = [
  39278. base + col + row * rowLength,
  39279. base + (col + 1) + row * rowLength,
  39280. base + (col + 1) + (row + 1) * rowLength,
  39281. base + col + (row + 1) * rowLength
  39282. ];
  39283. indices.push(square[1]);
  39284. indices.push(square[2]);
  39285. indices.push(square[3]);
  39286. indices.push(square[0]);
  39287. indices.push(square[1]);
  39288. indices.push(square[3]);
  39289. }
  39290. }
  39291. // Position, normals and uvs
  39292. var position = BABYLON.Vector3.Zero();
  39293. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39294. for (row = 0; row <= precision.h; row++) {
  39295. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  39296. for (col = 0; col <= precision.w; col++) {
  39297. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  39298. position.y = 0;
  39299. positions.push(position.x, position.y, position.z);
  39300. normals.push(normal.x, normal.y, normal.z);
  39301. uvs.push(col / precision.w, row / precision.h);
  39302. }
  39303. }
  39304. }
  39305. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  39306. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  39307. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  39308. }
  39309. }
  39310. // Result
  39311. var vertexData = new VertexData();
  39312. vertexData.indices = indices;
  39313. vertexData.positions = positions;
  39314. vertexData.normals = normals;
  39315. vertexData.uvs = uvs;
  39316. return vertexData;
  39317. };
  39318. /**
  39319. * Creates the VertexData of the Ground designed from a heightmap
  39320. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  39321. * * width the width (x direction) of the ground
  39322. * * height the height (z direction) of the ground
  39323. * * subdivisions the number of subdivisions per side
  39324. * * minHeight the minimum altitude on the ground, optional, default 0
  39325. * * maxHeight the maximum altitude on the ground, optional default 1
  39326. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  39327. * * buffer the array holding the image color data
  39328. * * bufferWidth the width of image
  39329. * * bufferHeight the height of image
  39330. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  39331. * @returns the VertexData of the Ground designed from a heightmap
  39332. */
  39333. VertexData.CreateGroundFromHeightMap = function (options) {
  39334. var indices = [];
  39335. var positions = [];
  39336. var normals = [];
  39337. var uvs = [];
  39338. var row, col;
  39339. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39340. var alphaFilter = options.alphaFilter || 0.0;
  39341. // Vertices
  39342. for (row = 0; row <= options.subdivisions; row++) {
  39343. for (col = 0; col <= options.subdivisions; col++) {
  39344. 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));
  39345. // Compute height
  39346. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  39347. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  39348. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  39349. var r = options.buffer[pos] / 255.0;
  39350. var g = options.buffer[pos + 1] / 255.0;
  39351. var b = options.buffer[pos + 2] / 255.0;
  39352. var a = options.buffer[pos + 3] / 255.0;
  39353. var gradient = r * filter.r + g * filter.g + b * filter.b;
  39354. // If our alpha channel is not within our filter then we will assign a 'special' height
  39355. // Then when building the indices, we will ignore any vertex that is using the special height
  39356. if (a >= alphaFilter) {
  39357. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  39358. }
  39359. else {
  39360. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  39361. }
  39362. // Add vertex
  39363. positions.push(position.x, position.y, position.z);
  39364. normals.push(0, 0, 0);
  39365. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  39366. }
  39367. }
  39368. // Indices
  39369. for (row = 0; row < options.subdivisions; row++) {
  39370. for (col = 0; col < options.subdivisions; col++) {
  39371. // Calculate Indices
  39372. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  39373. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  39374. var idx3 = (col + row * (options.subdivisions + 1));
  39375. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  39376. // Check that all indices are visible (based on our special height)
  39377. // Only display the vertex if all Indices are visible
  39378. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  39379. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  39380. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  39381. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  39382. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  39383. indices.push(idx1);
  39384. indices.push(idx2);
  39385. indices.push(idx3);
  39386. }
  39387. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  39388. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  39389. indices.push(idx4);
  39390. indices.push(idx1);
  39391. indices.push(idx3);
  39392. }
  39393. }
  39394. }
  39395. // Normals
  39396. VertexData.ComputeNormals(positions, indices, normals);
  39397. // Result
  39398. var vertexData = new VertexData();
  39399. vertexData.indices = indices;
  39400. vertexData.positions = positions;
  39401. vertexData.normals = normals;
  39402. vertexData.uvs = uvs;
  39403. return vertexData;
  39404. };
  39405. /**
  39406. * Creates the VertexData for a Plane
  39407. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  39408. * * size sets the width and height of the plane to the value of size, optional default 1
  39409. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  39410. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  39411. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39412. * * 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)
  39413. * * 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)
  39414. * @returns the VertexData of the box
  39415. */
  39416. VertexData.CreatePlane = function (options) {
  39417. var indices = [];
  39418. var positions = [];
  39419. var normals = [];
  39420. var uvs = [];
  39421. var width = options.width || options.size || 1;
  39422. var height = options.height || options.size || 1;
  39423. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39424. // Vertices
  39425. var halfWidth = width / 2.0;
  39426. var halfHeight = height / 2.0;
  39427. positions.push(-halfWidth, -halfHeight, 0);
  39428. normals.push(0, 0, -1.0);
  39429. uvs.push(0.0, 0.0);
  39430. positions.push(halfWidth, -halfHeight, 0);
  39431. normals.push(0, 0, -1.0);
  39432. uvs.push(1.0, 0.0);
  39433. positions.push(halfWidth, halfHeight, 0);
  39434. normals.push(0, 0, -1.0);
  39435. uvs.push(1.0, 1.0);
  39436. positions.push(-halfWidth, halfHeight, 0);
  39437. normals.push(0, 0, -1.0);
  39438. uvs.push(0.0, 1.0);
  39439. // Indices
  39440. indices.push(0);
  39441. indices.push(1);
  39442. indices.push(2);
  39443. indices.push(0);
  39444. indices.push(2);
  39445. indices.push(3);
  39446. // Sides
  39447. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39448. // Result
  39449. var vertexData = new VertexData();
  39450. vertexData.indices = indices;
  39451. vertexData.positions = positions;
  39452. vertexData.normals = normals;
  39453. vertexData.uvs = uvs;
  39454. return vertexData;
  39455. };
  39456. /**
  39457. * Creates the VertexData of the Disc or regular Polygon
  39458. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  39459. * * radius the radius of the disc, optional default 0.5
  39460. * * tessellation the number of polygon sides, optional, default 64
  39461. * * 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
  39462. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39463. * * 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)
  39464. * * 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)
  39465. * @returns the VertexData of the box
  39466. */
  39467. VertexData.CreateDisc = function (options) {
  39468. var positions = new Array();
  39469. var indices = new Array();
  39470. var normals = new Array();
  39471. var uvs = new Array();
  39472. var radius = options.radius || 0.5;
  39473. var tessellation = options.tessellation || 64;
  39474. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39475. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39476. // positions and uvs
  39477. positions.push(0, 0, 0); // disc center first
  39478. uvs.push(0.5, 0.5);
  39479. var theta = Math.PI * 2 * arc;
  39480. var step = theta / tessellation;
  39481. for (var a = 0; a < theta; a += step) {
  39482. var x = Math.cos(a);
  39483. var y = Math.sin(a);
  39484. var u = (x + 1) / 2;
  39485. var v = (1 - y) / 2;
  39486. positions.push(radius * x, radius * y, 0);
  39487. uvs.push(u, v);
  39488. }
  39489. if (arc === 1) {
  39490. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39491. uvs.push(uvs[2], uvs[3]);
  39492. }
  39493. //indices
  39494. var vertexNb = positions.length / 3;
  39495. for (var i = 1; i < vertexNb - 1; i++) {
  39496. indices.push(i + 1, 0, i);
  39497. }
  39498. // result
  39499. VertexData.ComputeNormals(positions, indices, normals);
  39500. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39501. var vertexData = new VertexData();
  39502. vertexData.indices = indices;
  39503. vertexData.positions = positions;
  39504. vertexData.normals = normals;
  39505. vertexData.uvs = uvs;
  39506. return vertexData;
  39507. };
  39508. /**
  39509. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  39510. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  39511. * @param polygon a mesh built from polygonTriangulation.build()
  39512. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39513. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39514. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39515. * @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)
  39516. * @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)
  39517. * @returns the VertexData of the Polygon
  39518. */
  39519. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  39520. var faceUV = fUV || new Array(3);
  39521. var faceColors = fColors;
  39522. var colors = [];
  39523. // default face colors and UV if undefined
  39524. for (var f = 0; f < 3; f++) {
  39525. if (faceUV[f] === undefined) {
  39526. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39527. }
  39528. if (faceColors && faceColors[f] === undefined) {
  39529. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39530. }
  39531. }
  39532. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39533. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39534. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39535. var indices = polygon.getIndices();
  39536. // set face colours and textures
  39537. var idx = 0;
  39538. var face = 0;
  39539. for (var index = 0; index < normals.length; index += 3) {
  39540. //Edge Face no. 1
  39541. if (Math.abs(normals[index + 1]) < 0.001) {
  39542. face = 1;
  39543. }
  39544. //Top Face no. 0
  39545. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  39546. face = 0;
  39547. }
  39548. //Bottom Face no. 2
  39549. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  39550. face = 2;
  39551. }
  39552. idx = index / 3;
  39553. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  39554. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  39555. if (faceColors) {
  39556. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  39557. }
  39558. }
  39559. // sides
  39560. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  39561. // Result
  39562. var vertexData = new VertexData();
  39563. vertexData.indices = indices;
  39564. vertexData.positions = positions;
  39565. vertexData.normals = normals;
  39566. vertexData.uvs = uvs;
  39567. if (faceColors) {
  39568. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39569. vertexData.colors = totalColors;
  39570. }
  39571. return vertexData;
  39572. };
  39573. /**
  39574. * Creates the VertexData of the IcoSphere
  39575. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  39576. * * radius the radius of the IcoSphere, optional default 1
  39577. * * radiusX allows stretching in the x direction, optional, default radius
  39578. * * radiusY allows stretching in the y direction, optional, default radius
  39579. * * radiusZ allows stretching in the z direction, optional, default radius
  39580. * * flat when true creates a flat shaded mesh, optional, default true
  39581. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39582. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39583. * * 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)
  39584. * * 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)
  39585. * @returns the VertexData of the IcoSphere
  39586. */
  39587. VertexData.CreateIcoSphere = function (options) {
  39588. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39589. var radius = options.radius || 1;
  39590. var flat = (options.flat === undefined) ? true : options.flat;
  39591. var subdivisions = options.subdivisions || 4;
  39592. var radiusX = options.radiusX || radius;
  39593. var radiusY = options.radiusY || radius;
  39594. var radiusZ = options.radiusZ || radius;
  39595. var t = (1 + Math.sqrt(5)) / 2;
  39596. // 12 vertex x,y,z
  39597. var ico_vertices = [
  39598. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39599. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39600. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39601. ];
  39602. // index of 3 vertex makes a face of icopshere
  39603. var ico_indices = [
  39604. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39605. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39606. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39607. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39608. ];
  39609. // vertex for uv have aliased position, not for UV
  39610. var vertices_unalias_id = [
  39611. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39612. // vertex alias
  39613. 0,
  39614. 2,
  39615. 3,
  39616. 3,
  39617. 3,
  39618. 4,
  39619. 7,
  39620. 8,
  39621. 9,
  39622. 9,
  39623. 10,
  39624. 11 // 23: B + 12
  39625. ];
  39626. // uv as integer step (not pixels !)
  39627. var ico_vertexuv = [
  39628. 5, 1, 3, 1, 6, 4, 0, 0,
  39629. 5, 3, 4, 2, 2, 2, 4, 0,
  39630. 2, 0, 1, 1, 6, 0, 6, 2,
  39631. // vertex alias (for same vertex on different faces)
  39632. 0, 4,
  39633. 3, 3,
  39634. 4, 4,
  39635. 3, 1,
  39636. 4, 2,
  39637. 4, 4,
  39638. 0, 2,
  39639. 1, 1,
  39640. 2, 2,
  39641. 3, 3,
  39642. 1, 3,
  39643. 2, 4 // 23: B + 12
  39644. ];
  39645. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39646. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39647. // First island of uv mapping
  39648. // v = 4h 3+ 2
  39649. // v = 3h 9+ 4
  39650. // v = 2h 9+ 5 B
  39651. // v = 1h 9 1 0
  39652. // v = 0h 3 8 7 A
  39653. // u = 0 1 2 3 4 5 6 *a
  39654. // Second island of uv mapping
  39655. // v = 4h 0+ B+ 4+
  39656. // v = 3h A+ 2+
  39657. // v = 2h 7+ 6 3+
  39658. // v = 1h 8+ 3+
  39659. // v = 0h
  39660. // u = 0 1 2 3 4 5 6 *a
  39661. // Face layout on texture UV mapping
  39662. // ============
  39663. // \ 4 /\ 16 / ======
  39664. // \ / \ / /\ 11 /
  39665. // \/ 7 \/ / \ /
  39666. // ======= / 10 \/
  39667. // /\ 17 /\ =======
  39668. // / \ / \ \ 15 /\
  39669. // / 8 \/ 12 \ \ / \
  39670. // ============ \/ 6 \
  39671. // \ 18 /\ ============
  39672. // \ / \ \ 5 /\ 0 /
  39673. // \/ 13 \ \ / \ /
  39674. // ======= \/ 1 \/
  39675. // =============
  39676. // /\ 19 /\ 2 /\
  39677. // / \ / \ / \
  39678. // / 14 \/ 9 \/ 3 \
  39679. // ===================
  39680. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39681. var ustep = 138 / 1024;
  39682. var vstep = 239 / 1024;
  39683. var uoffset = 60 / 1024;
  39684. var voffset = 26 / 1024;
  39685. // Second island should have margin, not to touch the first island
  39686. // avoid any borderline artefact in pixel rounding
  39687. var island_u_offset = -40 / 1024;
  39688. var island_v_offset = +20 / 1024;
  39689. // face is either island 0 or 1 :
  39690. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39691. var island = [
  39692. 0, 0, 0, 0, 1,
  39693. 0, 0, 1, 1, 0,
  39694. 0, 0, 1, 1, 0,
  39695. 0, 1, 1, 1, 0 // 15 - 19
  39696. ];
  39697. var indices = new Array();
  39698. var positions = new Array();
  39699. var normals = new Array();
  39700. var uvs = new Array();
  39701. var current_indice = 0;
  39702. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  39703. var face_vertex_pos = new Array(3);
  39704. var face_vertex_uv = new Array(3);
  39705. var v012;
  39706. for (v012 = 0; v012 < 3; v012++) {
  39707. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  39708. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  39709. }
  39710. // create all with normals
  39711. for (var face = 0; face < 20; face++) {
  39712. // 3 vertex per face
  39713. for (v012 = 0; v012 < 3; v012++) {
  39714. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  39715. var v_id = ico_indices[3 * face + v012];
  39716. // vertex have 3D position (x,y,z)
  39717. 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]);
  39718. // Normalize to get normal, then scale to radius
  39719. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  39720. // uv Coordinates from vertex ID
  39721. 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);
  39722. }
  39723. // Subdivide the face (interpolate pos, norm, uv)
  39724. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  39725. // - norm is linear interpolation of vertex corner normal
  39726. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  39727. // - uv is linear interpolation
  39728. //
  39729. // Topology is as below for sub-divide by 2
  39730. // vertex shown as v0,v1,v2
  39731. // interp index is i1 to progress in range [v0,v1[
  39732. // interp index is i2 to progress in range [v0,v2[
  39733. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  39734. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39735. //
  39736. //
  39737. // i2 v2
  39738. // ^ ^
  39739. // / / \
  39740. // / / \
  39741. // / / \
  39742. // / / (0,1) \
  39743. // / #---------\
  39744. // / / \ (0,0)'/ \
  39745. // / / \ / \
  39746. // / / \ / \
  39747. // / / (0,0) \ / (1,0) \
  39748. // / #---------#---------\
  39749. // v0 v1
  39750. //
  39751. // --------------------> i1
  39752. //
  39753. // interp of (i1,i2):
  39754. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  39755. // along i1 : lerp(x0,x1, i1/(S-i2))
  39756. //
  39757. // centroid of triangle is needed to get help normal computation
  39758. // (c1,c2) are used for centroid location
  39759. var interp_vertex = function (i1, i2, c1, c2) {
  39760. // vertex is interpolated from
  39761. // - face_vertex_pos[0..2]
  39762. // - face_vertex_uv[0..2]
  39763. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39764. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39765. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39766. pos_interp.normalize();
  39767. var vertex_normal;
  39768. if (flat) {
  39769. // in flat mode, recalculate normal as face centroid normal
  39770. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39771. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39772. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39773. }
  39774. else {
  39775. // in smooth mode, recalculate normal from each single vertex position
  39776. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39777. }
  39778. // Vertex normal need correction due to X,Y,Z radius scaling
  39779. vertex_normal.x /= radiusX;
  39780. vertex_normal.y /= radiusY;
  39781. vertex_normal.z /= radiusZ;
  39782. vertex_normal.normalize();
  39783. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39784. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39785. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39786. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39787. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39788. uvs.push(uv_interp.x, uv_interp.y);
  39789. // push each vertex has member of a face
  39790. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39791. indices.push(current_indice);
  39792. current_indice++;
  39793. };
  39794. for (var i2 = 0; i2 < subdivisions; i2++) {
  39795. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39796. // face : (i1,i2) for /\ :
  39797. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39798. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39799. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39800. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39801. if (i1 + i2 + 1 < subdivisions) {
  39802. // face : (i1,i2)' for \/ :
  39803. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39804. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39805. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39806. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39807. }
  39808. }
  39809. }
  39810. }
  39811. // Sides
  39812. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39813. // Result
  39814. var vertexData = new VertexData();
  39815. vertexData.indices = indices;
  39816. vertexData.positions = positions;
  39817. vertexData.normals = normals;
  39818. vertexData.uvs = uvs;
  39819. return vertexData;
  39820. };
  39821. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39822. /**
  39823. * Creates the VertexData for a Polyhedron
  39824. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39825. * * type provided types are:
  39826. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39827. * * 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)
  39828. * * size the size of the IcoSphere, optional default 1
  39829. * * sizeX allows stretching in the x direction, optional, default size
  39830. * * sizeY allows stretching in the y direction, optional, default size
  39831. * * sizeZ allows stretching in the z direction, optional, default size
  39832. * * 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
  39833. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39834. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39835. * * flat when true creates a flat shaded mesh, optional, default true
  39836. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39837. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39838. * * 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)
  39839. * * 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)
  39840. * @returns the VertexData of the Polyhedron
  39841. */
  39842. VertexData.CreatePolyhedron = function (options) {
  39843. // provided polyhedron types :
  39844. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39845. // 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)
  39846. var polyhedra = [];
  39847. 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]] };
  39848. 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]] };
  39849. polyhedra[2] = {
  39850. 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]],
  39851. 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]]
  39852. };
  39853. polyhedra[3] = {
  39854. 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]],
  39855. 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]]
  39856. };
  39857. polyhedra[4] = {
  39858. 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]],
  39859. 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]]
  39860. };
  39861. 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]] };
  39862. 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]] };
  39863. 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]] };
  39864. 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]] };
  39865. 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]] };
  39866. 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]] };
  39867. 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]] };
  39868. 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]] };
  39869. 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]] };
  39870. polyhedra[14] = {
  39871. 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]],
  39872. 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]]
  39873. };
  39874. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39875. var size = options.size;
  39876. var sizeX = options.sizeX || size || 1;
  39877. var sizeY = options.sizeY || size || 1;
  39878. var sizeZ = options.sizeZ || size || 1;
  39879. var data = options.custom || polyhedra[type];
  39880. var nbfaces = data.face.length;
  39881. var faceUV = options.faceUV || new Array(nbfaces);
  39882. var faceColors = options.faceColors;
  39883. var flat = (options.flat === undefined) ? true : options.flat;
  39884. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39885. var positions = new Array();
  39886. var indices = new Array();
  39887. var normals = new Array();
  39888. var uvs = new Array();
  39889. var colors = new Array();
  39890. var index = 0;
  39891. var faceIdx = 0; // face cursor in the array "indexes"
  39892. var indexes = new Array();
  39893. var i = 0;
  39894. var f = 0;
  39895. var u, v, ang, x, y, tmp;
  39896. // default face colors and UV if undefined
  39897. if (flat) {
  39898. for (f = 0; f < nbfaces; f++) {
  39899. if (faceColors && faceColors[f] === undefined) {
  39900. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39901. }
  39902. if (faceUV && faceUV[f] === undefined) {
  39903. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39904. }
  39905. }
  39906. }
  39907. if (!flat) {
  39908. for (i = 0; i < data.vertex.length; i++) {
  39909. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39910. uvs.push(0, 0);
  39911. }
  39912. for (f = 0; f < nbfaces; f++) {
  39913. for (i = 0; i < data.face[f].length - 2; i++) {
  39914. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39915. }
  39916. }
  39917. }
  39918. else {
  39919. for (f = 0; f < nbfaces; f++) {
  39920. var fl = data.face[f].length; // number of vertices of the current face
  39921. ang = 2 * Math.PI / fl;
  39922. x = 0.5 * Math.tan(ang / 2);
  39923. y = 0.5;
  39924. // positions, uvs, colors
  39925. for (i = 0; i < fl; i++) {
  39926. // positions
  39927. 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);
  39928. indexes.push(index);
  39929. index++;
  39930. // uvs
  39931. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39932. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39933. uvs.push(u, v);
  39934. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39935. y = x * Math.sin(ang) + y * Math.cos(ang);
  39936. x = tmp;
  39937. // colors
  39938. if (faceColors) {
  39939. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39940. }
  39941. }
  39942. // indices from indexes
  39943. for (i = 0; i < fl - 2; i++) {
  39944. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39945. }
  39946. faceIdx += fl;
  39947. }
  39948. }
  39949. VertexData.ComputeNormals(positions, indices, normals);
  39950. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39951. var vertexData = new VertexData();
  39952. vertexData.positions = positions;
  39953. vertexData.indices = indices;
  39954. vertexData.normals = normals;
  39955. vertexData.uvs = uvs;
  39956. if (faceColors && flat) {
  39957. vertexData.colors = colors;
  39958. }
  39959. return vertexData;
  39960. };
  39961. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  39962. /**
  39963. * Creates the VertexData for a TorusKnot
  39964. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  39965. * * radius the radius of the torus knot, optional, default 2
  39966. * * tube the thickness of the tube, optional, default 0.5
  39967. * * radialSegments the number of sides on each tube segments, optional, default 32
  39968. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  39969. * * p the number of windings around the z axis, optional, default 2
  39970. * * q the number of windings around the x axis, optional, default 3
  39971. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39972. * * 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)
  39973. * * 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)
  39974. * @returns the VertexData of the Torus Knot
  39975. */
  39976. VertexData.CreateTorusKnot = function (options) {
  39977. var indices = new Array();
  39978. var positions = new Array();
  39979. var normals = new Array();
  39980. var uvs = new Array();
  39981. var radius = options.radius || 2;
  39982. var tube = options.tube || 0.5;
  39983. var radialSegments = options.radialSegments || 32;
  39984. var tubularSegments = options.tubularSegments || 32;
  39985. var p = options.p || 2;
  39986. var q = options.q || 3;
  39987. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39988. // Helper
  39989. var getPos = function (angle) {
  39990. var cu = Math.cos(angle);
  39991. var su = Math.sin(angle);
  39992. var quOverP = q / p * angle;
  39993. var cs = Math.cos(quOverP);
  39994. var tx = radius * (2 + cs) * 0.5 * cu;
  39995. var ty = radius * (2 + cs) * su * 0.5;
  39996. var tz = radius * Math.sin(quOverP) * 0.5;
  39997. return new BABYLON.Vector3(tx, ty, tz);
  39998. };
  39999. // Vertices
  40000. var i;
  40001. var j;
  40002. for (i = 0; i <= radialSegments; i++) {
  40003. var modI = i % radialSegments;
  40004. var u = modI / radialSegments * 2 * p * Math.PI;
  40005. var p1 = getPos(u);
  40006. var p2 = getPos(u + 0.01);
  40007. var tang = p2.subtract(p1);
  40008. var n = p2.add(p1);
  40009. var bitan = BABYLON.Vector3.Cross(tang, n);
  40010. n = BABYLON.Vector3.Cross(bitan, tang);
  40011. bitan.normalize();
  40012. n.normalize();
  40013. for (j = 0; j < tubularSegments; j++) {
  40014. var modJ = j % tubularSegments;
  40015. var v = modJ / tubularSegments * 2 * Math.PI;
  40016. var cx = -tube * Math.cos(v);
  40017. var cy = tube * Math.sin(v);
  40018. positions.push(p1.x + cx * n.x + cy * bitan.x);
  40019. positions.push(p1.y + cx * n.y + cy * bitan.y);
  40020. positions.push(p1.z + cx * n.z + cy * bitan.z);
  40021. uvs.push(i / radialSegments);
  40022. uvs.push(j / tubularSegments);
  40023. }
  40024. }
  40025. for (i = 0; i < radialSegments; i++) {
  40026. for (j = 0; j < tubularSegments; j++) {
  40027. var jNext = (j + 1) % tubularSegments;
  40028. var a = i * tubularSegments + j;
  40029. var b = (i + 1) * tubularSegments + j;
  40030. var c = (i + 1) * tubularSegments + jNext;
  40031. var d = i * tubularSegments + jNext;
  40032. indices.push(d);
  40033. indices.push(b);
  40034. indices.push(a);
  40035. indices.push(d);
  40036. indices.push(c);
  40037. indices.push(b);
  40038. }
  40039. }
  40040. // Normals
  40041. VertexData.ComputeNormals(positions, indices, normals);
  40042. // Sides
  40043. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40044. // Result
  40045. var vertexData = new VertexData();
  40046. vertexData.indices = indices;
  40047. vertexData.positions = positions;
  40048. vertexData.normals = normals;
  40049. vertexData.uvs = uvs;
  40050. return vertexData;
  40051. };
  40052. // Tools
  40053. /**
  40054. * Compute normals for given positions and indices
  40055. * @param positions an array of vertex positions, [...., x, y, z, ......]
  40056. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  40057. * @param normals an array of vertex normals, [...., x, y, z, ......]
  40058. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  40059. * * facetNormals : optional array of facet normals (vector3)
  40060. * * facetPositions : optional array of facet positions (vector3)
  40061. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  40062. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  40063. * * bInfo : optional bounding info, required for facetPartitioning computation
  40064. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  40065. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  40066. * * useRightHandedSystem: optional boolean to for right handed system computation
  40067. * * depthSort : optional boolean to enable the facet depth sort computation
  40068. * * distanceTo : optional Vector3 to compute the facet depth from this location
  40069. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  40070. */
  40071. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  40072. // temporary scalar variables
  40073. var index = 0; // facet index
  40074. var p1p2x = 0.0; // p1p2 vector x coordinate
  40075. var p1p2y = 0.0; // p1p2 vector y coordinate
  40076. var p1p2z = 0.0; // p1p2 vector z coordinate
  40077. var p3p2x = 0.0; // p3p2 vector x coordinate
  40078. var p3p2y = 0.0; // p3p2 vector y coordinate
  40079. var p3p2z = 0.0; // p3p2 vector z coordinate
  40080. var faceNormalx = 0.0; // facet normal x coordinate
  40081. var faceNormaly = 0.0; // facet normal y coordinate
  40082. var faceNormalz = 0.0; // facet normal z coordinate
  40083. var length = 0.0; // facet normal length before normalization
  40084. var v1x = 0; // vector1 x index in the positions array
  40085. var v1y = 0; // vector1 y index in the positions array
  40086. var v1z = 0; // vector1 z index in the positions array
  40087. var v2x = 0; // vector2 x index in the positions array
  40088. var v2y = 0; // vector2 y index in the positions array
  40089. var v2z = 0; // vector2 z index in the positions array
  40090. var v3x = 0; // vector3 x index in the positions array
  40091. var v3y = 0; // vector3 y index in the positions array
  40092. var v3z = 0; // vector3 z index in the positions array
  40093. var computeFacetNormals = false;
  40094. var computeFacetPositions = false;
  40095. var computeFacetPartitioning = false;
  40096. var computeDepthSort = false;
  40097. var faceNormalSign = 1;
  40098. var ratio = 0;
  40099. var distanceTo = null;
  40100. if (options) {
  40101. computeFacetNormals = (options.facetNormals) ? true : false;
  40102. computeFacetPositions = (options.facetPositions) ? true : false;
  40103. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  40104. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  40105. ratio = options.ratio || 0;
  40106. computeDepthSort = (options.depthSort) ? true : false;
  40107. distanceTo = (options.distanceTo);
  40108. if (computeDepthSort) {
  40109. if (distanceTo === undefined) {
  40110. distanceTo = BABYLON.Vector3.Zero();
  40111. }
  40112. var depthSortedFacets = options.depthSortedFacets;
  40113. }
  40114. }
  40115. // facetPartitioning reinit if needed
  40116. var xSubRatio = 0;
  40117. var ySubRatio = 0;
  40118. var zSubRatio = 0;
  40119. var subSq = 0;
  40120. if (computeFacetPartitioning && options && options.bbSize) {
  40121. var ox = 0; // X partitioning index for facet position
  40122. var oy = 0; // Y partinioning index for facet position
  40123. var oz = 0; // Z partinioning index for facet position
  40124. var b1x = 0; // X partitioning index for facet v1 vertex
  40125. var b1y = 0; // Y partitioning index for facet v1 vertex
  40126. var b1z = 0; // z partitioning index for facet v1 vertex
  40127. var b2x = 0; // X partitioning index for facet v2 vertex
  40128. var b2y = 0; // Y partitioning index for facet v2 vertex
  40129. var b2z = 0; // Z partitioning index for facet v2 vertex
  40130. var b3x = 0; // X partitioning index for facet v3 vertex
  40131. var b3y = 0; // Y partitioning index for facet v3 vertex
  40132. var b3z = 0; // Z partitioning index for facet v3 vertex
  40133. var block_idx_o = 0; // facet barycenter block index
  40134. var block_idx_v1 = 0; // v1 vertex block index
  40135. var block_idx_v2 = 0; // v2 vertex block index
  40136. var block_idx_v3 = 0; // v3 vertex block index
  40137. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  40138. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  40139. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  40140. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  40141. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  40142. subSq = options.subDiv.max * options.subDiv.max;
  40143. options.facetPartitioning.length = 0;
  40144. }
  40145. // reset the normals
  40146. for (index = 0; index < positions.length; index++) {
  40147. normals[index] = 0.0;
  40148. }
  40149. // Loop : 1 indice triplet = 1 facet
  40150. var nbFaces = (indices.length / 3) | 0;
  40151. for (index = 0; index < nbFaces; index++) {
  40152. // get the indexes of the coordinates of each vertex of the facet
  40153. v1x = indices[index * 3] * 3;
  40154. v1y = v1x + 1;
  40155. v1z = v1x + 2;
  40156. v2x = indices[index * 3 + 1] * 3;
  40157. v2y = v2x + 1;
  40158. v2z = v2x + 2;
  40159. v3x = indices[index * 3 + 2] * 3;
  40160. v3y = v3x + 1;
  40161. v3z = v3x + 2;
  40162. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  40163. p1p2y = positions[v1y] - positions[v2y];
  40164. p1p2z = positions[v1z] - positions[v2z];
  40165. p3p2x = positions[v3x] - positions[v2x];
  40166. p3p2y = positions[v3y] - positions[v2y];
  40167. p3p2z = positions[v3z] - positions[v2z];
  40168. // compute the face normal with the cross product
  40169. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  40170. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  40171. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  40172. // normalize this normal and store it in the array facetData
  40173. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40174. length = (length === 0) ? 1.0 : length;
  40175. faceNormalx /= length;
  40176. faceNormaly /= length;
  40177. faceNormalz /= length;
  40178. if (computeFacetNormals && options) {
  40179. options.facetNormals[index].x = faceNormalx;
  40180. options.facetNormals[index].y = faceNormaly;
  40181. options.facetNormals[index].z = faceNormalz;
  40182. }
  40183. if (computeFacetPositions && options) {
  40184. // compute and the facet barycenter coordinates in the array facetPositions
  40185. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  40186. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  40187. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  40188. }
  40189. if (computeFacetPartitioning && options) {
  40190. // store the facet indexes in arrays in the main facetPartitioning array :
  40191. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  40192. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  40193. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  40194. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  40195. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40196. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40197. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40198. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40199. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40200. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40201. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40202. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40203. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40204. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  40205. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  40206. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  40207. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  40208. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  40209. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  40210. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  40211. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  40212. // push each facet index in each block containing the vertex
  40213. options.facetPartitioning[block_idx_v1].push(index);
  40214. if (block_idx_v2 != block_idx_v1) {
  40215. options.facetPartitioning[block_idx_v2].push(index);
  40216. }
  40217. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  40218. options.facetPartitioning[block_idx_v3].push(index);
  40219. }
  40220. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  40221. options.facetPartitioning[block_idx_o].push(index);
  40222. }
  40223. }
  40224. if (computeDepthSort && options && options.facetPositions) {
  40225. var dsf = depthSortedFacets[index];
  40226. dsf.ind = index * 3;
  40227. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  40228. }
  40229. // compute the normals anyway
  40230. normals[v1x] += faceNormalx; // accumulate all the normals per face
  40231. normals[v1y] += faceNormaly;
  40232. normals[v1z] += faceNormalz;
  40233. normals[v2x] += faceNormalx;
  40234. normals[v2y] += faceNormaly;
  40235. normals[v2z] += faceNormalz;
  40236. normals[v3x] += faceNormalx;
  40237. normals[v3y] += faceNormaly;
  40238. normals[v3z] += faceNormalz;
  40239. }
  40240. // last normalization of each normal
  40241. for (index = 0; index < normals.length / 3; index++) {
  40242. faceNormalx = normals[index * 3];
  40243. faceNormaly = normals[index * 3 + 1];
  40244. faceNormalz = normals[index * 3 + 2];
  40245. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40246. length = (length === 0) ? 1.0 : length;
  40247. faceNormalx /= length;
  40248. faceNormaly /= length;
  40249. faceNormalz /= length;
  40250. normals[index * 3] = faceNormalx;
  40251. normals[index * 3 + 1] = faceNormaly;
  40252. normals[index * 3 + 2] = faceNormalz;
  40253. }
  40254. };
  40255. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  40256. var li = indices.length;
  40257. var ln = normals.length;
  40258. var i;
  40259. var n;
  40260. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40261. switch (sideOrientation) {
  40262. case BABYLON.Mesh.FRONTSIDE:
  40263. // nothing changed
  40264. break;
  40265. case BABYLON.Mesh.BACKSIDE:
  40266. var tmp;
  40267. // indices
  40268. for (i = 0; i < li; i += 3) {
  40269. tmp = indices[i];
  40270. indices[i] = indices[i + 2];
  40271. indices[i + 2] = tmp;
  40272. }
  40273. // normals
  40274. for (n = 0; n < ln; n++) {
  40275. normals[n] = -normals[n];
  40276. }
  40277. break;
  40278. case BABYLON.Mesh.DOUBLESIDE:
  40279. // positions
  40280. var lp = positions.length;
  40281. var l = lp / 3;
  40282. for (var p = 0; p < lp; p++) {
  40283. positions[lp + p] = positions[p];
  40284. }
  40285. // indices
  40286. for (i = 0; i < li; i += 3) {
  40287. indices[i + li] = indices[i + 2] + l;
  40288. indices[i + 1 + li] = indices[i + 1] + l;
  40289. indices[i + 2 + li] = indices[i] + l;
  40290. }
  40291. // normals
  40292. for (n = 0; n < ln; n++) {
  40293. normals[ln + n] = -normals[n];
  40294. }
  40295. // uvs
  40296. var lu = uvs.length;
  40297. var u = 0;
  40298. for (u = 0; u < lu; u++) {
  40299. uvs[u + lu] = uvs[u];
  40300. }
  40301. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40302. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40303. u = 0;
  40304. for (i = 0; i < lu / 2; i++) {
  40305. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  40306. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  40307. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  40308. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  40309. u += 2;
  40310. }
  40311. break;
  40312. }
  40313. };
  40314. /**
  40315. * Applies VertexData created from the imported parameters to the geometry
  40316. * @param parsedVertexData the parsed data from an imported file
  40317. * @param geometry the geometry to apply the VertexData to
  40318. */
  40319. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  40320. var vertexData = new VertexData();
  40321. // positions
  40322. var positions = parsedVertexData.positions;
  40323. if (positions) {
  40324. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  40325. }
  40326. // normals
  40327. var normals = parsedVertexData.normals;
  40328. if (normals) {
  40329. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  40330. }
  40331. // tangents
  40332. var tangents = parsedVertexData.tangents;
  40333. if (tangents) {
  40334. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  40335. }
  40336. // uvs
  40337. var uvs = parsedVertexData.uvs;
  40338. if (uvs) {
  40339. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  40340. }
  40341. // uv2s
  40342. var uv2s = parsedVertexData.uv2s;
  40343. if (uv2s) {
  40344. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  40345. }
  40346. // uv3s
  40347. var uv3s = parsedVertexData.uv3s;
  40348. if (uv3s) {
  40349. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  40350. }
  40351. // uv4s
  40352. var uv4s = parsedVertexData.uv4s;
  40353. if (uv4s) {
  40354. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  40355. }
  40356. // uv5s
  40357. var uv5s = parsedVertexData.uv5s;
  40358. if (uv5s) {
  40359. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  40360. }
  40361. // uv6s
  40362. var uv6s = parsedVertexData.uv6s;
  40363. if (uv6s) {
  40364. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  40365. }
  40366. // colors
  40367. var colors = parsedVertexData.colors;
  40368. if (colors) {
  40369. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  40370. }
  40371. // matricesIndices
  40372. var matricesIndices = parsedVertexData.matricesIndices;
  40373. if (matricesIndices) {
  40374. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  40375. }
  40376. // matricesWeights
  40377. var matricesWeights = parsedVertexData.matricesWeights;
  40378. if (matricesWeights) {
  40379. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  40380. }
  40381. // indices
  40382. var indices = parsedVertexData.indices;
  40383. if (indices) {
  40384. vertexData.indices = indices;
  40385. }
  40386. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  40387. };
  40388. return VertexData;
  40389. }());
  40390. BABYLON.VertexData = VertexData;
  40391. })(BABYLON || (BABYLON = {}));
  40392. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  40393. var BABYLON;
  40394. (function (BABYLON) {
  40395. /**
  40396. * Class used to store geometry data (vertex buffers + index buffer)
  40397. */
  40398. var Geometry = /** @class */ (function () {
  40399. /**
  40400. * Creates a new geometry
  40401. * @param id defines the unique ID
  40402. * @param scene defines the hosting scene
  40403. * @param vertexData defines the VertexData used to get geometry data
  40404. * @param updatable defines if geometry must be updatable (false by default)
  40405. * @param mesh defines the mesh that will be associated with the geometry
  40406. */
  40407. function Geometry(id, scene, vertexData, updatable, mesh) {
  40408. if (updatable === void 0) { updatable = false; }
  40409. if (mesh === void 0) { mesh = null; }
  40410. /**
  40411. * Gets the delay loading state of the geometry (none by default which means not delayed)
  40412. */
  40413. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40414. this._totalVertices = 0;
  40415. this._isDisposed = false;
  40416. this._indexBufferIsUpdatable = false;
  40417. this.id = id;
  40418. this._engine = scene.getEngine();
  40419. this._meshes = [];
  40420. this._scene = scene;
  40421. //Init vertex buffer cache
  40422. this._vertexBuffers = {};
  40423. this._indices = [];
  40424. this._updatable = updatable;
  40425. // vertexData
  40426. if (vertexData) {
  40427. this.setAllVerticesData(vertexData, updatable);
  40428. }
  40429. else {
  40430. this._totalVertices = 0;
  40431. this._indices = [];
  40432. }
  40433. if (this._engine.getCaps().vertexArrayObject) {
  40434. this._vertexArrayObjects = {};
  40435. }
  40436. // applyToMesh
  40437. if (mesh) {
  40438. this.applyToMesh(mesh);
  40439. mesh.computeWorldMatrix(true);
  40440. }
  40441. }
  40442. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40443. /**
  40444. * 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
  40445. */
  40446. get: function () {
  40447. return this._boundingBias;
  40448. },
  40449. /**
  40450. * 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
  40451. */
  40452. set: function (value) {
  40453. if (this._boundingBias) {
  40454. this._boundingBias.copyFrom(value);
  40455. }
  40456. else {
  40457. this._boundingBias = value.clone();
  40458. }
  40459. this._updateBoundingInfo(true, null);
  40460. },
  40461. enumerable: true,
  40462. configurable: true
  40463. });
  40464. /**
  40465. * Static function used to attach a new empty geometry to a mesh
  40466. * @param mesh defines the mesh to attach the geometry to
  40467. * @returns the new Geometry
  40468. */
  40469. Geometry.CreateGeometryForMesh = function (mesh) {
  40470. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  40471. geometry.applyToMesh(mesh);
  40472. return geometry;
  40473. };
  40474. Object.defineProperty(Geometry.prototype, "extend", {
  40475. /**
  40476. * Gets the current extend of the geometry
  40477. */
  40478. get: function () {
  40479. return this._extend;
  40480. },
  40481. enumerable: true,
  40482. configurable: true
  40483. });
  40484. /**
  40485. * Gets the hosting scene
  40486. * @returns the hosting Scene
  40487. */
  40488. Geometry.prototype.getScene = function () {
  40489. return this._scene;
  40490. };
  40491. /**
  40492. * Gets the hosting engine
  40493. * @returns the hosting Engine
  40494. */
  40495. Geometry.prototype.getEngine = function () {
  40496. return this._engine;
  40497. };
  40498. /**
  40499. * Defines if the geometry is ready to use
  40500. * @returns true if the geometry is ready to be used
  40501. */
  40502. Geometry.prototype.isReady = function () {
  40503. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40504. };
  40505. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40506. /**
  40507. * Gets a value indicating that the geometry should not be serialized
  40508. */
  40509. get: function () {
  40510. for (var index = 0; index < this._meshes.length; index++) {
  40511. if (!this._meshes[index].doNotSerialize) {
  40512. return false;
  40513. }
  40514. }
  40515. return true;
  40516. },
  40517. enumerable: true,
  40518. configurable: true
  40519. });
  40520. /** @hidden */
  40521. Geometry.prototype._rebuild = function () {
  40522. if (this._vertexArrayObjects) {
  40523. this._vertexArrayObjects = {};
  40524. }
  40525. // Index buffer
  40526. if (this._meshes.length !== 0 && this._indices) {
  40527. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40528. }
  40529. // Vertex buffers
  40530. for (var key in this._vertexBuffers) {
  40531. var vertexBuffer = this._vertexBuffers[key];
  40532. vertexBuffer._rebuild();
  40533. }
  40534. };
  40535. /**
  40536. * Affects all geometry data in one call
  40537. * @param vertexData defines the geometry data
  40538. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  40539. */
  40540. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40541. vertexData.applyToGeometry(this, updatable);
  40542. this.notifyUpdate();
  40543. };
  40544. /**
  40545. * Set specific vertex data
  40546. * @param kind defines the data kind (Position, normal, etc...)
  40547. * @param data defines the vertex data to use
  40548. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  40549. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  40550. */
  40551. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40552. if (updatable === void 0) { updatable = false; }
  40553. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40554. this.setVerticesBuffer(buffer);
  40555. };
  40556. /**
  40557. * Removes a specific vertex data
  40558. * @param kind defines the data kind (Position, normal, etc...)
  40559. */
  40560. Geometry.prototype.removeVerticesData = function (kind) {
  40561. if (this._vertexBuffers[kind]) {
  40562. this._vertexBuffers[kind].dispose();
  40563. delete this._vertexBuffers[kind];
  40564. }
  40565. };
  40566. /**
  40567. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  40568. * @param buffer defines the vertex buffer to use
  40569. * @param totalVertices defines the total number of vertices for position kind (could be null)
  40570. */
  40571. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  40572. if (totalVertices === void 0) { totalVertices = null; }
  40573. var kind = buffer.getKind();
  40574. if (this._vertexBuffers[kind]) {
  40575. this._vertexBuffers[kind].dispose();
  40576. }
  40577. this._vertexBuffers[kind] = buffer;
  40578. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40579. var data = buffer.getData();
  40580. if (totalVertices != null) {
  40581. this._totalVertices = totalVertices;
  40582. }
  40583. else {
  40584. if (data != null) {
  40585. this._totalVertices = data.length / (buffer.byteStride / 4);
  40586. }
  40587. }
  40588. this._updateExtend(data);
  40589. this._resetPointsArrayCache();
  40590. var meshes = this._meshes;
  40591. var numOfMeshes = meshes.length;
  40592. for (var index = 0; index < numOfMeshes; index++) {
  40593. var mesh = meshes[index];
  40594. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40595. mesh._createGlobalSubMesh(false);
  40596. mesh.computeWorldMatrix(true);
  40597. }
  40598. }
  40599. this.notifyUpdate(kind);
  40600. if (this._vertexArrayObjects) {
  40601. this._disposeVertexArrayObjects();
  40602. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40603. }
  40604. };
  40605. /**
  40606. * Update a specific vertex buffer
  40607. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  40608. * It will do nothing if the buffer is not updatable
  40609. * @param kind defines the data kind (Position, normal, etc...)
  40610. * @param data defines the data to use
  40611. * @param offset defines the offset in the target buffer where to store the data
  40612. * @param useBytes set to true if the offset is in bytes
  40613. */
  40614. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  40615. if (useBytes === void 0) { useBytes = false; }
  40616. var vertexBuffer = this.getVertexBuffer(kind);
  40617. if (!vertexBuffer) {
  40618. return;
  40619. }
  40620. vertexBuffer.updateDirectly(data, offset, useBytes);
  40621. this.notifyUpdate(kind);
  40622. };
  40623. /**
  40624. * Update a specific vertex buffer
  40625. * This function will create a new buffer if the current one is not updatable
  40626. * @param kind defines the data kind (Position, normal, etc...)
  40627. * @param data defines the data to use
  40628. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  40629. */
  40630. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40631. if (updateExtends === void 0) { updateExtends = false; }
  40632. var vertexBuffer = this.getVertexBuffer(kind);
  40633. if (!vertexBuffer) {
  40634. return;
  40635. }
  40636. vertexBuffer.update(data);
  40637. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40638. this._updateBoundingInfo(updateExtends, data);
  40639. }
  40640. this.notifyUpdate(kind);
  40641. };
  40642. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  40643. if (updateExtends) {
  40644. this._updateExtend(data);
  40645. }
  40646. this._resetPointsArrayCache();
  40647. if (updateExtends) {
  40648. var meshes = this._meshes;
  40649. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  40650. var mesh = meshes_1[_i];
  40651. if (mesh._boundingInfo) {
  40652. mesh._boundingInfo.reConstruct(this._extend.minimum, this._extend.maximum);
  40653. }
  40654. else {
  40655. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40656. }
  40657. var subMeshes = mesh.subMeshes;
  40658. for (var _a = 0, subMeshes_1 = subMeshes; _a < subMeshes_1.length; _a++) {
  40659. var subMesh = subMeshes_1[_a];
  40660. subMesh.refreshBoundingInfo();
  40661. }
  40662. }
  40663. }
  40664. };
  40665. /** @hidden */
  40666. Geometry.prototype._bind = function (effect, indexToBind) {
  40667. if (!effect) {
  40668. return;
  40669. }
  40670. if (indexToBind === undefined) {
  40671. indexToBind = this._indexBuffer;
  40672. }
  40673. var vbs = this.getVertexBuffers();
  40674. if (!vbs) {
  40675. return;
  40676. }
  40677. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40678. this._engine.bindBuffers(vbs, indexToBind, effect);
  40679. return;
  40680. }
  40681. // Using VAO
  40682. if (!this._vertexArrayObjects[effect.key]) {
  40683. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  40684. }
  40685. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40686. };
  40687. /**
  40688. * Gets total number of vertices
  40689. * @returns the total number of vertices
  40690. */
  40691. Geometry.prototype.getTotalVertices = function () {
  40692. if (!this.isReady()) {
  40693. return 0;
  40694. }
  40695. return this._totalVertices;
  40696. };
  40697. /**
  40698. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  40699. * @param kind defines the data kind (Position, normal, etc...)
  40700. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40701. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40702. * @returns a float array containing vertex data
  40703. */
  40704. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  40705. var vertexBuffer = this.getVertexBuffer(kind);
  40706. if (!vertexBuffer) {
  40707. return null;
  40708. }
  40709. var data = vertexBuffer.getData();
  40710. if (!data) {
  40711. return null;
  40712. }
  40713. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  40714. var count = this._totalVertices * vertexBuffer.getSize();
  40715. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  40716. var copy_1 = [];
  40717. vertexBuffer.forEach(count, function (value) { return copy_1.push(value); });
  40718. return copy_1;
  40719. }
  40720. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  40721. if (data instanceof Array) {
  40722. var offset = vertexBuffer.byteOffset / 4;
  40723. return BABYLON.Tools.Slice(data, offset, offset + count);
  40724. }
  40725. else if (data instanceof ArrayBuffer) {
  40726. return new Float32Array(data, vertexBuffer.byteOffset, count);
  40727. }
  40728. else {
  40729. var offset = data.byteOffset + vertexBuffer.byteOffset;
  40730. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40731. var result = new Float32Array(count);
  40732. var source = new Float32Array(data.buffer, offset, count);
  40733. result.set(source);
  40734. return result;
  40735. }
  40736. return new Float32Array(data.buffer, offset, count);
  40737. }
  40738. }
  40739. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40740. return BABYLON.Tools.Slice(data);
  40741. }
  40742. return data;
  40743. };
  40744. /**
  40745. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  40746. * @param kind defines the data kind (Position, normal, etc...)
  40747. * @returns true if the vertex buffer with the specified kind is updatable
  40748. */
  40749. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  40750. var vb = this._vertexBuffers[kind];
  40751. if (!vb) {
  40752. return false;
  40753. }
  40754. return vb.isUpdatable();
  40755. };
  40756. /**
  40757. * Gets a specific vertex buffer
  40758. * @param kind defines the data kind (Position, normal, etc...)
  40759. * @returns a VertexBuffer
  40760. */
  40761. Geometry.prototype.getVertexBuffer = function (kind) {
  40762. if (!this.isReady()) {
  40763. return null;
  40764. }
  40765. return this._vertexBuffers[kind];
  40766. };
  40767. /**
  40768. * Returns all vertex buffers
  40769. * @return an object holding all vertex buffers indexed by kind
  40770. */
  40771. Geometry.prototype.getVertexBuffers = function () {
  40772. if (!this.isReady()) {
  40773. return null;
  40774. }
  40775. return this._vertexBuffers;
  40776. };
  40777. /**
  40778. * Gets a boolean indicating if specific vertex buffer is present
  40779. * @param kind defines the data kind (Position, normal, etc...)
  40780. * @returns true if data is present
  40781. */
  40782. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40783. if (!this._vertexBuffers) {
  40784. if (this._delayInfo) {
  40785. return this._delayInfo.indexOf(kind) !== -1;
  40786. }
  40787. return false;
  40788. }
  40789. return this._vertexBuffers[kind] !== undefined;
  40790. };
  40791. /**
  40792. * Gets a list of all attached data kinds (Position, normal, etc...)
  40793. * @returns a list of string containing all kinds
  40794. */
  40795. Geometry.prototype.getVerticesDataKinds = function () {
  40796. var result = [];
  40797. var kind;
  40798. if (!this._vertexBuffers && this._delayInfo) {
  40799. for (kind in this._delayInfo) {
  40800. result.push(kind);
  40801. }
  40802. }
  40803. else {
  40804. for (kind in this._vertexBuffers) {
  40805. result.push(kind);
  40806. }
  40807. }
  40808. return result;
  40809. };
  40810. /**
  40811. * Update index buffer
  40812. * @param indices defines the indices to store in the index buffer
  40813. * @param offset defines the offset in the target buffer where to store the data
  40814. */
  40815. Geometry.prototype.updateIndices = function (indices, offset) {
  40816. if (!this._indexBuffer) {
  40817. return;
  40818. }
  40819. if (!this._indexBufferIsUpdatable) {
  40820. this.setIndices(indices, null, true);
  40821. }
  40822. else {
  40823. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40824. }
  40825. };
  40826. /**
  40827. * Creates a new index buffer
  40828. * @param indices defines the indices to store in the index buffer
  40829. * @param totalVertices defines the total number of vertices (could be null)
  40830. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40831. */
  40832. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40833. if (totalVertices === void 0) { totalVertices = null; }
  40834. if (updatable === void 0) { updatable = false; }
  40835. if (this._indexBuffer) {
  40836. this._engine._releaseBuffer(this._indexBuffer);
  40837. }
  40838. this._disposeVertexArrayObjects();
  40839. this._indices = indices;
  40840. this._indexBufferIsUpdatable = updatable;
  40841. if (this._meshes.length !== 0 && this._indices) {
  40842. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40843. }
  40844. if (totalVertices != undefined) { // including null and undefined
  40845. this._totalVertices = totalVertices;
  40846. }
  40847. var meshes = this._meshes;
  40848. var numOfMeshes = meshes.length;
  40849. for (var index = 0; index < numOfMeshes; index++) {
  40850. meshes[index]._createGlobalSubMesh(true);
  40851. }
  40852. this.notifyUpdate();
  40853. };
  40854. /**
  40855. * Return the total number of indices
  40856. * @returns the total number of indices
  40857. */
  40858. Geometry.prototype.getTotalIndices = function () {
  40859. if (!this.isReady()) {
  40860. return 0;
  40861. }
  40862. return this._indices.length;
  40863. };
  40864. /**
  40865. * Gets the index buffer array
  40866. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40867. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40868. * @returns the index buffer array
  40869. */
  40870. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40871. if (!this.isReady()) {
  40872. return null;
  40873. }
  40874. var orig = this._indices;
  40875. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40876. return orig;
  40877. }
  40878. else {
  40879. var len = orig.length;
  40880. var copy = [];
  40881. for (var i = 0; i < len; i++) {
  40882. copy.push(orig[i]);
  40883. }
  40884. return copy;
  40885. }
  40886. };
  40887. /**
  40888. * Gets the index buffer
  40889. * @return the index buffer
  40890. */
  40891. Geometry.prototype.getIndexBuffer = function () {
  40892. if (!this.isReady()) {
  40893. return null;
  40894. }
  40895. return this._indexBuffer;
  40896. };
  40897. /** @hidden */
  40898. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  40899. if (effect === void 0) { effect = null; }
  40900. if (!effect || !this._vertexArrayObjects) {
  40901. return;
  40902. }
  40903. if (this._vertexArrayObjects[effect.key]) {
  40904. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  40905. delete this._vertexArrayObjects[effect.key];
  40906. }
  40907. };
  40908. /**
  40909. * Release the associated resources for a specific mesh
  40910. * @param mesh defines the source mesh
  40911. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  40912. */
  40913. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40914. var meshes = this._meshes;
  40915. var index = meshes.indexOf(mesh);
  40916. if (index === -1) {
  40917. return;
  40918. }
  40919. meshes.splice(index, 1);
  40920. mesh._geometry = null;
  40921. if (meshes.length === 0 && shouldDispose) {
  40922. this.dispose();
  40923. }
  40924. };
  40925. /**
  40926. * Apply current geometry to a given mesh
  40927. * @param mesh defines the mesh to apply geometry to
  40928. */
  40929. Geometry.prototype.applyToMesh = function (mesh) {
  40930. if (mesh._geometry === this) {
  40931. return;
  40932. }
  40933. var previousGeometry = mesh._geometry;
  40934. if (previousGeometry) {
  40935. previousGeometry.releaseForMesh(mesh);
  40936. }
  40937. var meshes = this._meshes;
  40938. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40939. mesh._geometry = this;
  40940. this._scene.pushGeometry(this);
  40941. meshes.push(mesh);
  40942. if (this.isReady()) {
  40943. this._applyToMesh(mesh);
  40944. }
  40945. else {
  40946. mesh._boundingInfo = this._boundingInfo;
  40947. }
  40948. };
  40949. Geometry.prototype._updateExtend = function (data) {
  40950. if (data === void 0) { data = null; }
  40951. if (!data) {
  40952. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40953. }
  40954. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  40955. };
  40956. Geometry.prototype._applyToMesh = function (mesh) {
  40957. var numOfMeshes = this._meshes.length;
  40958. // vertexBuffers
  40959. for (var kind in this._vertexBuffers) {
  40960. if (numOfMeshes === 1) {
  40961. this._vertexBuffers[kind].create();
  40962. }
  40963. var buffer = this._vertexBuffers[kind].getBuffer();
  40964. if (buffer) {
  40965. buffer.references = numOfMeshes;
  40966. }
  40967. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40968. if (!this._extend) {
  40969. this._updateExtend();
  40970. }
  40971. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40972. mesh._createGlobalSubMesh(false);
  40973. //bounding info was just created again, world matrix should be applied again.
  40974. mesh._updateBoundingInfo();
  40975. }
  40976. }
  40977. // indexBuffer
  40978. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  40979. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40980. }
  40981. if (this._indexBuffer) {
  40982. this._indexBuffer.references = numOfMeshes;
  40983. }
  40984. // morphTargets
  40985. mesh._syncGeometryWithMorphTargetManager();
  40986. };
  40987. Geometry.prototype.notifyUpdate = function (kind) {
  40988. if (this.onGeometryUpdated) {
  40989. this.onGeometryUpdated(this, kind);
  40990. }
  40991. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  40992. var mesh = _a[_i];
  40993. mesh._markSubMeshesAsAttributesDirty();
  40994. }
  40995. };
  40996. /**
  40997. * Load the geometry if it was flagged as delay loaded
  40998. * @param scene defines the hosting scene
  40999. * @param onLoaded defines a callback called when the geometry is loaded
  41000. */
  41001. Geometry.prototype.load = function (scene, onLoaded) {
  41002. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  41003. return;
  41004. }
  41005. if (this.isReady()) {
  41006. if (onLoaded) {
  41007. onLoaded();
  41008. }
  41009. return;
  41010. }
  41011. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  41012. this._queueLoad(scene, onLoaded);
  41013. };
  41014. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  41015. var _this = this;
  41016. if (!this.delayLoadingFile) {
  41017. return;
  41018. }
  41019. scene._addPendingData(this);
  41020. scene._loadFile(this.delayLoadingFile, function (data) {
  41021. if (!_this._delayLoadingFunction) {
  41022. return;
  41023. }
  41024. _this._delayLoadingFunction(JSON.parse(data), _this);
  41025. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41026. _this._delayInfo = [];
  41027. scene._removePendingData(_this);
  41028. var meshes = _this._meshes;
  41029. var numOfMeshes = meshes.length;
  41030. for (var index = 0; index < numOfMeshes; index++) {
  41031. _this._applyToMesh(meshes[index]);
  41032. }
  41033. if (onLoaded) {
  41034. onLoaded();
  41035. }
  41036. }, undefined, true);
  41037. };
  41038. /**
  41039. * Invert the geometry to move from a right handed system to a left handed one.
  41040. */
  41041. Geometry.prototype.toLeftHanded = function () {
  41042. // Flip faces
  41043. var tIndices = this.getIndices(false);
  41044. if (tIndices != null && tIndices.length > 0) {
  41045. for (var i = 0; i < tIndices.length; i += 3) {
  41046. var tTemp = tIndices[i + 0];
  41047. tIndices[i + 0] = tIndices[i + 2];
  41048. tIndices[i + 2] = tTemp;
  41049. }
  41050. this.setIndices(tIndices);
  41051. }
  41052. // Negate position.z
  41053. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  41054. if (tPositions != null && tPositions.length > 0) {
  41055. for (var i = 0; i < tPositions.length; i += 3) {
  41056. tPositions[i + 2] = -tPositions[i + 2];
  41057. }
  41058. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  41059. }
  41060. // Negate normal.z
  41061. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  41062. if (tNormals != null && tNormals.length > 0) {
  41063. for (var i = 0; i < tNormals.length; i += 3) {
  41064. tNormals[i + 2] = -tNormals[i + 2];
  41065. }
  41066. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  41067. }
  41068. };
  41069. // Cache
  41070. /** @hidden */
  41071. Geometry.prototype._resetPointsArrayCache = function () {
  41072. this._positions = null;
  41073. };
  41074. /** @hidden */
  41075. Geometry.prototype._generatePointsArray = function () {
  41076. if (this._positions) {
  41077. return true;
  41078. }
  41079. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41080. if (!data || data.length === 0) {
  41081. return false;
  41082. }
  41083. this._positions = [];
  41084. for (var index = 0; index < data.length; index += 3) {
  41085. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  41086. }
  41087. return true;
  41088. };
  41089. /**
  41090. * Gets a value indicating if the geometry is disposed
  41091. * @returns true if the geometry was disposed
  41092. */
  41093. Geometry.prototype.isDisposed = function () {
  41094. return this._isDisposed;
  41095. };
  41096. Geometry.prototype._disposeVertexArrayObjects = function () {
  41097. if (this._vertexArrayObjects) {
  41098. for (var kind in this._vertexArrayObjects) {
  41099. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  41100. }
  41101. this._vertexArrayObjects = {};
  41102. }
  41103. };
  41104. /**
  41105. * Free all associated resources
  41106. */
  41107. Geometry.prototype.dispose = function () {
  41108. var meshes = this._meshes;
  41109. var numOfMeshes = meshes.length;
  41110. var index;
  41111. for (index = 0; index < numOfMeshes; index++) {
  41112. this.releaseForMesh(meshes[index]);
  41113. }
  41114. this._meshes = [];
  41115. this._disposeVertexArrayObjects();
  41116. for (var kind in this._vertexBuffers) {
  41117. this._vertexBuffers[kind].dispose();
  41118. }
  41119. this._vertexBuffers = {};
  41120. this._totalVertices = 0;
  41121. if (this._indexBuffer) {
  41122. this._engine._releaseBuffer(this._indexBuffer);
  41123. }
  41124. this._indexBuffer = null;
  41125. this._indices = [];
  41126. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  41127. this.delayLoadingFile = null;
  41128. this._delayLoadingFunction = null;
  41129. this._delayInfo = [];
  41130. this._boundingInfo = null;
  41131. this._scene.removeGeometry(this);
  41132. this._isDisposed = true;
  41133. };
  41134. /**
  41135. * Clone the current geometry into a new geometry
  41136. * @param id defines the unique ID of the new geometry
  41137. * @returns a new geometry object
  41138. */
  41139. Geometry.prototype.copy = function (id) {
  41140. var vertexData = new BABYLON.VertexData();
  41141. vertexData.indices = [];
  41142. var indices = this.getIndices();
  41143. if (indices) {
  41144. for (var index = 0; index < indices.length; index++) {
  41145. vertexData.indices.push(indices[index]);
  41146. }
  41147. }
  41148. var updatable = false;
  41149. var stopChecking = false;
  41150. var kind;
  41151. for (kind in this._vertexBuffers) {
  41152. // using slice() to make a copy of the array and not just reference it
  41153. var data = this.getVerticesData(kind);
  41154. if (data instanceof Float32Array) {
  41155. vertexData.set(new Float32Array(data), kind);
  41156. }
  41157. else {
  41158. vertexData.set(data.slice(0), kind);
  41159. }
  41160. if (!stopChecking) {
  41161. var vb = this.getVertexBuffer(kind);
  41162. if (vb) {
  41163. updatable = vb.isUpdatable();
  41164. stopChecking = !updatable;
  41165. }
  41166. }
  41167. }
  41168. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  41169. geometry.delayLoadState = this.delayLoadState;
  41170. geometry.delayLoadingFile = this.delayLoadingFile;
  41171. geometry._delayLoadingFunction = this._delayLoadingFunction;
  41172. for (kind in this._delayInfo) {
  41173. geometry._delayInfo = geometry._delayInfo || [];
  41174. geometry._delayInfo.push(kind);
  41175. }
  41176. // Bounding info
  41177. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41178. return geometry;
  41179. };
  41180. /**
  41181. * Serialize the current geometry info (and not the vertices data) into a JSON object
  41182. * @return a JSON representation of the current geometry data (without the vertices data)
  41183. */
  41184. Geometry.prototype.serialize = function () {
  41185. var serializationObject = {};
  41186. serializationObject.id = this.id;
  41187. serializationObject.updatable = this._updatable;
  41188. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  41189. serializationObject.tags = BABYLON.Tags.GetTags(this);
  41190. }
  41191. return serializationObject;
  41192. };
  41193. Geometry.prototype.toNumberArray = function (origin) {
  41194. if (Array.isArray(origin)) {
  41195. return origin;
  41196. }
  41197. else {
  41198. return Array.prototype.slice.call(origin);
  41199. }
  41200. };
  41201. /**
  41202. * Serialize all vertices data into a JSON oject
  41203. * @returns a JSON representation of the current geometry data
  41204. */
  41205. Geometry.prototype.serializeVerticeData = function () {
  41206. var serializationObject = this.serialize();
  41207. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  41208. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  41209. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  41210. serializationObject.positions._updatable = true;
  41211. }
  41212. }
  41213. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41214. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  41215. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  41216. serializationObject.normals._updatable = true;
  41217. }
  41218. }
  41219. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41220. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  41221. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  41222. serializationObject.tangets._updatable = true;
  41223. }
  41224. }
  41225. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41226. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  41227. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  41228. serializationObject.uvs._updatable = true;
  41229. }
  41230. }
  41231. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41232. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  41233. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  41234. serializationObject.uv2s._updatable = true;
  41235. }
  41236. }
  41237. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41238. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  41239. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  41240. serializationObject.uv3s._updatable = true;
  41241. }
  41242. }
  41243. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41244. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  41245. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  41246. serializationObject.uv4s._updatable = true;
  41247. }
  41248. }
  41249. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41250. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  41251. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  41252. serializationObject.uv5s._updatable = true;
  41253. }
  41254. }
  41255. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41256. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  41257. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  41258. serializationObject.uv6s._updatable = true;
  41259. }
  41260. }
  41261. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41262. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  41263. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  41264. serializationObject.colors._updatable = true;
  41265. }
  41266. }
  41267. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41268. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  41269. serializationObject.matricesIndices._isExpanded = true;
  41270. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41271. serializationObject.matricesIndices._updatable = true;
  41272. }
  41273. }
  41274. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41275. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  41276. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41277. serializationObject.matricesWeights._updatable = true;
  41278. }
  41279. }
  41280. serializationObject.indices = this.toNumberArray(this.getIndices());
  41281. return serializationObject;
  41282. };
  41283. // Statics
  41284. /**
  41285. * Extracts a clone of a mesh geometry
  41286. * @param mesh defines the source mesh
  41287. * @param id defines the unique ID of the new geometry object
  41288. * @returns the new geometry object
  41289. */
  41290. Geometry.ExtractFromMesh = function (mesh, id) {
  41291. var geometry = mesh._geometry;
  41292. if (!geometry) {
  41293. return null;
  41294. }
  41295. return geometry.copy(id);
  41296. };
  41297. /**
  41298. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41299. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41300. * Be aware Math.random() could cause collisions, but:
  41301. * "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"
  41302. * @returns a string containing a new GUID
  41303. */
  41304. Geometry.RandomId = function () {
  41305. return BABYLON.Tools.RandomId();
  41306. };
  41307. /** @hidden */
  41308. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  41309. var scene = mesh.getScene();
  41310. // Geometry
  41311. var geometryId = parsedGeometry.geometryId;
  41312. if (geometryId) {
  41313. var geometry = scene.getGeometryByID(geometryId);
  41314. if (geometry) {
  41315. geometry.applyToMesh(mesh);
  41316. }
  41317. }
  41318. else if (parsedGeometry instanceof ArrayBuffer) {
  41319. var binaryInfo = mesh._binaryInfo;
  41320. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41321. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41322. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41323. }
  41324. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41325. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41326. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41327. }
  41328. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  41329. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  41330. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  41331. }
  41332. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41333. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41334. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41335. }
  41336. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41337. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41338. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41339. }
  41340. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41341. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41342. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41343. }
  41344. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41345. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41346. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41347. }
  41348. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41349. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41350. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41351. }
  41352. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41353. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41354. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41355. }
  41356. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41357. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41358. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41359. }
  41360. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41361. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41362. var floatIndices = [];
  41363. for (var i = 0; i < matricesIndicesData.length; i++) {
  41364. var index = matricesIndicesData[i];
  41365. floatIndices.push(index & 0x000000FF);
  41366. floatIndices.push((index & 0x0000FF00) >> 8);
  41367. floatIndices.push((index & 0x00FF0000) >> 16);
  41368. floatIndices.push(index >> 24);
  41369. }
  41370. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  41371. }
  41372. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41373. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41374. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41375. }
  41376. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41377. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41378. mesh.setIndices(indicesData, null);
  41379. }
  41380. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41381. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41382. mesh.subMeshes = [];
  41383. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41384. var materialIndex = subMeshesData[(i * 5) + 0];
  41385. var verticesStart = subMeshesData[(i * 5) + 1];
  41386. var verticesCount = subMeshesData[(i * 5) + 2];
  41387. var indexStart = subMeshesData[(i * 5) + 3];
  41388. var indexCount = subMeshesData[(i * 5) + 4];
  41389. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41390. }
  41391. }
  41392. }
  41393. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41394. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41395. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41396. if (parsedGeometry.tangents) {
  41397. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  41398. }
  41399. if (parsedGeometry.uvs) {
  41400. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41401. }
  41402. if (parsedGeometry.uvs2) {
  41403. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41404. }
  41405. if (parsedGeometry.uvs3) {
  41406. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41407. }
  41408. if (parsedGeometry.uvs4) {
  41409. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41410. }
  41411. if (parsedGeometry.uvs5) {
  41412. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41413. }
  41414. if (parsedGeometry.uvs6) {
  41415. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41416. }
  41417. if (parsedGeometry.colors) {
  41418. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41419. }
  41420. if (parsedGeometry.matricesIndices) {
  41421. if (!parsedGeometry.matricesIndices._isExpanded) {
  41422. var floatIndices = [];
  41423. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41424. var matricesIndex = parsedGeometry.matricesIndices[i];
  41425. floatIndices.push(matricesIndex & 0x000000FF);
  41426. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41427. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41428. floatIndices.push(matricesIndex >> 24);
  41429. }
  41430. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41431. }
  41432. else {
  41433. delete parsedGeometry.matricesIndices._isExpanded;
  41434. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41435. }
  41436. }
  41437. if (parsedGeometry.matricesIndicesExtra) {
  41438. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41439. var floatIndices = [];
  41440. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41441. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41442. floatIndices.push(matricesIndex & 0x000000FF);
  41443. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41444. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41445. floatIndices.push(matricesIndex >> 24);
  41446. }
  41447. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41448. }
  41449. else {
  41450. delete parsedGeometry.matricesIndices._isExpanded;
  41451. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41452. }
  41453. }
  41454. if (parsedGeometry.matricesWeights) {
  41455. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  41456. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41457. }
  41458. if (parsedGeometry.matricesWeightsExtra) {
  41459. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41460. }
  41461. mesh.setIndices(parsedGeometry.indices, null);
  41462. }
  41463. // SubMeshes
  41464. if (parsedGeometry.subMeshes) {
  41465. mesh.subMeshes = [];
  41466. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41467. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41468. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41469. }
  41470. }
  41471. // Flat shading
  41472. if (mesh._shouldGenerateFlatShading) {
  41473. mesh.convertToFlatShadedMesh();
  41474. delete mesh._shouldGenerateFlatShading;
  41475. }
  41476. // Update
  41477. mesh.computeWorldMatrix(true);
  41478. scene.onMeshImportedObservable.notifyObservers(mesh);
  41479. };
  41480. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  41481. var epsilon = 1e-3;
  41482. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  41483. return;
  41484. }
  41485. var noInfluenceBoneIndex = 0.0;
  41486. if (parsedGeometry.skeletonId > -1) {
  41487. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  41488. if (!skeleton) {
  41489. return;
  41490. }
  41491. noInfluenceBoneIndex = skeleton.bones.length;
  41492. }
  41493. else {
  41494. return;
  41495. }
  41496. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41497. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41498. var matricesWeights = parsedGeometry.matricesWeights;
  41499. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  41500. var influencers = parsedGeometry.numBoneInfluencer;
  41501. var size = matricesWeights.length;
  41502. for (var i = 0; i < size; i += 4) {
  41503. var weight = 0.0;
  41504. var firstZeroWeight = -1;
  41505. for (var j = 0; j < 4; j++) {
  41506. var w = matricesWeights[i + j];
  41507. weight += w;
  41508. if (w < epsilon && firstZeroWeight < 0) {
  41509. firstZeroWeight = j;
  41510. }
  41511. }
  41512. if (matricesWeightsExtra) {
  41513. for (var j = 0; j < 4; j++) {
  41514. var w = matricesWeightsExtra[i + j];
  41515. weight += w;
  41516. if (w < epsilon && firstZeroWeight < 0) {
  41517. firstZeroWeight = j + 4;
  41518. }
  41519. }
  41520. }
  41521. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  41522. firstZeroWeight = influencers - 1;
  41523. }
  41524. if (weight > epsilon) {
  41525. var mweight = 1.0 / weight;
  41526. for (var j = 0; j < 4; j++) {
  41527. matricesWeights[i + j] *= mweight;
  41528. }
  41529. if (matricesWeightsExtra) {
  41530. for (var j = 0; j < 4; j++) {
  41531. matricesWeightsExtra[i + j] *= mweight;
  41532. }
  41533. }
  41534. }
  41535. else {
  41536. if (firstZeroWeight >= 4) {
  41537. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  41538. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  41539. }
  41540. else {
  41541. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  41542. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  41543. }
  41544. }
  41545. }
  41546. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  41547. if (parsedGeometry.matricesWeightsExtra) {
  41548. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  41549. }
  41550. };
  41551. /**
  41552. * Create a new geometry from persisted data (Using .babylon file format)
  41553. * @param parsedVertexData defines the persisted data
  41554. * @param scene defines the hosting scene
  41555. * @param rootUrl defines the root url to use to load assets (like delayed data)
  41556. * @returns the new geometry object
  41557. */
  41558. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41559. if (scene.getGeometryByID(parsedVertexData.id)) {
  41560. return null; // null since geometry could be something else than a box...
  41561. }
  41562. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  41563. if (BABYLON.Tags) {
  41564. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41565. }
  41566. if (parsedVertexData.delayLoadingFile) {
  41567. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41568. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41569. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41570. geometry._delayInfo = [];
  41571. if (parsedVertexData.hasUVs) {
  41572. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41573. }
  41574. if (parsedVertexData.hasUVs2) {
  41575. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41576. }
  41577. if (parsedVertexData.hasUVs3) {
  41578. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41579. }
  41580. if (parsedVertexData.hasUVs4) {
  41581. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41582. }
  41583. if (parsedVertexData.hasUVs5) {
  41584. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41585. }
  41586. if (parsedVertexData.hasUVs6) {
  41587. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41588. }
  41589. if (parsedVertexData.hasColors) {
  41590. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41591. }
  41592. if (parsedVertexData.hasMatricesIndices) {
  41593. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41594. }
  41595. if (parsedVertexData.hasMatricesWeights) {
  41596. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41597. }
  41598. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41599. }
  41600. else {
  41601. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41602. }
  41603. scene.pushGeometry(geometry, true);
  41604. return geometry;
  41605. };
  41606. return Geometry;
  41607. }());
  41608. BABYLON.Geometry = Geometry;
  41609. // Primitives
  41610. /// Abstract class
  41611. /**
  41612. * Abstract class used to provide common services for all typed geometries
  41613. * @hidden
  41614. */
  41615. var _PrimitiveGeometry = /** @class */ (function (_super) {
  41616. __extends(_PrimitiveGeometry, _super);
  41617. /**
  41618. * Creates a new typed geometry
  41619. * @param id defines the unique ID of the geometry
  41620. * @param scene defines the hosting scene
  41621. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41622. * @param mesh defines the hosting mesh (can be null)
  41623. */
  41624. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  41625. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  41626. if (mesh === void 0) { mesh = null; }
  41627. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  41628. _this._canBeRegenerated = _canBeRegenerated;
  41629. _this._beingRegenerated = true;
  41630. _this.regenerate();
  41631. _this._beingRegenerated = false;
  41632. return _this;
  41633. }
  41634. /**
  41635. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  41636. * @returns true if the geometry can be regenerated
  41637. */
  41638. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  41639. return this._canBeRegenerated;
  41640. };
  41641. /**
  41642. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  41643. */
  41644. _PrimitiveGeometry.prototype.regenerate = function () {
  41645. if (!this._canBeRegenerated) {
  41646. return;
  41647. }
  41648. this._beingRegenerated = true;
  41649. this.setAllVerticesData(this._regenerateVertexData(), false);
  41650. this._beingRegenerated = false;
  41651. };
  41652. /**
  41653. * Clone the geometry
  41654. * @param id defines the unique ID of the new geometry
  41655. * @returns the new geometry
  41656. */
  41657. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  41658. return _super.prototype.copy.call(this, id);
  41659. };
  41660. // overrides
  41661. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  41662. if (!this._beingRegenerated) {
  41663. return;
  41664. }
  41665. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41666. };
  41667. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  41668. if (!this._beingRegenerated) {
  41669. return;
  41670. }
  41671. _super.prototype.setVerticesData.call(this, kind, data, false);
  41672. };
  41673. // to override
  41674. /** @hidden */
  41675. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  41676. throw new Error("Abstract method");
  41677. };
  41678. _PrimitiveGeometry.prototype.copy = function (id) {
  41679. throw new Error("Must be overriden in sub-classes.");
  41680. };
  41681. _PrimitiveGeometry.prototype.serialize = function () {
  41682. var serializationObject = _super.prototype.serialize.call(this);
  41683. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41684. return serializationObject;
  41685. };
  41686. return _PrimitiveGeometry;
  41687. }(Geometry));
  41688. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  41689. /**
  41690. * Creates a ribbon geometry
  41691. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  41692. */
  41693. var RibbonGeometry = /** @class */ (function (_super) {
  41694. __extends(RibbonGeometry, _super);
  41695. /**
  41696. * Creates a ribbon geometry
  41697. * @param id defines the unique ID of the geometry
  41698. * @param scene defines the hosting scene
  41699. * @param pathArray defines the array of paths to use
  41700. * @param closeArray defines if the last path and the first path must be joined
  41701. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  41702. * @param offset defines the offset between points
  41703. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41704. * @param mesh defines the hosting mesh (can be null)
  41705. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41706. */
  41707. function RibbonGeometry(id, scene,
  41708. /**
  41709. * Defines the array of paths to use
  41710. */
  41711. pathArray,
  41712. /**
  41713. * Defines if the last and first points of each path in your pathArray must be joined
  41714. */
  41715. closeArray,
  41716. /**
  41717. * Defines if the last and first points of each path in your pathArray must be joined
  41718. */
  41719. closePath,
  41720. /**
  41721. * Defines the offset between points
  41722. */
  41723. offset, canBeRegenerated, mesh,
  41724. /**
  41725. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41726. */
  41727. side) {
  41728. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41729. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41730. _this.pathArray = pathArray;
  41731. _this.closeArray = closeArray;
  41732. _this.closePath = closePath;
  41733. _this.offset = offset;
  41734. _this.side = side;
  41735. return _this;
  41736. }
  41737. /** @hidden */
  41738. RibbonGeometry.prototype._regenerateVertexData = function () {
  41739. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41740. };
  41741. RibbonGeometry.prototype.copy = function (id) {
  41742. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  41743. };
  41744. return RibbonGeometry;
  41745. }(_PrimitiveGeometry));
  41746. BABYLON.RibbonGeometry = RibbonGeometry;
  41747. /**
  41748. * Creates a box geometry
  41749. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  41750. */
  41751. var BoxGeometry = /** @class */ (function (_super) {
  41752. __extends(BoxGeometry, _super);
  41753. /**
  41754. * Creates a box geometry
  41755. * @param id defines the unique ID of the geometry
  41756. * @param scene defines the hosting scene
  41757. * @param size defines the zise of the box (width, height and depth are the same)
  41758. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41759. * @param mesh defines the hosting mesh (can be null)
  41760. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41761. */
  41762. function BoxGeometry(id, scene,
  41763. /**
  41764. * Defines the zise of the box (width, height and depth are the same)
  41765. */
  41766. size, canBeRegenerated, mesh,
  41767. /**
  41768. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41769. */
  41770. side) {
  41771. if (mesh === void 0) { mesh = null; }
  41772. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41773. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41774. _this.size = size;
  41775. _this.side = side;
  41776. return _this;
  41777. }
  41778. /** @hidden */
  41779. BoxGeometry.prototype._regenerateVertexData = function () {
  41780. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41781. };
  41782. BoxGeometry.prototype.copy = function (id) {
  41783. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  41784. };
  41785. BoxGeometry.prototype.serialize = function () {
  41786. var serializationObject = _super.prototype.serialize.call(this);
  41787. serializationObject.size = this.size;
  41788. return serializationObject;
  41789. };
  41790. BoxGeometry.Parse = function (parsedBox, scene) {
  41791. if (scene.getGeometryByID(parsedBox.id)) {
  41792. return null; // null since geometry could be something else than a box...
  41793. }
  41794. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41795. if (BABYLON.Tags) {
  41796. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41797. }
  41798. scene.pushGeometry(box, true);
  41799. return box;
  41800. };
  41801. return BoxGeometry;
  41802. }(_PrimitiveGeometry));
  41803. BABYLON.BoxGeometry = BoxGeometry;
  41804. /**
  41805. * Creates a sphere geometry
  41806. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  41807. */
  41808. var SphereGeometry = /** @class */ (function (_super) {
  41809. __extends(SphereGeometry, _super);
  41810. /**
  41811. * Create a new sphere geometry
  41812. * @param id defines the unique ID of the geometry
  41813. * @param scene defines the hosting scene
  41814. * @param segments defines the number of segments to use to create the sphere
  41815. * @param diameter defines the diameter of the sphere
  41816. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41817. * @param mesh defines the hosting mesh (can be null)
  41818. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41819. */
  41820. function SphereGeometry(id, scene,
  41821. /**
  41822. * Defines the number of segments to use to create the sphere
  41823. */
  41824. segments,
  41825. /**
  41826. * Defines the diameter of the sphere
  41827. */
  41828. diameter, canBeRegenerated, mesh,
  41829. /**
  41830. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41831. */
  41832. side) {
  41833. if (mesh === void 0) { mesh = null; }
  41834. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41835. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41836. _this.segments = segments;
  41837. _this.diameter = diameter;
  41838. _this.side = side;
  41839. return _this;
  41840. }
  41841. /** @hidden */
  41842. SphereGeometry.prototype._regenerateVertexData = function () {
  41843. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41844. };
  41845. SphereGeometry.prototype.copy = function (id) {
  41846. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41847. };
  41848. SphereGeometry.prototype.serialize = function () {
  41849. var serializationObject = _super.prototype.serialize.call(this);
  41850. serializationObject.segments = this.segments;
  41851. serializationObject.diameter = this.diameter;
  41852. return serializationObject;
  41853. };
  41854. SphereGeometry.Parse = function (parsedSphere, scene) {
  41855. if (scene.getGeometryByID(parsedSphere.id)) {
  41856. return null; // null since geometry could be something else than a sphere...
  41857. }
  41858. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41859. if (BABYLON.Tags) {
  41860. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41861. }
  41862. scene.pushGeometry(sphere, true);
  41863. return sphere;
  41864. };
  41865. return SphereGeometry;
  41866. }(_PrimitiveGeometry));
  41867. BABYLON.SphereGeometry = SphereGeometry;
  41868. /**
  41869. * Creates a disc geometry
  41870. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41871. */
  41872. var DiscGeometry = /** @class */ (function (_super) {
  41873. __extends(DiscGeometry, _super);
  41874. /**
  41875. * Creates a new disc geometry
  41876. * @param id defines the unique ID of the geometry
  41877. * @param scene defines the hosting scene
  41878. * @param radius defines the radius of the disc
  41879. * @param tessellation defines the tesselation factor to apply to the disc
  41880. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41881. * @param mesh defines the hosting mesh (can be null)
  41882. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41883. */
  41884. function DiscGeometry(id, scene,
  41885. /**
  41886. * Defines the radius of the disc
  41887. */
  41888. radius,
  41889. /**
  41890. * Defines the tesselation factor to apply to the disc
  41891. */
  41892. tessellation, canBeRegenerated, mesh,
  41893. /**
  41894. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41895. */
  41896. side) {
  41897. if (mesh === void 0) { mesh = null; }
  41898. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41899. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41900. _this.radius = radius;
  41901. _this.tessellation = tessellation;
  41902. _this.side = side;
  41903. return _this;
  41904. }
  41905. /** @hidden */
  41906. DiscGeometry.prototype._regenerateVertexData = function () {
  41907. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41908. };
  41909. DiscGeometry.prototype.copy = function (id) {
  41910. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41911. };
  41912. return DiscGeometry;
  41913. }(_PrimitiveGeometry));
  41914. BABYLON.DiscGeometry = DiscGeometry;
  41915. /**
  41916. * Creates a new cylinder geometry
  41917. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  41918. */
  41919. var CylinderGeometry = /** @class */ (function (_super) {
  41920. __extends(CylinderGeometry, _super);
  41921. /**
  41922. * Creates a new cylinder geometry
  41923. * @param id defines the unique ID of the geometry
  41924. * @param scene defines the hosting scene
  41925. * @param height defines the height of the cylinder
  41926. * @param diameterTop defines the diameter of the cylinder's top cap
  41927. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  41928. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  41929. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  41930. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41931. * @param mesh defines the hosting mesh (can be null)
  41932. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41933. */
  41934. function CylinderGeometry(id, scene,
  41935. /**
  41936. * Defines the height of the cylinder
  41937. */
  41938. height,
  41939. /**
  41940. * Defines the diameter of the cylinder's top cap
  41941. */
  41942. diameterTop,
  41943. /**
  41944. * Defines the diameter of the cylinder's bottom cap
  41945. */
  41946. diameterBottom,
  41947. /**
  41948. * Defines the tessellation factor to apply to the cylinder
  41949. */
  41950. tessellation,
  41951. /**
  41952. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  41953. */
  41954. subdivisions, canBeRegenerated, mesh,
  41955. /**
  41956. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41957. */
  41958. side) {
  41959. if (subdivisions === void 0) { subdivisions = 1; }
  41960. if (mesh === void 0) { mesh = null; }
  41961. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41962. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41963. _this.height = height;
  41964. _this.diameterTop = diameterTop;
  41965. _this.diameterBottom = diameterBottom;
  41966. _this.tessellation = tessellation;
  41967. _this.subdivisions = subdivisions;
  41968. _this.side = side;
  41969. return _this;
  41970. }
  41971. /** @hidden */
  41972. CylinderGeometry.prototype._regenerateVertexData = function () {
  41973. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41974. };
  41975. CylinderGeometry.prototype.copy = function (id) {
  41976. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41977. };
  41978. CylinderGeometry.prototype.serialize = function () {
  41979. var serializationObject = _super.prototype.serialize.call(this);
  41980. serializationObject.height = this.height;
  41981. serializationObject.diameterTop = this.diameterTop;
  41982. serializationObject.diameterBottom = this.diameterBottom;
  41983. serializationObject.tessellation = this.tessellation;
  41984. return serializationObject;
  41985. };
  41986. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  41987. if (scene.getGeometryByID(parsedCylinder.id)) {
  41988. return null; // null since geometry could be something else than a cylinder...
  41989. }
  41990. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41991. if (BABYLON.Tags) {
  41992. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41993. }
  41994. scene.pushGeometry(cylinder, true);
  41995. return cylinder;
  41996. };
  41997. return CylinderGeometry;
  41998. }(_PrimitiveGeometry));
  41999. BABYLON.CylinderGeometry = CylinderGeometry;
  42000. /**
  42001. * Creates a new torus geometry
  42002. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  42003. */
  42004. var TorusGeometry = /** @class */ (function (_super) {
  42005. __extends(TorusGeometry, _super);
  42006. /**
  42007. * Creates a new torus geometry
  42008. * @param id defines the unique ID of the geometry
  42009. * @param scene defines the hosting scene
  42010. * @param diameter defines the diameter of the torus
  42011. * @param thickness defines the thickness of the torus (ie. internal diameter)
  42012. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  42013. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42014. * @param mesh defines the hosting mesh (can be null)
  42015. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42016. */
  42017. function TorusGeometry(id, scene,
  42018. /**
  42019. * Defines the diameter of the torus
  42020. */
  42021. diameter,
  42022. /**
  42023. * Defines the thickness of the torus (ie. internal diameter)
  42024. */
  42025. thickness,
  42026. /**
  42027. * Defines the tesselation factor to apply to the torus
  42028. */
  42029. tessellation, canBeRegenerated, mesh,
  42030. /**
  42031. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42032. */
  42033. side) {
  42034. if (mesh === void 0) { mesh = null; }
  42035. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42036. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42037. _this.diameter = diameter;
  42038. _this.thickness = thickness;
  42039. _this.tessellation = tessellation;
  42040. _this.side = side;
  42041. return _this;
  42042. }
  42043. /** @hidden */
  42044. TorusGeometry.prototype._regenerateVertexData = function () {
  42045. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  42046. };
  42047. TorusGeometry.prototype.copy = function (id) {
  42048. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  42049. };
  42050. TorusGeometry.prototype.serialize = function () {
  42051. var serializationObject = _super.prototype.serialize.call(this);
  42052. serializationObject.diameter = this.diameter;
  42053. serializationObject.thickness = this.thickness;
  42054. serializationObject.tessellation = this.tessellation;
  42055. return serializationObject;
  42056. };
  42057. TorusGeometry.Parse = function (parsedTorus, scene) {
  42058. if (scene.getGeometryByID(parsedTorus.id)) {
  42059. return null; // null since geometry could be something else than a torus...
  42060. }
  42061. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  42062. if (BABYLON.Tags) {
  42063. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  42064. }
  42065. scene.pushGeometry(torus, true);
  42066. return torus;
  42067. };
  42068. return TorusGeometry;
  42069. }(_PrimitiveGeometry));
  42070. BABYLON.TorusGeometry = TorusGeometry;
  42071. /**
  42072. * Creates a new ground geometry
  42073. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  42074. */
  42075. var GroundGeometry = /** @class */ (function (_super) {
  42076. __extends(GroundGeometry, _super);
  42077. /**
  42078. * Creates a new ground geometry
  42079. * @param id defines the unique ID of the geometry
  42080. * @param scene defines the hosting scene
  42081. * @param width defines the width of the ground
  42082. * @param height defines the height of the ground
  42083. * @param subdivisions defines the subdivisions to apply to the ground
  42084. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42085. * @param mesh defines the hosting mesh (can be null)
  42086. */
  42087. function GroundGeometry(id, scene,
  42088. /**
  42089. * Defines the width of the ground
  42090. */
  42091. width,
  42092. /**
  42093. * Defines the height of the ground
  42094. */
  42095. height,
  42096. /**
  42097. * Defines the subdivisions to apply to the ground
  42098. */
  42099. subdivisions, canBeRegenerated, mesh) {
  42100. if (mesh === void 0) { mesh = null; }
  42101. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42102. _this.width = width;
  42103. _this.height = height;
  42104. _this.subdivisions = subdivisions;
  42105. return _this;
  42106. }
  42107. /** @hidden */
  42108. GroundGeometry.prototype._regenerateVertexData = function () {
  42109. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  42110. };
  42111. GroundGeometry.prototype.copy = function (id) {
  42112. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  42113. };
  42114. GroundGeometry.prototype.serialize = function () {
  42115. var serializationObject = _super.prototype.serialize.call(this);
  42116. serializationObject.width = this.width;
  42117. serializationObject.height = this.height;
  42118. serializationObject.subdivisions = this.subdivisions;
  42119. return serializationObject;
  42120. };
  42121. GroundGeometry.Parse = function (parsedGround, scene) {
  42122. if (scene.getGeometryByID(parsedGround.id)) {
  42123. return null; // null since geometry could be something else than a ground...
  42124. }
  42125. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  42126. if (BABYLON.Tags) {
  42127. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  42128. }
  42129. scene.pushGeometry(ground, true);
  42130. return ground;
  42131. };
  42132. return GroundGeometry;
  42133. }(_PrimitiveGeometry));
  42134. BABYLON.GroundGeometry = GroundGeometry;
  42135. /**
  42136. * Creates a tiled ground geometry
  42137. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  42138. */
  42139. var TiledGroundGeometry = /** @class */ (function (_super) {
  42140. __extends(TiledGroundGeometry, _super);
  42141. /**
  42142. * Creates a tiled ground geometry
  42143. * @param id defines the unique ID of the geometry
  42144. * @param scene defines the hosting scene
  42145. * @param xmin defines the minimum value on X axis
  42146. * @param zmin defines the minimum value on Z axis
  42147. * @param xmax defines the maximum value on X axis
  42148. * @param zmax defines the maximum value on Z axis
  42149. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  42150. * @param precision defines the precision to use when computing the tiles
  42151. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42152. * @param mesh defines the hosting mesh (can be null)
  42153. */
  42154. function TiledGroundGeometry(id, scene,
  42155. /**
  42156. * Defines the minimum value on X axis
  42157. */
  42158. xmin,
  42159. /**
  42160. * Defines the minimum value on Z axis
  42161. */
  42162. zmin,
  42163. /**
  42164. * Defines the maximum value on X axis
  42165. */
  42166. xmax,
  42167. /**
  42168. * Defines the maximum value on Z axis
  42169. */
  42170. zmax,
  42171. /**
  42172. * Defines the subdivisions to apply to the ground
  42173. */
  42174. subdivisions,
  42175. /**
  42176. * Defines the precision to use when computing the tiles
  42177. */
  42178. precision, canBeRegenerated, mesh) {
  42179. if (mesh === void 0) { mesh = null; }
  42180. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42181. _this.xmin = xmin;
  42182. _this.zmin = zmin;
  42183. _this.xmax = xmax;
  42184. _this.zmax = zmax;
  42185. _this.subdivisions = subdivisions;
  42186. _this.precision = precision;
  42187. return _this;
  42188. }
  42189. /** @hidden */
  42190. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  42191. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  42192. };
  42193. TiledGroundGeometry.prototype.copy = function (id) {
  42194. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  42195. };
  42196. return TiledGroundGeometry;
  42197. }(_PrimitiveGeometry));
  42198. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  42199. /**
  42200. * Creates a plane geometry
  42201. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  42202. */
  42203. var PlaneGeometry = /** @class */ (function (_super) {
  42204. __extends(PlaneGeometry, _super);
  42205. /**
  42206. * Creates a plane geometry
  42207. * @param id defines the unique ID of the geometry
  42208. * @param scene defines the hosting scene
  42209. * @param size defines the size of the plane (width === height)
  42210. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42211. * @param mesh defines the hosting mesh (can be null)
  42212. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42213. */
  42214. function PlaneGeometry(id, scene,
  42215. /**
  42216. * Defines the size of the plane (width === height)
  42217. */
  42218. size, canBeRegenerated, mesh,
  42219. /**
  42220. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42221. */
  42222. side) {
  42223. if (mesh === void 0) { mesh = null; }
  42224. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42225. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42226. _this.size = size;
  42227. _this.side = side;
  42228. return _this;
  42229. }
  42230. /** @hidden */
  42231. PlaneGeometry.prototype._regenerateVertexData = function () {
  42232. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  42233. };
  42234. PlaneGeometry.prototype.copy = function (id) {
  42235. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  42236. };
  42237. PlaneGeometry.prototype.serialize = function () {
  42238. var serializationObject = _super.prototype.serialize.call(this);
  42239. serializationObject.size = this.size;
  42240. return serializationObject;
  42241. };
  42242. PlaneGeometry.Parse = function (parsedPlane, scene) {
  42243. if (scene.getGeometryByID(parsedPlane.id)) {
  42244. return null; // null since geometry could be something else than a ground...
  42245. }
  42246. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  42247. if (BABYLON.Tags) {
  42248. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  42249. }
  42250. scene.pushGeometry(plane, true);
  42251. return plane;
  42252. };
  42253. return PlaneGeometry;
  42254. }(_PrimitiveGeometry));
  42255. BABYLON.PlaneGeometry = PlaneGeometry;
  42256. /**
  42257. * Creates a torus knot geometry
  42258. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  42259. */
  42260. var TorusKnotGeometry = /** @class */ (function (_super) {
  42261. __extends(TorusKnotGeometry, _super);
  42262. /**
  42263. * Creates a torus knot geometry
  42264. * @param id defines the unique ID of the geometry
  42265. * @param scene defines the hosting scene
  42266. * @param radius defines the radius of the torus knot
  42267. * @param tube defines the thickness of the torus knot tube
  42268. * @param radialSegments defines the number of radial segments
  42269. * @param tubularSegments defines the number of tubular segments
  42270. * @param p defines the first number of windings
  42271. * @param q defines the second number of windings
  42272. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42273. * @param mesh defines the hosting mesh (can be null)
  42274. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42275. */
  42276. function TorusKnotGeometry(id, scene,
  42277. /**
  42278. * Defines the radius of the torus knot
  42279. */
  42280. radius,
  42281. /**
  42282. * Defines the thickness of the torus knot tube
  42283. */
  42284. tube,
  42285. /**
  42286. * Defines the number of radial segments
  42287. */
  42288. radialSegments,
  42289. /**
  42290. * Defines the number of tubular segments
  42291. */
  42292. tubularSegments,
  42293. /**
  42294. * Defines the first number of windings
  42295. */
  42296. p,
  42297. /**
  42298. * Defines the second number of windings
  42299. */
  42300. q, canBeRegenerated, mesh,
  42301. /**
  42302. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42303. */
  42304. side) {
  42305. if (mesh === void 0) { mesh = null; }
  42306. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42307. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42308. _this.radius = radius;
  42309. _this.tube = tube;
  42310. _this.radialSegments = radialSegments;
  42311. _this.tubularSegments = tubularSegments;
  42312. _this.p = p;
  42313. _this.q = q;
  42314. _this.side = side;
  42315. return _this;
  42316. }
  42317. /** @hidden */
  42318. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  42319. 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 });
  42320. };
  42321. TorusKnotGeometry.prototype.copy = function (id) {
  42322. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  42323. };
  42324. TorusKnotGeometry.prototype.serialize = function () {
  42325. var serializationObject = _super.prototype.serialize.call(this);
  42326. serializationObject.radius = this.radius;
  42327. serializationObject.tube = this.tube;
  42328. serializationObject.radialSegments = this.radialSegments;
  42329. serializationObject.tubularSegments = this.tubularSegments;
  42330. serializationObject.p = this.p;
  42331. serializationObject.q = this.q;
  42332. return serializationObject;
  42333. };
  42334. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  42335. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  42336. return null; // null since geometry could be something else than a ground...
  42337. }
  42338. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  42339. if (BABYLON.Tags) {
  42340. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  42341. }
  42342. scene.pushGeometry(torusKnot, true);
  42343. return torusKnot;
  42344. };
  42345. return TorusKnotGeometry;
  42346. }(_PrimitiveGeometry));
  42347. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  42348. //}
  42349. })(BABYLON || (BABYLON = {}));
  42350. //# sourceMappingURL=babylon.geometry.js.map
  42351. var BABYLON;
  42352. (function (BABYLON) {
  42353. /**
  42354. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  42355. */
  42356. var PerformanceMonitor = /** @class */ (function () {
  42357. /**
  42358. * constructor
  42359. * @param frameSampleSize The number of samples required to saturate the sliding window
  42360. */
  42361. function PerformanceMonitor(frameSampleSize) {
  42362. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  42363. this._enabled = true;
  42364. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  42365. }
  42366. /**
  42367. * Samples current frame
  42368. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  42369. */
  42370. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  42371. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  42372. if (!this._enabled) {
  42373. return;
  42374. }
  42375. if (this._lastFrameTimeMs != null) {
  42376. var dt = timeMs - this._lastFrameTimeMs;
  42377. this._rollingFrameTime.add(dt);
  42378. }
  42379. this._lastFrameTimeMs = timeMs;
  42380. };
  42381. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  42382. /**
  42383. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42384. */
  42385. get: function () {
  42386. return this._rollingFrameTime.average;
  42387. },
  42388. enumerable: true,
  42389. configurable: true
  42390. });
  42391. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  42392. /**
  42393. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42394. */
  42395. get: function () {
  42396. return this._rollingFrameTime.variance;
  42397. },
  42398. enumerable: true,
  42399. configurable: true
  42400. });
  42401. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  42402. /**
  42403. * Returns the frame time of the most recent frame
  42404. */
  42405. get: function () {
  42406. return this._rollingFrameTime.history(0);
  42407. },
  42408. enumerable: true,
  42409. configurable: true
  42410. });
  42411. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  42412. /**
  42413. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  42414. */
  42415. get: function () {
  42416. return 1000.0 / this._rollingFrameTime.average;
  42417. },
  42418. enumerable: true,
  42419. configurable: true
  42420. });
  42421. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  42422. /**
  42423. * Returns the average framerate in frames per second using the most recent frame time
  42424. */
  42425. get: function () {
  42426. var history = this._rollingFrameTime.history(0);
  42427. if (history === 0) {
  42428. return 0;
  42429. }
  42430. return 1000.0 / history;
  42431. },
  42432. enumerable: true,
  42433. configurable: true
  42434. });
  42435. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  42436. /**
  42437. * Returns true if enough samples have been taken to completely fill the sliding window
  42438. */
  42439. get: function () {
  42440. return this._rollingFrameTime.isSaturated();
  42441. },
  42442. enumerable: true,
  42443. configurable: true
  42444. });
  42445. /**
  42446. * Enables contributions to the sliding window sample set
  42447. */
  42448. PerformanceMonitor.prototype.enable = function () {
  42449. this._enabled = true;
  42450. };
  42451. /**
  42452. * Disables contributions to the sliding window sample set
  42453. * Samples will not be interpolated over the disabled period
  42454. */
  42455. PerformanceMonitor.prototype.disable = function () {
  42456. this._enabled = false;
  42457. //clear last sample to avoid interpolating over the disabled period when next enabled
  42458. this._lastFrameTimeMs = null;
  42459. };
  42460. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  42461. /**
  42462. * Returns true if sampling is enabled
  42463. */
  42464. get: function () {
  42465. return this._enabled;
  42466. },
  42467. enumerable: true,
  42468. configurable: true
  42469. });
  42470. /**
  42471. * Resets performance monitor
  42472. */
  42473. PerformanceMonitor.prototype.reset = function () {
  42474. //clear last sample to avoid interpolating over the disabled period when next enabled
  42475. this._lastFrameTimeMs = null;
  42476. //wipe record
  42477. this._rollingFrameTime.reset();
  42478. };
  42479. return PerformanceMonitor;
  42480. }());
  42481. BABYLON.PerformanceMonitor = PerformanceMonitor;
  42482. /**
  42483. * RollingAverage
  42484. *
  42485. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  42486. */
  42487. var RollingAverage = /** @class */ (function () {
  42488. /**
  42489. * constructor
  42490. * @param length The number of samples required to saturate the sliding window
  42491. */
  42492. function RollingAverage(length) {
  42493. this._samples = new Array(length);
  42494. this.reset();
  42495. }
  42496. /**
  42497. * Adds a sample to the sample set
  42498. * @param v The sample value
  42499. */
  42500. RollingAverage.prototype.add = function (v) {
  42501. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  42502. var delta;
  42503. //we need to check if we've already wrapped round
  42504. if (this.isSaturated()) {
  42505. //remove bottom of stack from mean
  42506. var bottomValue = this._samples[this._pos];
  42507. delta = bottomValue - this.average;
  42508. this.average -= delta / (this._sampleCount - 1);
  42509. this._m2 -= delta * (bottomValue - this.average);
  42510. }
  42511. else {
  42512. this._sampleCount++;
  42513. }
  42514. //add new value to mean
  42515. delta = v - this.average;
  42516. this.average += delta / (this._sampleCount);
  42517. this._m2 += delta * (v - this.average);
  42518. //set the new variance
  42519. this.variance = this._m2 / (this._sampleCount - 1);
  42520. this._samples[this._pos] = v;
  42521. this._pos++;
  42522. this._pos %= this._samples.length; //positive wrap around
  42523. };
  42524. /**
  42525. * Returns previously added values or null if outside of history or outside the sliding window domain
  42526. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  42527. * @return Value previously recorded with add() or null if outside of range
  42528. */
  42529. RollingAverage.prototype.history = function (i) {
  42530. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  42531. return 0;
  42532. }
  42533. var i0 = this._wrapPosition(this._pos - 1.0);
  42534. return this._samples[this._wrapPosition(i0 - i)];
  42535. };
  42536. /**
  42537. * Returns true if enough samples have been taken to completely fill the sliding window
  42538. * @return true if sample-set saturated
  42539. */
  42540. RollingAverage.prototype.isSaturated = function () {
  42541. return this._sampleCount >= this._samples.length;
  42542. };
  42543. /**
  42544. * Resets the rolling average (equivalent to 0 samples taken so far)
  42545. */
  42546. RollingAverage.prototype.reset = function () {
  42547. this.average = 0;
  42548. this.variance = 0;
  42549. this._sampleCount = 0;
  42550. this._pos = 0;
  42551. this._m2 = 0;
  42552. };
  42553. /**
  42554. * Wraps a value around the sample range boundaries
  42555. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  42556. * @return Wrapped position in sample range
  42557. */
  42558. RollingAverage.prototype._wrapPosition = function (i) {
  42559. var max = this._samples.length;
  42560. return ((i % max) + max) % max;
  42561. };
  42562. return RollingAverage;
  42563. }());
  42564. BABYLON.RollingAverage = RollingAverage;
  42565. })(BABYLON || (BABYLON = {}));
  42566. //# sourceMappingURL=babylon.performanceMonitor.js.map
  42567. var BABYLON;
  42568. (function (BABYLON) {
  42569. /**
  42570. * "Static Class" containing the most commonly used helper while dealing with material for
  42571. * rendering purpose.
  42572. *
  42573. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42574. *
  42575. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42576. */
  42577. var MaterialHelper = /** @class */ (function () {
  42578. function MaterialHelper() {
  42579. }
  42580. /**
  42581. * Bind the current view position to an effect.
  42582. * @param effect The effect to be bound
  42583. * @param scene The scene the eyes position is used from
  42584. */
  42585. MaterialHelper.BindEyePosition = function (effect, scene) {
  42586. if (scene._forcedViewPosition) {
  42587. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42588. return;
  42589. }
  42590. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42591. };
  42592. /**
  42593. * Helps preparing the defines values about the UVs in used in the effect.
  42594. * UVs are shared as much as we can accross channels in the shaders.
  42595. * @param texture The texture we are preparing the UVs for
  42596. * @param defines The defines to update
  42597. * @param key The channel key "diffuse", "specular"... used in the shader
  42598. */
  42599. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42600. defines._needUVs = true;
  42601. defines[key] = true;
  42602. if (texture.getTextureMatrix().isIdentityAs3x2()) {
  42603. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42604. if (texture.coordinatesIndex === 0) {
  42605. defines["MAINUV1"] = true;
  42606. }
  42607. else {
  42608. defines["MAINUV2"] = true;
  42609. }
  42610. }
  42611. else {
  42612. defines[key + "DIRECTUV"] = 0;
  42613. }
  42614. };
  42615. /**
  42616. * Binds a texture matrix value to its corrsponding uniform
  42617. * @param texture The texture to bind the matrix for
  42618. * @param uniformBuffer The uniform buffer receivin the data
  42619. * @param key The channel key "diffuse", "specular"... used in the shader
  42620. */
  42621. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42622. var matrix = texture.getTextureMatrix();
  42623. if (!matrix.isIdentityAs3x2()) {
  42624. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42625. }
  42626. };
  42627. /**
  42628. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42629. * @param mesh defines the current mesh
  42630. * @param scene defines the current scene
  42631. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42632. * @param pointsCloud defines if point cloud rendering has to be turned on
  42633. * @param fogEnabled defines if fog has to be turned on
  42634. * @param alphaTest defines if alpha testing has to be turned on
  42635. * @param defines defines the current list of defines
  42636. */
  42637. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42638. if (defines._areMiscDirty) {
  42639. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42640. defines["POINTSIZE"] = pointsCloud;
  42641. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42642. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42643. defines["ALPHATEST"] = alphaTest;
  42644. }
  42645. };
  42646. /**
  42647. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42648. * @param scene defines the current scene
  42649. * @param engine defines the current engine
  42650. * @param defines specifies the list of active defines
  42651. * @param useInstances defines if instances have to be turned on
  42652. * @param useClipPlane defines if clip plane have to be turned on
  42653. */
  42654. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42655. if (useClipPlane === void 0) { useClipPlane = null; }
  42656. var changed = false;
  42657. var useClipPlane1 = false;
  42658. var useClipPlane2 = false;
  42659. var useClipPlane3 = false;
  42660. var useClipPlane4 = false;
  42661. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  42662. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  42663. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  42664. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  42665. if (defines["CLIPPLANE"] !== useClipPlane1) {
  42666. defines["CLIPPLANE"] = useClipPlane1;
  42667. changed = true;
  42668. }
  42669. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  42670. defines["CLIPPLANE2"] = useClipPlane2;
  42671. changed = true;
  42672. }
  42673. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  42674. defines["CLIPPLANE3"] = useClipPlane3;
  42675. changed = true;
  42676. }
  42677. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  42678. defines["CLIPPLANE4"] = useClipPlane4;
  42679. changed = true;
  42680. }
  42681. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42682. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42683. changed = true;
  42684. }
  42685. if (defines["INSTANCES"] !== useInstances) {
  42686. defines["INSTANCES"] = useInstances;
  42687. changed = true;
  42688. }
  42689. if (changed) {
  42690. defines.markAsUnprocessed();
  42691. }
  42692. };
  42693. /**
  42694. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42695. * @param mesh The mesh containing the geometry data we will draw
  42696. * @param defines The defines to update
  42697. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42698. * @param useBones Precise whether bones should be used or not (override mesh info)
  42699. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42700. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42701. * @returns false if defines are considered not dirty and have not been checked
  42702. */
  42703. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42704. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42705. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42706. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42707. return false;
  42708. }
  42709. defines._normals = defines._needNormals;
  42710. defines._uvs = defines._needUVs;
  42711. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42712. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42713. defines["TANGENT"] = true;
  42714. }
  42715. if (defines._needUVs) {
  42716. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42717. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42718. }
  42719. else {
  42720. defines["UV1"] = false;
  42721. defines["UV2"] = false;
  42722. }
  42723. if (useVertexColor) {
  42724. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42725. defines["VERTEXCOLOR"] = hasVertexColors;
  42726. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42727. }
  42728. if (useBones) {
  42729. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42730. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42731. var materialSupportsBoneTexture = defines["BONETEXTURE"] !== undefined;
  42732. if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) {
  42733. defines["BONETEXTURE"] = true;
  42734. }
  42735. else {
  42736. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42737. defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : undefined;
  42738. }
  42739. }
  42740. else {
  42741. defines["NUM_BONE_INFLUENCERS"] = 0;
  42742. defines["BonesPerMesh"] = 0;
  42743. }
  42744. }
  42745. if (useMorphTargets) {
  42746. var manager = mesh.morphTargetManager;
  42747. if (manager) {
  42748. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42749. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42750. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42751. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42752. }
  42753. else {
  42754. defines["MORPHTARGETS_TANGENT"] = false;
  42755. defines["MORPHTARGETS_NORMAL"] = false;
  42756. defines["MORPHTARGETS"] = false;
  42757. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42758. }
  42759. }
  42760. return true;
  42761. };
  42762. /**
  42763. * Prepares the defines related to the light information passed in parameter
  42764. * @param scene The scene we are intending to draw
  42765. * @param mesh The mesh the effect is compiling for
  42766. * @param defines The defines to update
  42767. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42768. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42769. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42770. * @returns true if normals will be required for the rest of the effect
  42771. */
  42772. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42773. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42774. if (disableLighting === void 0) { disableLighting = false; }
  42775. if (!defines._areLightsDirty) {
  42776. return defines._needNormals;
  42777. }
  42778. var lightIndex = 0;
  42779. var needNormals = false;
  42780. var needRebuild = false;
  42781. var lightmapMode = false;
  42782. var shadowEnabled = false;
  42783. var specularEnabled = false;
  42784. if (scene.lightsEnabled && !disableLighting) {
  42785. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42786. var light = _a[_i];
  42787. needNormals = true;
  42788. if (defines["LIGHT" + lightIndex] === undefined) {
  42789. needRebuild = true;
  42790. }
  42791. defines["LIGHT" + lightIndex] = true;
  42792. defines["SPOTLIGHT" + lightIndex] = false;
  42793. defines["HEMILIGHT" + lightIndex] = false;
  42794. defines["POINTLIGHT" + lightIndex] = false;
  42795. defines["DIRLIGHT" + lightIndex] = false;
  42796. light.prepareLightSpecificDefines(defines, lightIndex);
  42797. // FallOff.
  42798. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  42799. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  42800. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  42801. switch (light.falloffType) {
  42802. case BABYLON.Light.FALLOFF_GLTF:
  42803. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  42804. break;
  42805. case BABYLON.Light.FALLOFF_PHYSICAL:
  42806. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  42807. break;
  42808. case BABYLON.Light.FALLOFF_STANDARD:
  42809. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  42810. break;
  42811. }
  42812. // Specular
  42813. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42814. specularEnabled = true;
  42815. }
  42816. // Shadows
  42817. defines["SHADOW" + lightIndex] = false;
  42818. defines["SHADOWPCF" + lightIndex] = false;
  42819. defines["SHADOWPCSS" + lightIndex] = false;
  42820. defines["SHADOWPOISSON" + lightIndex] = false;
  42821. defines["SHADOWESM" + lightIndex] = false;
  42822. defines["SHADOWCUBE" + lightIndex] = false;
  42823. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42824. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42825. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42826. var shadowGenerator = light.getShadowGenerator();
  42827. if (shadowGenerator) {
  42828. var shadowMap = shadowGenerator.getShadowMap();
  42829. if (shadowMap) {
  42830. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42831. shadowEnabled = true;
  42832. shadowGenerator.prepareDefines(defines, lightIndex);
  42833. }
  42834. }
  42835. }
  42836. }
  42837. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42838. lightmapMode = true;
  42839. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42840. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42841. }
  42842. else {
  42843. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42844. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42845. }
  42846. lightIndex++;
  42847. if (lightIndex === maxSimultaneousLights) {
  42848. break;
  42849. }
  42850. }
  42851. }
  42852. defines["SPECULARTERM"] = specularEnabled;
  42853. defines["SHADOWS"] = shadowEnabled;
  42854. // Resetting all other lights if any
  42855. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42856. if (defines["LIGHT" + index] !== undefined) {
  42857. defines["LIGHT" + index] = false;
  42858. defines["HEMILIGHT" + lightIndex] = false;
  42859. defines["POINTLIGHT" + lightIndex] = false;
  42860. defines["DIRLIGHT" + lightIndex] = false;
  42861. defines["SPOTLIGHT" + lightIndex] = false;
  42862. defines["SHADOW" + lightIndex] = false;
  42863. }
  42864. }
  42865. var caps = scene.getEngine().getCaps();
  42866. if (defines["SHADOWFLOAT"] === undefined) {
  42867. needRebuild = true;
  42868. }
  42869. defines["SHADOWFLOAT"] = shadowEnabled &&
  42870. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42871. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42872. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42873. if (needRebuild) {
  42874. defines.rebuild();
  42875. }
  42876. return needNormals;
  42877. };
  42878. /**
  42879. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42880. * that won t be acctive due to defines being turned off.
  42881. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42882. * @param samplersList The samplers list
  42883. * @param defines The defines helping in the list generation
  42884. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42885. */
  42886. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42887. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42888. var uniformsList;
  42889. var uniformBuffersList = null;
  42890. if (uniformsListOrOptions.uniformsNames) {
  42891. var options = uniformsListOrOptions;
  42892. uniformsList = options.uniformsNames;
  42893. uniformBuffersList = options.uniformBuffersNames;
  42894. samplersList = options.samplers;
  42895. defines = options.defines;
  42896. maxSimultaneousLights = options.maxSimultaneousLights;
  42897. }
  42898. else {
  42899. uniformsList = uniformsListOrOptions;
  42900. if (!samplersList) {
  42901. samplersList = [];
  42902. }
  42903. }
  42904. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42905. if (!defines["LIGHT" + lightIndex]) {
  42906. break;
  42907. }
  42908. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42909. if (uniformBuffersList) {
  42910. uniformBuffersList.push("Light" + lightIndex);
  42911. }
  42912. samplersList.push("shadowSampler" + lightIndex);
  42913. samplersList.push("depthSampler" + lightIndex);
  42914. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42915. samplersList.push("projectionLightSampler" + lightIndex);
  42916. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42917. }
  42918. }
  42919. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42920. uniformsList.push("morphTargetInfluences");
  42921. }
  42922. };
  42923. /**
  42924. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42925. * @param defines The defines to update while falling back
  42926. * @param fallbacks The authorized effect fallbacks
  42927. * @param maxSimultaneousLights The maximum number of lights allowed
  42928. * @param rank the current rank of the Effect
  42929. * @returns The newly affected rank
  42930. */
  42931. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42932. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42933. if (rank === void 0) { rank = 0; }
  42934. var lightFallbackRank = 0;
  42935. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42936. if (!defines["LIGHT" + lightIndex]) {
  42937. break;
  42938. }
  42939. if (lightIndex > 0) {
  42940. lightFallbackRank = rank + lightIndex;
  42941. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42942. }
  42943. if (!defines["SHADOWS"]) {
  42944. if (defines["SHADOW" + lightIndex]) {
  42945. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42946. }
  42947. if (defines["SHADOWPCF" + lightIndex]) {
  42948. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42949. }
  42950. if (defines["SHADOWPCSS" + lightIndex]) {
  42951. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42952. }
  42953. if (defines["SHADOWPOISSON" + lightIndex]) {
  42954. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42955. }
  42956. if (defines["SHADOWESM" + lightIndex]) {
  42957. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42958. }
  42959. }
  42960. }
  42961. return lightFallbackRank++;
  42962. };
  42963. /**
  42964. * Prepares the list of attributes required for morph targets according to the effect defines.
  42965. * @param attribs The current list of supported attribs
  42966. * @param mesh The mesh to prepare the morph targets attributes for
  42967. * @param defines The current Defines of the effect
  42968. */
  42969. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42970. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42971. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42972. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42973. var manager = mesh.morphTargetManager;
  42974. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42975. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42976. for (var index = 0; index < influencers; index++) {
  42977. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42978. if (normal) {
  42979. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42980. }
  42981. if (tangent) {
  42982. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42983. }
  42984. if (attribs.length > maxAttributesCount) {
  42985. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42986. }
  42987. }
  42988. }
  42989. };
  42990. /**
  42991. * Prepares the list of attributes required for bones according to the effect defines.
  42992. * @param attribs The current list of supported attribs
  42993. * @param mesh The mesh to prepare the bones attributes for
  42994. * @param defines The current Defines of the effect
  42995. * @param fallbacks The current efffect fallback strategy
  42996. */
  42997. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42998. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42999. fallbacks.addCPUSkinningFallback(0, mesh);
  43000. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43001. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43002. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  43003. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43004. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43005. }
  43006. }
  43007. };
  43008. /**
  43009. * Prepares the list of attributes required for instances according to the effect defines.
  43010. * @param attribs The current list of supported attribs
  43011. * @param defines The current Defines of the effect
  43012. */
  43013. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  43014. if (defines["INSTANCES"]) {
  43015. attribs.push("world0");
  43016. attribs.push("world1");
  43017. attribs.push("world2");
  43018. attribs.push("world3");
  43019. }
  43020. };
  43021. /**
  43022. * Binds the light shadow information to the effect for the given mesh.
  43023. * @param light The light containing the generator
  43024. * @param scene The scene the lights belongs to
  43025. * @param mesh The mesh we are binding the information to render
  43026. * @param lightIndex The light index in the effect used to render the mesh
  43027. * @param effect The effect we are binding the data to
  43028. */
  43029. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  43030. if (light.shadowEnabled && mesh.receiveShadows) {
  43031. var shadowGenerator = light.getShadowGenerator();
  43032. if (shadowGenerator) {
  43033. shadowGenerator.bindShadowLight(lightIndex, effect);
  43034. }
  43035. }
  43036. };
  43037. /**
  43038. * Binds the light information to the effect.
  43039. * @param light The light containing the generator
  43040. * @param effect The effect we are binding the data to
  43041. * @param lightIndex The light index in the effect used to render
  43042. */
  43043. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  43044. light.transferToEffect(effect, lightIndex + "");
  43045. };
  43046. /**
  43047. * Binds the lights information from the scene to the effect for the given mesh.
  43048. * @param scene The scene the lights belongs to
  43049. * @param mesh The mesh we are binding the information to render
  43050. * @param effect The effect we are binding the data to
  43051. * @param defines The generated defines for the effect
  43052. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  43053. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  43054. */
  43055. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  43056. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43057. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  43058. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  43059. for (var i = 0; i < len; i++) {
  43060. var light = mesh._lightSources[i];
  43061. var iAsString = i.toString();
  43062. var scaledIntensity = light.getScaledIntensity();
  43063. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  43064. MaterialHelper.BindLightProperties(light, effect, i);
  43065. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  43066. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  43067. if (defines["SPECULARTERM"]) {
  43068. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  43069. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  43070. }
  43071. // Shadows
  43072. if (scene.shadowsEnabled) {
  43073. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  43074. }
  43075. light._uniformBuffer.update();
  43076. }
  43077. };
  43078. /**
  43079. * Binds the fog information from the scene to the effect for the given mesh.
  43080. * @param scene The scene the lights belongs to
  43081. * @param mesh The mesh we are binding the information to render
  43082. * @param effect The effect we are binding the data to
  43083. * @param linearSpace Defines if the fog effect is applied in linear space
  43084. */
  43085. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  43086. if (linearSpace === void 0) { linearSpace = false; }
  43087. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  43088. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  43089. // Convert fog color to linear space if used in a linear space computed shader.
  43090. if (linearSpace) {
  43091. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  43092. effect.setColor3("vFogColor", this._tempFogColor);
  43093. }
  43094. else {
  43095. effect.setColor3("vFogColor", scene.fogColor);
  43096. }
  43097. }
  43098. };
  43099. /**
  43100. * Binds the bones information from the mesh to the effect.
  43101. * @param mesh The mesh we are binding the information to render
  43102. * @param effect The effect we are binding the data to
  43103. */
  43104. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  43105. if (!effect || !mesh) {
  43106. return;
  43107. }
  43108. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  43109. mesh.computeBonesUsingShaders = false;
  43110. }
  43111. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43112. var skeleton = mesh.skeleton;
  43113. if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) {
  43114. var boneTexture = skeleton.getTransformMatrixTexture();
  43115. effect.setTexture("boneSampler", boneTexture);
  43116. effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  43117. }
  43118. else {
  43119. var matrices = skeleton.getTransformMatrices(mesh);
  43120. if (matrices) {
  43121. effect.setMatrices("mBones", matrices);
  43122. }
  43123. }
  43124. }
  43125. };
  43126. /**
  43127. * Binds the morph targets information from the mesh to the effect.
  43128. * @param abstractMesh The mesh we are binding the information to render
  43129. * @param effect The effect we are binding the data to
  43130. */
  43131. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  43132. var manager = abstractMesh.morphTargetManager;
  43133. if (!abstractMesh || !manager) {
  43134. return;
  43135. }
  43136. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43137. };
  43138. /**
  43139. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43140. * @param defines The generated defines used in the effect
  43141. * @param effect The effect we are binding the data to
  43142. * @param scene The scene we are willing to render with logarithmic scale for
  43143. */
  43144. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43145. if (defines["LOGARITHMICDEPTH"]) {
  43146. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43147. }
  43148. };
  43149. /**
  43150. * Binds the clip plane information from the scene to the effect.
  43151. * @param scene The scene the clip plane information are extracted from
  43152. * @param effect The effect we are binding the data to
  43153. */
  43154. MaterialHelper.BindClipPlane = function (effect, scene) {
  43155. if (scene.clipPlane) {
  43156. var clipPlane = scene.clipPlane;
  43157. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43158. }
  43159. if (scene.clipPlane2) {
  43160. var clipPlane = scene.clipPlane2;
  43161. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43162. }
  43163. if (scene.clipPlane3) {
  43164. var clipPlane = scene.clipPlane3;
  43165. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43166. }
  43167. if (scene.clipPlane4) {
  43168. var clipPlane = scene.clipPlane4;
  43169. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43170. }
  43171. };
  43172. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  43173. return MaterialHelper;
  43174. }());
  43175. BABYLON.MaterialHelper = MaterialHelper;
  43176. })(BABYLON || (BABYLON = {}));
  43177. //# sourceMappingURL=babylon.materialHelper.js.map
  43178. var BABYLON;
  43179. (function (BABYLON) {
  43180. /**
  43181. * Base class of materials working in push mode in babylon JS
  43182. * @hidden
  43183. */
  43184. var PushMaterial = /** @class */ (function (_super) {
  43185. __extends(PushMaterial, _super);
  43186. function PushMaterial(name, scene) {
  43187. var _this = _super.call(this, name, scene) || this;
  43188. _this._normalMatrix = new BABYLON.Matrix();
  43189. /**
  43190. * Gets or sets a boolean indicating that the material is allowed to do shader hot swapping.
  43191. * This means that the material can keep using a previous shader while a new one is being compiled.
  43192. * This is mostly used when shader parallel compilation is supported (true by default)
  43193. */
  43194. _this.allowShaderHotSwapping = true;
  43195. _this._storeEffectOnSubMeshes = true;
  43196. return _this;
  43197. }
  43198. PushMaterial.prototype.getEffect = function () {
  43199. return this._activeEffect;
  43200. };
  43201. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43202. if (!mesh) {
  43203. return false;
  43204. }
  43205. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43206. return true;
  43207. }
  43208. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43209. };
  43210. /**
  43211. * Binds the given world matrix to the active effect
  43212. *
  43213. * @param world the matrix to bind
  43214. */
  43215. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43216. this._activeEffect.setMatrix("world", world);
  43217. };
  43218. /**
  43219. * Binds the given normal matrix to the active effect
  43220. *
  43221. * @param normalMatrix the matrix to bind
  43222. */
  43223. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43224. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43225. };
  43226. PushMaterial.prototype.bind = function (world, mesh) {
  43227. if (!mesh) {
  43228. return;
  43229. }
  43230. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43231. };
  43232. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43233. if (effect === void 0) { effect = null; }
  43234. _super.prototype._afterBind.call(this, mesh);
  43235. this.getScene()._cachedEffect = effect;
  43236. };
  43237. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43238. if (visibility === void 0) { visibility = 1; }
  43239. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43240. };
  43241. return PushMaterial;
  43242. }(BABYLON.Material));
  43243. BABYLON.PushMaterial = PushMaterial;
  43244. })(BABYLON || (BABYLON = {}));
  43245. //# sourceMappingURL=babylon.pushMaterial.js.map
  43246. var BABYLON;
  43247. (function (BABYLON) {
  43248. /** @hidden */
  43249. var StandardMaterialDefines = /** @class */ (function (_super) {
  43250. __extends(StandardMaterialDefines, _super);
  43251. function StandardMaterialDefines() {
  43252. var _this = _super.call(this) || this;
  43253. _this.MAINUV1 = false;
  43254. _this.MAINUV2 = false;
  43255. _this.DIFFUSE = false;
  43256. _this.DIFFUSEDIRECTUV = 0;
  43257. _this.AMBIENT = false;
  43258. _this.AMBIENTDIRECTUV = 0;
  43259. _this.OPACITY = false;
  43260. _this.OPACITYDIRECTUV = 0;
  43261. _this.OPACITYRGB = false;
  43262. _this.REFLECTION = false;
  43263. _this.EMISSIVE = false;
  43264. _this.EMISSIVEDIRECTUV = 0;
  43265. _this.SPECULAR = false;
  43266. _this.SPECULARDIRECTUV = 0;
  43267. _this.BUMP = false;
  43268. _this.BUMPDIRECTUV = 0;
  43269. _this.PARALLAX = false;
  43270. _this.PARALLAXOCCLUSION = false;
  43271. _this.SPECULAROVERALPHA = false;
  43272. _this.CLIPPLANE = false;
  43273. _this.CLIPPLANE2 = false;
  43274. _this.CLIPPLANE3 = false;
  43275. _this.CLIPPLANE4 = false;
  43276. _this.ALPHATEST = false;
  43277. _this.DEPTHPREPASS = false;
  43278. _this.ALPHAFROMDIFFUSE = false;
  43279. _this.POINTSIZE = false;
  43280. _this.FOG = false;
  43281. _this.SPECULARTERM = false;
  43282. _this.DIFFUSEFRESNEL = false;
  43283. _this.OPACITYFRESNEL = false;
  43284. _this.REFLECTIONFRESNEL = false;
  43285. _this.REFRACTIONFRESNEL = false;
  43286. _this.EMISSIVEFRESNEL = false;
  43287. _this.FRESNEL = false;
  43288. _this.NORMAL = false;
  43289. _this.UV1 = false;
  43290. _this.UV2 = false;
  43291. _this.VERTEXCOLOR = false;
  43292. _this.VERTEXALPHA = false;
  43293. _this.NUM_BONE_INFLUENCERS = 0;
  43294. _this.BonesPerMesh = 0;
  43295. _this.BONETEXTURE = false;
  43296. _this.INSTANCES = false;
  43297. _this.GLOSSINESS = false;
  43298. _this.ROUGHNESS = false;
  43299. _this.EMISSIVEASILLUMINATION = false;
  43300. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43301. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43302. _this.LIGHTMAP = false;
  43303. _this.LIGHTMAPDIRECTUV = 0;
  43304. _this.OBJECTSPACE_NORMALMAP = false;
  43305. _this.USELIGHTMAPASSHADOWMAP = false;
  43306. _this.REFLECTIONMAP_3D = false;
  43307. _this.REFLECTIONMAP_SPHERICAL = false;
  43308. _this.REFLECTIONMAP_PLANAR = false;
  43309. _this.REFLECTIONMAP_CUBIC = false;
  43310. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43311. _this.REFLECTIONMAP_PROJECTION = false;
  43312. _this.REFLECTIONMAP_SKYBOX = false;
  43313. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43314. _this.REFLECTIONMAP_EXPLICIT = false;
  43315. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43316. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43317. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43318. _this.INVERTCUBICMAP = false;
  43319. _this.LOGARITHMICDEPTH = false;
  43320. _this.REFRACTION = false;
  43321. _this.REFRACTIONMAP_3D = false;
  43322. _this.REFLECTIONOVERALPHA = false;
  43323. _this.TWOSIDEDLIGHTING = false;
  43324. _this.SHADOWFLOAT = false;
  43325. _this.MORPHTARGETS = false;
  43326. _this.MORPHTARGETS_NORMAL = false;
  43327. _this.MORPHTARGETS_TANGENT = false;
  43328. _this.NUM_MORPH_INFLUENCERS = 0;
  43329. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43330. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43331. _this.IMAGEPROCESSING = false;
  43332. _this.VIGNETTE = false;
  43333. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43334. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43335. _this.TONEMAPPING = false;
  43336. _this.TONEMAPPING_ACES = false;
  43337. _this.CONTRAST = false;
  43338. _this.COLORCURVES = false;
  43339. _this.COLORGRADING = false;
  43340. _this.COLORGRADING3D = false;
  43341. _this.SAMPLER3DGREENDEPTH = false;
  43342. _this.SAMPLER3DBGRMAP = false;
  43343. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43344. /**
  43345. * If the reflection texture on this material is in linear color space
  43346. * @hidden
  43347. */
  43348. _this.IS_REFLECTION_LINEAR = false;
  43349. /**
  43350. * If the refraction texture on this material is in linear color space
  43351. * @hidden
  43352. */
  43353. _this.IS_REFRACTION_LINEAR = false;
  43354. _this.EXPOSURE = false;
  43355. _this.rebuild();
  43356. return _this;
  43357. }
  43358. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43359. var modes = [
  43360. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43361. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43362. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43363. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43364. ];
  43365. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43366. var mode = modes_1[_i];
  43367. this[mode] = (mode === modeToEnable);
  43368. }
  43369. };
  43370. return StandardMaterialDefines;
  43371. }(BABYLON.MaterialDefines));
  43372. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43373. /**
  43374. * This is the default material used in Babylon. It is the best trade off between quality
  43375. * and performances.
  43376. * @see http://doc.babylonjs.com/babylon101/materials
  43377. */
  43378. var StandardMaterial = /** @class */ (function (_super) {
  43379. __extends(StandardMaterial, _super);
  43380. /**
  43381. * Instantiates a new standard material.
  43382. * This is the default material used in Babylon. It is the best trade off between quality
  43383. * and performances.
  43384. * @see http://doc.babylonjs.com/babylon101/materials
  43385. * @param name Define the name of the material in the scene
  43386. * @param scene Define the scene the material belong to
  43387. */
  43388. function StandardMaterial(name, scene) {
  43389. var _this = _super.call(this, name, scene) || this;
  43390. /**
  43391. * The color of the material lit by the environmental background lighting.
  43392. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  43393. */
  43394. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43395. /**
  43396. * The basic color of the material as viewed under a light.
  43397. */
  43398. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43399. /**
  43400. * Define how the color and intensity of the highlight given by the light in the material.
  43401. */
  43402. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43403. /**
  43404. * Define the color of the material as if self lit.
  43405. * This will be mixed in the final result even in the absence of light.
  43406. */
  43407. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43408. /**
  43409. * Defines how sharp are the highlights in the material.
  43410. * The bigger the value the sharper giving a more glossy feeling to the result.
  43411. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  43412. */
  43413. _this.specularPower = 64;
  43414. _this._useAlphaFromDiffuseTexture = false;
  43415. _this._useEmissiveAsIllumination = false;
  43416. _this._linkEmissiveWithDiffuse = false;
  43417. _this._useSpecularOverAlpha = false;
  43418. _this._useReflectionOverAlpha = false;
  43419. _this._disableLighting = false;
  43420. _this._useObjectSpaceNormalMap = false;
  43421. _this._useParallax = false;
  43422. _this._useParallaxOcclusion = false;
  43423. /**
  43424. * 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.
  43425. */
  43426. _this.parallaxScaleBias = 0.05;
  43427. _this._roughness = 0;
  43428. /**
  43429. * In case of refraction, define the value of the indice of refraction.
  43430. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43431. */
  43432. _this.indexOfRefraction = 0.98;
  43433. /**
  43434. * Invert the refraction texture alongside the y axis.
  43435. * It can be usefull with procedural textures or probe for instance.
  43436. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43437. */
  43438. _this.invertRefractionY = true;
  43439. /**
  43440. * Defines the alpha limits in alpha test mode.
  43441. */
  43442. _this.alphaCutOff = 0.4;
  43443. _this._useLightmapAsShadowmap = false;
  43444. _this._useReflectionFresnelFromSpecular = false;
  43445. _this._useGlossinessFromSpecularMapAlpha = false;
  43446. _this._maxSimultaneousLights = 4;
  43447. _this._invertNormalMapX = false;
  43448. _this._invertNormalMapY = false;
  43449. _this._twoSidedLighting = false;
  43450. _this._renderTargets = new BABYLON.SmartArray(16);
  43451. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43452. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43453. // Setup the default processing configuration to the scene.
  43454. _this._attachImageProcessingConfiguration(null);
  43455. _this.getRenderTargetTextures = function () {
  43456. _this._renderTargets.reset();
  43457. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43458. _this._renderTargets.push(_this._reflectionTexture);
  43459. }
  43460. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43461. _this._renderTargets.push(_this._refractionTexture);
  43462. }
  43463. return _this._renderTargets;
  43464. };
  43465. return _this;
  43466. }
  43467. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43468. /**
  43469. * Gets the image processing configuration used either in this material.
  43470. */
  43471. get: function () {
  43472. return this._imageProcessingConfiguration;
  43473. },
  43474. /**
  43475. * Sets the Default image processing configuration used either in the this material.
  43476. *
  43477. * If sets to null, the scene one is in use.
  43478. */
  43479. set: function (value) {
  43480. this._attachImageProcessingConfiguration(value);
  43481. // Ensure the effect will be rebuilt.
  43482. this._markAllSubMeshesAsTexturesDirty();
  43483. },
  43484. enumerable: true,
  43485. configurable: true
  43486. });
  43487. /**
  43488. * Attaches a new image processing configuration to the Standard Material.
  43489. * @param configuration
  43490. */
  43491. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43492. var _this = this;
  43493. if (configuration === this._imageProcessingConfiguration) {
  43494. return;
  43495. }
  43496. // Detaches observer.
  43497. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43498. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43499. }
  43500. // Pick the scene configuration if needed.
  43501. if (!configuration) {
  43502. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43503. }
  43504. else {
  43505. this._imageProcessingConfiguration = configuration;
  43506. }
  43507. // Attaches observer.
  43508. if (this._imageProcessingConfiguration) {
  43509. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43510. _this._markAllSubMeshesAsImageProcessingDirty();
  43511. });
  43512. }
  43513. };
  43514. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43515. /**
  43516. * Gets wether the color curves effect is enabled.
  43517. */
  43518. get: function () {
  43519. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43520. },
  43521. /**
  43522. * Sets wether the color curves effect is enabled.
  43523. */
  43524. set: function (value) {
  43525. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43526. },
  43527. enumerable: true,
  43528. configurable: true
  43529. });
  43530. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43531. /**
  43532. * Gets wether the color grading effect is enabled.
  43533. */
  43534. get: function () {
  43535. return this.imageProcessingConfiguration.colorGradingEnabled;
  43536. },
  43537. /**
  43538. * Gets wether the color grading effect is enabled.
  43539. */
  43540. set: function (value) {
  43541. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43542. },
  43543. enumerable: true,
  43544. configurable: true
  43545. });
  43546. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43547. /**
  43548. * Gets wether tonemapping is enabled or not.
  43549. */
  43550. get: function () {
  43551. return this._imageProcessingConfiguration.toneMappingEnabled;
  43552. },
  43553. /**
  43554. * Sets wether tonemapping is enabled or not
  43555. */
  43556. set: function (value) {
  43557. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43558. },
  43559. enumerable: true,
  43560. configurable: true
  43561. });
  43562. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43563. /**
  43564. * The camera exposure used on this material.
  43565. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43566. * This corresponds to a photographic exposure.
  43567. */
  43568. get: function () {
  43569. return this._imageProcessingConfiguration.exposure;
  43570. },
  43571. /**
  43572. * The camera exposure used on this material.
  43573. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43574. * This corresponds to a photographic exposure.
  43575. */
  43576. set: function (value) {
  43577. this._imageProcessingConfiguration.exposure = value;
  43578. },
  43579. enumerable: true,
  43580. configurable: true
  43581. });
  43582. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43583. /**
  43584. * Gets The camera contrast used on this material.
  43585. */
  43586. get: function () {
  43587. return this._imageProcessingConfiguration.contrast;
  43588. },
  43589. /**
  43590. * Sets The camera contrast used on this material.
  43591. */
  43592. set: function (value) {
  43593. this._imageProcessingConfiguration.contrast = value;
  43594. },
  43595. enumerable: true,
  43596. configurable: true
  43597. });
  43598. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43599. /**
  43600. * Gets the Color Grading 2D Lookup Texture.
  43601. */
  43602. get: function () {
  43603. return this._imageProcessingConfiguration.colorGradingTexture;
  43604. },
  43605. /**
  43606. * Sets the Color Grading 2D Lookup Texture.
  43607. */
  43608. set: function (value) {
  43609. this._imageProcessingConfiguration.colorGradingTexture = value;
  43610. },
  43611. enumerable: true,
  43612. configurable: true
  43613. });
  43614. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43615. /**
  43616. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43617. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43618. * 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;
  43619. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43620. */
  43621. get: function () {
  43622. return this._imageProcessingConfiguration.colorCurves;
  43623. },
  43624. /**
  43625. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43626. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43627. * 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;
  43628. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43629. */
  43630. set: function (value) {
  43631. this._imageProcessingConfiguration.colorCurves = value;
  43632. },
  43633. enumerable: true,
  43634. configurable: true
  43635. });
  43636. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  43637. /**
  43638. * Gets a boolean indicating that current material needs to register RTT
  43639. */
  43640. get: function () {
  43641. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43642. return true;
  43643. }
  43644. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43645. return true;
  43646. }
  43647. return false;
  43648. },
  43649. enumerable: true,
  43650. configurable: true
  43651. });
  43652. /**
  43653. * Gets the current class name of the material e.g. "StandardMaterial"
  43654. * Mainly use in serialization.
  43655. * @returns the class name
  43656. */
  43657. StandardMaterial.prototype.getClassName = function () {
  43658. return "StandardMaterial";
  43659. };
  43660. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43661. /**
  43662. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  43663. * You can try switching to logarithmic depth.
  43664. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  43665. */
  43666. get: function () {
  43667. return this._useLogarithmicDepth;
  43668. },
  43669. set: function (value) {
  43670. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43671. this._markAllSubMeshesAsMiscDirty();
  43672. },
  43673. enumerable: true,
  43674. configurable: true
  43675. });
  43676. /**
  43677. * Specifies if the material will require alpha blending
  43678. * @returns a boolean specifying if alpha blending is needed
  43679. */
  43680. StandardMaterial.prototype.needAlphaBlending = function () {
  43681. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43682. };
  43683. /**
  43684. * Specifies if this material should be rendered in alpha test mode
  43685. * @returns a boolean specifying if an alpha test is needed.
  43686. */
  43687. StandardMaterial.prototype.needAlphaTesting = function () {
  43688. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43689. };
  43690. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43691. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43692. };
  43693. /**
  43694. * Get the texture used for alpha test purpose.
  43695. * @returns the diffuse texture in case of the standard material.
  43696. */
  43697. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43698. return this._diffuseTexture;
  43699. };
  43700. /**
  43701. * Get if the submesh is ready to be used and all its information available.
  43702. * Child classes can use it to update shaders
  43703. * @param mesh defines the mesh to check
  43704. * @param subMesh defines which submesh to check
  43705. * @param useInstances specifies that instances should be used
  43706. * @returns a boolean indicating that the submesh is ready or not
  43707. */
  43708. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43709. if (useInstances === void 0) { useInstances = false; }
  43710. if (subMesh.effect && this.isFrozen) {
  43711. if (this._wasPreviouslyReady) {
  43712. return true;
  43713. }
  43714. }
  43715. if (!subMesh._materialDefines) {
  43716. subMesh._materialDefines = new StandardMaterialDefines();
  43717. }
  43718. var scene = this.getScene();
  43719. var defines = subMesh._materialDefines;
  43720. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43721. if (defines._renderId === scene.getRenderId()) {
  43722. return true;
  43723. }
  43724. }
  43725. var engine = scene.getEngine();
  43726. // Lights
  43727. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43728. // Textures
  43729. if (defines._areTexturesDirty) {
  43730. defines._needUVs = false;
  43731. defines.MAINUV1 = false;
  43732. defines.MAINUV2 = false;
  43733. if (scene.texturesEnabled) {
  43734. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43735. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43736. return false;
  43737. }
  43738. else {
  43739. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43740. }
  43741. }
  43742. else {
  43743. defines.DIFFUSE = false;
  43744. }
  43745. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43746. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43747. return false;
  43748. }
  43749. else {
  43750. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43751. }
  43752. }
  43753. else {
  43754. defines.AMBIENT = false;
  43755. }
  43756. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43757. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43758. return false;
  43759. }
  43760. else {
  43761. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43762. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43763. }
  43764. }
  43765. else {
  43766. defines.OPACITY = false;
  43767. }
  43768. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43769. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43770. return false;
  43771. }
  43772. else {
  43773. defines._needNormals = true;
  43774. defines.REFLECTION = true;
  43775. defines.ROUGHNESS = (this._roughness > 0);
  43776. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43777. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43778. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43779. switch (this._reflectionTexture.coordinatesMode) {
  43780. case BABYLON.Texture.EXPLICIT_MODE:
  43781. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43782. break;
  43783. case BABYLON.Texture.PLANAR_MODE:
  43784. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43785. break;
  43786. case BABYLON.Texture.PROJECTION_MODE:
  43787. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43788. break;
  43789. case BABYLON.Texture.SKYBOX_MODE:
  43790. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43791. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43792. break;
  43793. case BABYLON.Texture.SPHERICAL_MODE:
  43794. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43795. break;
  43796. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43797. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43798. break;
  43799. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43800. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43801. break;
  43802. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43803. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43804. break;
  43805. case BABYLON.Texture.CUBIC_MODE:
  43806. case BABYLON.Texture.INVCUBIC_MODE:
  43807. default:
  43808. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43809. break;
  43810. }
  43811. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43812. }
  43813. }
  43814. else {
  43815. defines.REFLECTION = false;
  43816. }
  43817. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43818. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43819. return false;
  43820. }
  43821. else {
  43822. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43823. }
  43824. }
  43825. else {
  43826. defines.EMISSIVE = false;
  43827. }
  43828. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43829. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43830. return false;
  43831. }
  43832. else {
  43833. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43834. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43835. }
  43836. }
  43837. else {
  43838. defines.LIGHTMAP = false;
  43839. }
  43840. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43841. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43842. return false;
  43843. }
  43844. else {
  43845. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43846. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43847. }
  43848. }
  43849. else {
  43850. defines.SPECULAR = false;
  43851. }
  43852. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43853. // Bump texure can not be not blocking.
  43854. if (!this._bumpTexture.isReady()) {
  43855. return false;
  43856. }
  43857. else {
  43858. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43859. defines.PARALLAX = this._useParallax;
  43860. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43861. }
  43862. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43863. }
  43864. else {
  43865. defines.BUMP = false;
  43866. }
  43867. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43868. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43869. return false;
  43870. }
  43871. else {
  43872. defines._needUVs = true;
  43873. defines.REFRACTION = true;
  43874. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43875. }
  43876. }
  43877. else {
  43878. defines.REFRACTION = false;
  43879. }
  43880. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43881. }
  43882. else {
  43883. defines.DIFFUSE = false;
  43884. defines.AMBIENT = false;
  43885. defines.OPACITY = false;
  43886. defines.REFLECTION = false;
  43887. defines.EMISSIVE = false;
  43888. defines.LIGHTMAP = false;
  43889. defines.BUMP = false;
  43890. defines.REFRACTION = false;
  43891. }
  43892. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43893. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43894. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43895. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43896. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43897. }
  43898. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43899. if (!this._imageProcessingConfiguration.isReady()) {
  43900. return false;
  43901. }
  43902. this._imageProcessingConfiguration.prepareDefines(defines);
  43903. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43904. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43905. }
  43906. if (defines._areFresnelDirty) {
  43907. if (StandardMaterial.FresnelEnabled) {
  43908. // Fresnel
  43909. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43910. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43911. this._reflectionFresnelParameters) {
  43912. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43913. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43914. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43915. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43916. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43917. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43918. defines._needNormals = true;
  43919. defines.FRESNEL = true;
  43920. }
  43921. }
  43922. else {
  43923. defines.FRESNEL = false;
  43924. }
  43925. }
  43926. // Misc.
  43927. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43928. // Attribs
  43929. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43930. // Values that need to be evaluated on every frame
  43931. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43932. // Get correct effect
  43933. if (defines.isDirty) {
  43934. defines.markAsProcessed();
  43935. // Fallbacks
  43936. var fallbacks = new BABYLON.EffectFallbacks();
  43937. if (defines.REFLECTION) {
  43938. fallbacks.addFallback(0, "REFLECTION");
  43939. }
  43940. if (defines.SPECULAR) {
  43941. fallbacks.addFallback(0, "SPECULAR");
  43942. }
  43943. if (defines.BUMP) {
  43944. fallbacks.addFallback(0, "BUMP");
  43945. }
  43946. if (defines.PARALLAX) {
  43947. fallbacks.addFallback(1, "PARALLAX");
  43948. }
  43949. if (defines.PARALLAXOCCLUSION) {
  43950. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43951. }
  43952. if (defines.SPECULAROVERALPHA) {
  43953. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43954. }
  43955. if (defines.FOG) {
  43956. fallbacks.addFallback(1, "FOG");
  43957. }
  43958. if (defines.POINTSIZE) {
  43959. fallbacks.addFallback(0, "POINTSIZE");
  43960. }
  43961. if (defines.LOGARITHMICDEPTH) {
  43962. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43963. }
  43964. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43965. if (defines.SPECULARTERM) {
  43966. fallbacks.addFallback(0, "SPECULARTERM");
  43967. }
  43968. if (defines.DIFFUSEFRESNEL) {
  43969. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43970. }
  43971. if (defines.OPACITYFRESNEL) {
  43972. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43973. }
  43974. if (defines.REFLECTIONFRESNEL) {
  43975. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43976. }
  43977. if (defines.EMISSIVEFRESNEL) {
  43978. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43979. }
  43980. if (defines.FRESNEL) {
  43981. fallbacks.addFallback(4, "FRESNEL");
  43982. }
  43983. //Attributes
  43984. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43985. if (defines.NORMAL) {
  43986. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43987. }
  43988. if (defines.UV1) {
  43989. attribs.push(BABYLON.VertexBuffer.UVKind);
  43990. }
  43991. if (defines.UV2) {
  43992. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43993. }
  43994. if (defines.VERTEXCOLOR) {
  43995. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43996. }
  43997. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43998. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43999. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44000. var shaderName = "default";
  44001. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  44002. "vFogInfos", "vFogColor", "pointSize",
  44003. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44004. "mBones",
  44005. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  44006. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  44007. "vReflectionPosition", "vReflectionSize",
  44008. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff", "boneTextureWidth"
  44009. ];
  44010. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler",
  44011. "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  44012. "refractionCubeSampler", "refraction2DSampler", "boneSampler"];
  44013. var uniformBuffers = ["Material", "Scene"];
  44014. if (BABYLON.ImageProcessingConfiguration) {
  44015. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44016. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44017. }
  44018. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44019. uniformsNames: uniforms,
  44020. uniformBuffersNames: uniformBuffers,
  44021. samplers: samplers,
  44022. defines: defines,
  44023. maxSimultaneousLights: this._maxSimultaneousLights
  44024. });
  44025. if (this.customShaderNameResolve) {
  44026. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  44027. }
  44028. var join = defines.toString();
  44029. var previousEffect = subMesh.effect;
  44030. var effect = scene.getEngine().createEffect(shaderName, {
  44031. attributes: attribs,
  44032. uniformsNames: uniforms,
  44033. uniformBuffersNames: uniformBuffers,
  44034. samplers: samplers,
  44035. defines: join,
  44036. fallbacks: fallbacks,
  44037. onCompiled: this.onCompiled,
  44038. onError: this.onError,
  44039. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44040. }, engine);
  44041. if (effect) {
  44042. // Use previous effect while new one is compiling
  44043. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  44044. effect = previousEffect;
  44045. defines.markAsUnprocessed();
  44046. }
  44047. else {
  44048. scene.resetCachedMaterial();
  44049. subMesh.setEffect(effect, defines);
  44050. this.buildUniformLayout();
  44051. }
  44052. }
  44053. }
  44054. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44055. return false;
  44056. }
  44057. defines._renderId = scene.getRenderId();
  44058. this._wasPreviouslyReady = true;
  44059. return true;
  44060. };
  44061. /**
  44062. * Builds the material UBO layouts.
  44063. * Used internally during the effect preparation.
  44064. */
  44065. StandardMaterial.prototype.buildUniformLayout = function () {
  44066. // Order is important !
  44067. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44068. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44069. this._uniformBuffer.addUniform("opacityParts", 4);
  44070. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44071. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44072. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44073. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44074. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44075. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44076. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44077. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44078. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44079. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44080. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44081. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44082. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44083. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44084. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44085. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44086. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44087. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44088. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44089. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44090. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44091. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44092. this._uniformBuffer.addUniform("specularMatrix", 16);
  44093. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44094. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44095. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44096. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44097. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44098. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44099. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44100. this._uniformBuffer.addUniform("pointSize", 1);
  44101. this._uniformBuffer.create();
  44102. };
  44103. /**
  44104. * Unbinds the material from the mesh
  44105. */
  44106. StandardMaterial.prototype.unbind = function () {
  44107. if (this._activeEffect) {
  44108. var needFlag = false;
  44109. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44110. this._activeEffect.setTexture("reflection2DSampler", null);
  44111. needFlag = true;
  44112. }
  44113. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44114. this._activeEffect.setTexture("refraction2DSampler", null);
  44115. needFlag = true;
  44116. }
  44117. if (needFlag) {
  44118. this._markAllSubMeshesAsTexturesDirty();
  44119. }
  44120. }
  44121. _super.prototype.unbind.call(this);
  44122. };
  44123. /**
  44124. * Binds the submesh to this material by preparing the effect and shader to draw
  44125. * @param world defines the world transformation matrix
  44126. * @param mesh defines the mesh containing the submesh
  44127. * @param subMesh defines the submesh to bind the material to
  44128. */
  44129. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44130. var scene = this.getScene();
  44131. var defines = subMesh._materialDefines;
  44132. if (!defines) {
  44133. return;
  44134. }
  44135. var effect = subMesh.effect;
  44136. if (!effect) {
  44137. return;
  44138. }
  44139. this._activeEffect = effect;
  44140. // Matrices
  44141. this.bindOnlyWorldMatrix(world);
  44142. // Normal Matrix
  44143. if (defines.OBJECTSPACE_NORMALMAP) {
  44144. world.toNormalMatrix(this._normalMatrix);
  44145. this.bindOnlyNormalMatrix(this._normalMatrix);
  44146. }
  44147. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44148. // Bones
  44149. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44150. if (mustRebind) {
  44151. this._uniformBuffer.bindToEffect(effect, "Material");
  44152. this.bindViewProjection(effect);
  44153. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44154. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44155. // Fresnel
  44156. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44157. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44158. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44159. }
  44160. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44161. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44162. }
  44163. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44164. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44165. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44166. }
  44167. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44168. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44169. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44170. }
  44171. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44172. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44173. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44174. }
  44175. }
  44176. // Textures
  44177. if (scene.texturesEnabled) {
  44178. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44179. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44180. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44181. if (this._diffuseTexture.hasAlpha) {
  44182. effect.setFloat("alphaCutOff", this.alphaCutOff);
  44183. }
  44184. }
  44185. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44186. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44187. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44188. }
  44189. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44190. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44191. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44192. }
  44193. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44194. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44195. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44196. if (this._reflectionTexture.boundingBoxSize) {
  44197. var cubeTexture = this._reflectionTexture;
  44198. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44199. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44200. }
  44201. }
  44202. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44203. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44204. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44205. }
  44206. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44207. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44208. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44209. }
  44210. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44211. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44212. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44213. }
  44214. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44215. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44216. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44217. if (scene._mirroredCameraPosition) {
  44218. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44219. }
  44220. else {
  44221. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44222. }
  44223. }
  44224. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44225. var depth = 1.0;
  44226. if (!this._refractionTexture.isCube) {
  44227. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44228. if (this._refractionTexture.depth) {
  44229. depth = this._refractionTexture.depth;
  44230. }
  44231. }
  44232. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44233. }
  44234. }
  44235. // Point size
  44236. if (this.pointsCloud) {
  44237. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44238. }
  44239. if (defines.SPECULARTERM) {
  44240. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44241. }
  44242. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44243. // Diffuse
  44244. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44245. }
  44246. // Textures
  44247. if (scene.texturesEnabled) {
  44248. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44249. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44250. }
  44251. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44252. effect.setTexture("ambientSampler", this._ambientTexture);
  44253. }
  44254. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44255. effect.setTexture("opacitySampler", this._opacityTexture);
  44256. }
  44257. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44258. if (this._reflectionTexture.isCube) {
  44259. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44260. }
  44261. else {
  44262. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44263. }
  44264. }
  44265. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44266. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44267. }
  44268. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44269. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44270. }
  44271. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44272. effect.setTexture("specularSampler", this._specularTexture);
  44273. }
  44274. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44275. effect.setTexture("bumpSampler", this._bumpTexture);
  44276. }
  44277. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44278. var depth = 1.0;
  44279. if (this._refractionTexture.isCube) {
  44280. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44281. }
  44282. else {
  44283. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44284. }
  44285. }
  44286. }
  44287. // Clip plane
  44288. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44289. // Colors
  44290. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44291. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44292. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44293. }
  44294. if (mustRebind || !this.isFrozen) {
  44295. // Lights
  44296. if (scene.lightsEnabled && !this._disableLighting) {
  44297. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44298. }
  44299. // View
  44300. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44301. this.bindView(effect);
  44302. }
  44303. // Fog
  44304. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44305. // Morph targets
  44306. if (defines.NUM_MORPH_INFLUENCERS) {
  44307. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44308. }
  44309. // Log. depth
  44310. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44311. // image processing
  44312. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  44313. this._imageProcessingConfiguration.bind(this._activeEffect);
  44314. }
  44315. }
  44316. this._uniformBuffer.update();
  44317. this._afterBind(mesh, this._activeEffect);
  44318. };
  44319. /**
  44320. * Get the list of animatables in the material.
  44321. * @returns the list of animatables object used in the material
  44322. */
  44323. StandardMaterial.prototype.getAnimatables = function () {
  44324. var results = [];
  44325. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44326. results.push(this._diffuseTexture);
  44327. }
  44328. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44329. results.push(this._ambientTexture);
  44330. }
  44331. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44332. results.push(this._opacityTexture);
  44333. }
  44334. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44335. results.push(this._reflectionTexture);
  44336. }
  44337. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44338. results.push(this._emissiveTexture);
  44339. }
  44340. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44341. results.push(this._specularTexture);
  44342. }
  44343. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44344. results.push(this._bumpTexture);
  44345. }
  44346. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44347. results.push(this._lightmapTexture);
  44348. }
  44349. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44350. results.push(this._refractionTexture);
  44351. }
  44352. return results;
  44353. };
  44354. /**
  44355. * Gets the active textures from the material
  44356. * @returns an array of textures
  44357. */
  44358. StandardMaterial.prototype.getActiveTextures = function () {
  44359. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44360. if (this._diffuseTexture) {
  44361. activeTextures.push(this._diffuseTexture);
  44362. }
  44363. if (this._ambientTexture) {
  44364. activeTextures.push(this._ambientTexture);
  44365. }
  44366. if (this._opacityTexture) {
  44367. activeTextures.push(this._opacityTexture);
  44368. }
  44369. if (this._reflectionTexture) {
  44370. activeTextures.push(this._reflectionTexture);
  44371. }
  44372. if (this._emissiveTexture) {
  44373. activeTextures.push(this._emissiveTexture);
  44374. }
  44375. if (this._specularTexture) {
  44376. activeTextures.push(this._specularTexture);
  44377. }
  44378. if (this._bumpTexture) {
  44379. activeTextures.push(this._bumpTexture);
  44380. }
  44381. if (this._lightmapTexture) {
  44382. activeTextures.push(this._lightmapTexture);
  44383. }
  44384. if (this._refractionTexture) {
  44385. activeTextures.push(this._refractionTexture);
  44386. }
  44387. return activeTextures;
  44388. };
  44389. /**
  44390. * Specifies if the material uses a texture
  44391. * @param texture defines the texture to check against the material
  44392. * @returns a boolean specifying if the material uses the texture
  44393. */
  44394. StandardMaterial.prototype.hasTexture = function (texture) {
  44395. if (_super.prototype.hasTexture.call(this, texture)) {
  44396. return true;
  44397. }
  44398. if (this._diffuseTexture === texture) {
  44399. return true;
  44400. }
  44401. if (this._ambientTexture === texture) {
  44402. return true;
  44403. }
  44404. if (this._opacityTexture === texture) {
  44405. return true;
  44406. }
  44407. if (this._reflectionTexture === texture) {
  44408. return true;
  44409. }
  44410. if (this._emissiveTexture === texture) {
  44411. return true;
  44412. }
  44413. if (this._specularTexture === texture) {
  44414. return true;
  44415. }
  44416. if (this._bumpTexture === texture) {
  44417. return true;
  44418. }
  44419. if (this._lightmapTexture === texture) {
  44420. return true;
  44421. }
  44422. if (this._refractionTexture === texture) {
  44423. return true;
  44424. }
  44425. return false;
  44426. };
  44427. /**
  44428. * Disposes the material
  44429. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  44430. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  44431. */
  44432. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44433. if (forceDisposeTextures) {
  44434. if (this._diffuseTexture) {
  44435. this._diffuseTexture.dispose();
  44436. }
  44437. if (this._ambientTexture) {
  44438. this._ambientTexture.dispose();
  44439. }
  44440. if (this._opacityTexture) {
  44441. this._opacityTexture.dispose();
  44442. }
  44443. if (this._reflectionTexture) {
  44444. this._reflectionTexture.dispose();
  44445. }
  44446. if (this._emissiveTexture) {
  44447. this._emissiveTexture.dispose();
  44448. }
  44449. if (this._specularTexture) {
  44450. this._specularTexture.dispose();
  44451. }
  44452. if (this._bumpTexture) {
  44453. this._bumpTexture.dispose();
  44454. }
  44455. if (this._lightmapTexture) {
  44456. this._lightmapTexture.dispose();
  44457. }
  44458. if (this._refractionTexture) {
  44459. this._refractionTexture.dispose();
  44460. }
  44461. }
  44462. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44463. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44464. }
  44465. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44466. };
  44467. /**
  44468. * Makes a duplicate of the material, and gives it a new name
  44469. * @param name defines the new name for the duplicated material
  44470. * @returns the cloned material
  44471. */
  44472. StandardMaterial.prototype.clone = function (name) {
  44473. var _this = this;
  44474. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44475. result.name = name;
  44476. result.id = name;
  44477. return result;
  44478. };
  44479. /**
  44480. * Serializes this material in a JSON representation
  44481. * @returns the serialized material object
  44482. */
  44483. StandardMaterial.prototype.serialize = function () {
  44484. return BABYLON.SerializationHelper.Serialize(this);
  44485. };
  44486. /**
  44487. * Creates a standard material from parsed material data
  44488. * @param source defines the JSON represnetation of the material
  44489. * @param scene defines the hosting scene
  44490. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  44491. * @returns a new material
  44492. */
  44493. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44494. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44495. };
  44496. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44497. /**
  44498. * Are diffuse textures enabled in the application.
  44499. */
  44500. get: function () {
  44501. return StandardMaterial._DiffuseTextureEnabled;
  44502. },
  44503. set: function (value) {
  44504. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44505. return;
  44506. }
  44507. StandardMaterial._DiffuseTextureEnabled = value;
  44508. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44509. },
  44510. enumerable: true,
  44511. configurable: true
  44512. });
  44513. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44514. /**
  44515. * Are ambient textures enabled in the application.
  44516. */
  44517. get: function () {
  44518. return StandardMaterial._AmbientTextureEnabled;
  44519. },
  44520. set: function (value) {
  44521. if (StandardMaterial._AmbientTextureEnabled === value) {
  44522. return;
  44523. }
  44524. StandardMaterial._AmbientTextureEnabled = value;
  44525. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44526. },
  44527. enumerable: true,
  44528. configurable: true
  44529. });
  44530. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44531. /**
  44532. * Are opacity textures enabled in the application.
  44533. */
  44534. get: function () {
  44535. return StandardMaterial._OpacityTextureEnabled;
  44536. },
  44537. set: function (value) {
  44538. if (StandardMaterial._OpacityTextureEnabled === value) {
  44539. return;
  44540. }
  44541. StandardMaterial._OpacityTextureEnabled = value;
  44542. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44543. },
  44544. enumerable: true,
  44545. configurable: true
  44546. });
  44547. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44548. /**
  44549. * Are reflection textures enabled in the application.
  44550. */
  44551. get: function () {
  44552. return StandardMaterial._ReflectionTextureEnabled;
  44553. },
  44554. set: function (value) {
  44555. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44556. return;
  44557. }
  44558. StandardMaterial._ReflectionTextureEnabled = value;
  44559. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44560. },
  44561. enumerable: true,
  44562. configurable: true
  44563. });
  44564. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44565. /**
  44566. * Are emissive textures enabled in the application.
  44567. */
  44568. get: function () {
  44569. return StandardMaterial._EmissiveTextureEnabled;
  44570. },
  44571. set: function (value) {
  44572. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44573. return;
  44574. }
  44575. StandardMaterial._EmissiveTextureEnabled = value;
  44576. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44577. },
  44578. enumerable: true,
  44579. configurable: true
  44580. });
  44581. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44582. /**
  44583. * Are specular textures enabled in the application.
  44584. */
  44585. get: function () {
  44586. return StandardMaterial._SpecularTextureEnabled;
  44587. },
  44588. set: function (value) {
  44589. if (StandardMaterial._SpecularTextureEnabled === value) {
  44590. return;
  44591. }
  44592. StandardMaterial._SpecularTextureEnabled = value;
  44593. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44594. },
  44595. enumerable: true,
  44596. configurable: true
  44597. });
  44598. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44599. /**
  44600. * Are bump textures enabled in the application.
  44601. */
  44602. get: function () {
  44603. return StandardMaterial._BumpTextureEnabled;
  44604. },
  44605. set: function (value) {
  44606. if (StandardMaterial._BumpTextureEnabled === value) {
  44607. return;
  44608. }
  44609. StandardMaterial._BumpTextureEnabled = value;
  44610. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44611. },
  44612. enumerable: true,
  44613. configurable: true
  44614. });
  44615. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44616. /**
  44617. * Are lightmap textures enabled in the application.
  44618. */
  44619. get: function () {
  44620. return StandardMaterial._LightmapTextureEnabled;
  44621. },
  44622. set: function (value) {
  44623. if (StandardMaterial._LightmapTextureEnabled === value) {
  44624. return;
  44625. }
  44626. StandardMaterial._LightmapTextureEnabled = value;
  44627. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44628. },
  44629. enumerable: true,
  44630. configurable: true
  44631. });
  44632. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44633. /**
  44634. * Are refraction textures enabled in the application.
  44635. */
  44636. get: function () {
  44637. return StandardMaterial._RefractionTextureEnabled;
  44638. },
  44639. set: function (value) {
  44640. if (StandardMaterial._RefractionTextureEnabled === value) {
  44641. return;
  44642. }
  44643. StandardMaterial._RefractionTextureEnabled = value;
  44644. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44645. },
  44646. enumerable: true,
  44647. configurable: true
  44648. });
  44649. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44650. /**
  44651. * Are color grading textures enabled in the application.
  44652. */
  44653. get: function () {
  44654. return StandardMaterial._ColorGradingTextureEnabled;
  44655. },
  44656. set: function (value) {
  44657. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44658. return;
  44659. }
  44660. StandardMaterial._ColorGradingTextureEnabled = value;
  44661. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44662. },
  44663. enumerable: true,
  44664. configurable: true
  44665. });
  44666. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44667. /**
  44668. * Are fresnels enabled in the application.
  44669. */
  44670. get: function () {
  44671. return StandardMaterial._FresnelEnabled;
  44672. },
  44673. set: function (value) {
  44674. if (StandardMaterial._FresnelEnabled === value) {
  44675. return;
  44676. }
  44677. StandardMaterial._FresnelEnabled = value;
  44678. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44679. },
  44680. enumerable: true,
  44681. configurable: true
  44682. });
  44683. // Flags used to enable or disable a type of texture for all Standard Materials
  44684. StandardMaterial._DiffuseTextureEnabled = true;
  44685. StandardMaterial._AmbientTextureEnabled = true;
  44686. StandardMaterial._OpacityTextureEnabled = true;
  44687. StandardMaterial._ReflectionTextureEnabled = true;
  44688. StandardMaterial._EmissiveTextureEnabled = true;
  44689. StandardMaterial._SpecularTextureEnabled = true;
  44690. StandardMaterial._BumpTextureEnabled = true;
  44691. StandardMaterial._LightmapTextureEnabled = true;
  44692. StandardMaterial._RefractionTextureEnabled = true;
  44693. StandardMaterial._ColorGradingTextureEnabled = true;
  44694. StandardMaterial._FresnelEnabled = true;
  44695. __decorate([
  44696. BABYLON.serializeAsTexture("diffuseTexture")
  44697. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44698. __decorate([
  44699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44700. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44701. __decorate([
  44702. BABYLON.serializeAsTexture("ambientTexture")
  44703. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44704. __decorate([
  44705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44706. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44707. __decorate([
  44708. BABYLON.serializeAsTexture("opacityTexture")
  44709. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44710. __decorate([
  44711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44712. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44713. __decorate([
  44714. BABYLON.serializeAsTexture("reflectionTexture")
  44715. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44716. __decorate([
  44717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44718. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44719. __decorate([
  44720. BABYLON.serializeAsTexture("emissiveTexture")
  44721. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44722. __decorate([
  44723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44724. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44725. __decorate([
  44726. BABYLON.serializeAsTexture("specularTexture")
  44727. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44728. __decorate([
  44729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44730. ], StandardMaterial.prototype, "specularTexture", void 0);
  44731. __decorate([
  44732. BABYLON.serializeAsTexture("bumpTexture")
  44733. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44734. __decorate([
  44735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44736. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44737. __decorate([
  44738. BABYLON.serializeAsTexture("lightmapTexture")
  44739. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44740. __decorate([
  44741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44742. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44743. __decorate([
  44744. BABYLON.serializeAsTexture("refractionTexture")
  44745. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44746. __decorate([
  44747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44748. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44749. __decorate([
  44750. BABYLON.serializeAsColor3("ambient")
  44751. ], StandardMaterial.prototype, "ambientColor", void 0);
  44752. __decorate([
  44753. BABYLON.serializeAsColor3("diffuse")
  44754. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44755. __decorate([
  44756. BABYLON.serializeAsColor3("specular")
  44757. ], StandardMaterial.prototype, "specularColor", void 0);
  44758. __decorate([
  44759. BABYLON.serializeAsColor3("emissive")
  44760. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44761. __decorate([
  44762. BABYLON.serialize()
  44763. ], StandardMaterial.prototype, "specularPower", void 0);
  44764. __decorate([
  44765. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44766. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44767. __decorate([
  44768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44769. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44770. __decorate([
  44771. BABYLON.serialize("useEmissiveAsIllumination")
  44772. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44773. __decorate([
  44774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44775. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44776. __decorate([
  44777. BABYLON.serialize("linkEmissiveWithDiffuse")
  44778. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44779. __decorate([
  44780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44781. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44782. __decorate([
  44783. BABYLON.serialize("useSpecularOverAlpha")
  44784. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44785. __decorate([
  44786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44787. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44788. __decorate([
  44789. BABYLON.serialize("useReflectionOverAlpha")
  44790. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44791. __decorate([
  44792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44793. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44794. __decorate([
  44795. BABYLON.serialize("disableLighting")
  44796. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44797. __decorate([
  44798. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44799. ], StandardMaterial.prototype, "disableLighting", void 0);
  44800. __decorate([
  44801. BABYLON.serialize("useObjectSpaceNormalMap")
  44802. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44803. __decorate([
  44804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44805. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44806. __decorate([
  44807. BABYLON.serialize("useParallax")
  44808. ], StandardMaterial.prototype, "_useParallax", void 0);
  44809. __decorate([
  44810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44811. ], StandardMaterial.prototype, "useParallax", void 0);
  44812. __decorate([
  44813. BABYLON.serialize("useParallaxOcclusion")
  44814. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44815. __decorate([
  44816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44817. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44818. __decorate([
  44819. BABYLON.serialize()
  44820. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44821. __decorate([
  44822. BABYLON.serialize("roughness")
  44823. ], StandardMaterial.prototype, "_roughness", void 0);
  44824. __decorate([
  44825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44826. ], StandardMaterial.prototype, "roughness", void 0);
  44827. __decorate([
  44828. BABYLON.serialize()
  44829. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44830. __decorate([
  44831. BABYLON.serialize()
  44832. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44833. __decorate([
  44834. BABYLON.serialize()
  44835. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44836. __decorate([
  44837. BABYLON.serialize("useLightmapAsShadowmap")
  44838. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44839. __decorate([
  44840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44841. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44842. __decorate([
  44843. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44844. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44845. __decorate([
  44846. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44847. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44848. __decorate([
  44849. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44850. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44851. __decorate([
  44852. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44853. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44854. __decorate([
  44855. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44856. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44857. __decorate([
  44858. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44859. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44860. __decorate([
  44861. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44862. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44863. __decorate([
  44864. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44865. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44866. __decorate([
  44867. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44868. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44869. __decorate([
  44870. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44871. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44872. __decorate([
  44873. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44874. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44875. __decorate([
  44876. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44877. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44878. __decorate([
  44879. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44880. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44881. __decorate([
  44882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44883. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44884. __decorate([
  44885. BABYLON.serialize("maxSimultaneousLights")
  44886. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44887. __decorate([
  44888. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44889. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44890. __decorate([
  44891. BABYLON.serialize("invertNormalMapX")
  44892. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44893. __decorate([
  44894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44895. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44896. __decorate([
  44897. BABYLON.serialize("invertNormalMapY")
  44898. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44899. __decorate([
  44900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44901. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44902. __decorate([
  44903. BABYLON.serialize("twoSidedLighting")
  44904. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44905. __decorate([
  44906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44907. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44908. __decorate([
  44909. BABYLON.serialize()
  44910. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44911. return StandardMaterial;
  44912. }(BABYLON.PushMaterial));
  44913. BABYLON.StandardMaterial = StandardMaterial;
  44914. })(BABYLON || (BABYLON = {}));
  44915. //# sourceMappingURL=babylon.standardMaterial.js.map
  44916. var BABYLON;
  44917. (function (BABYLON) {
  44918. /**
  44919. * Class representing spherical polynomial coefficients to the 3rd degree
  44920. */
  44921. var SphericalPolynomial = /** @class */ (function () {
  44922. function SphericalPolynomial() {
  44923. /**
  44924. * The x coefficients of the spherical polynomial
  44925. */
  44926. this.x = BABYLON.Vector3.Zero();
  44927. /**
  44928. * The y coefficients of the spherical polynomial
  44929. */
  44930. this.y = BABYLON.Vector3.Zero();
  44931. /**
  44932. * The z coefficients of the spherical polynomial
  44933. */
  44934. this.z = BABYLON.Vector3.Zero();
  44935. /**
  44936. * The xx coefficients of the spherical polynomial
  44937. */
  44938. this.xx = BABYLON.Vector3.Zero();
  44939. /**
  44940. * The yy coefficients of the spherical polynomial
  44941. */
  44942. this.yy = BABYLON.Vector3.Zero();
  44943. /**
  44944. * The zz coefficients of the spherical polynomial
  44945. */
  44946. this.zz = BABYLON.Vector3.Zero();
  44947. /**
  44948. * The xy coefficients of the spherical polynomial
  44949. */
  44950. this.xy = BABYLON.Vector3.Zero();
  44951. /**
  44952. * The yz coefficients of the spherical polynomial
  44953. */
  44954. this.yz = BABYLON.Vector3.Zero();
  44955. /**
  44956. * The zx coefficients of the spherical polynomial
  44957. */
  44958. this.zx = BABYLON.Vector3.Zero();
  44959. }
  44960. /**
  44961. * Adds an ambient color to the spherical polynomial
  44962. * @param color the color to add
  44963. */
  44964. SphericalPolynomial.prototype.addAmbient = function (color) {
  44965. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44966. this.xx = this.xx.add(colorVector);
  44967. this.yy = this.yy.add(colorVector);
  44968. this.zz = this.zz.add(colorVector);
  44969. };
  44970. /**
  44971. * Scales the spherical polynomial by the given amount
  44972. * @param scale the amount to scale
  44973. */
  44974. SphericalPolynomial.prototype.scale = function (scale) {
  44975. this.x = this.x.scale(scale);
  44976. this.y = this.y.scale(scale);
  44977. this.z = this.z.scale(scale);
  44978. this.xx = this.xx.scale(scale);
  44979. this.yy = this.yy.scale(scale);
  44980. this.zz = this.zz.scale(scale);
  44981. this.yz = this.yz.scale(scale);
  44982. this.zx = this.zx.scale(scale);
  44983. this.xy = this.xy.scale(scale);
  44984. };
  44985. /**
  44986. * Gets the spherical polynomial from harmonics
  44987. * @param harmonics the spherical harmonics
  44988. * @returns the spherical polynomial
  44989. */
  44990. SphericalPolynomial.FromHarmonics = function (harmonics) {
  44991. var result = new SphericalPolynomial();
  44992. result.x = harmonics.l11.scale(1.02333);
  44993. result.y = harmonics.l1_1.scale(1.02333);
  44994. result.z = harmonics.l10.scale(1.02333);
  44995. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  44996. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  44997. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  44998. result.yz = harmonics.l2_1.scale(0.858086);
  44999. result.zx = harmonics.l21.scale(0.858086);
  45000. result.xy = harmonics.l2_2.scale(0.858086);
  45001. result.scale(1.0 / Math.PI);
  45002. return result;
  45003. };
  45004. /**
  45005. * Constructs a spherical polynomial from an array.
  45006. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  45007. * @returns the spherical polynomial
  45008. */
  45009. SphericalPolynomial.FromArray = function (data) {
  45010. var sp = new SphericalPolynomial();
  45011. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  45012. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  45013. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  45014. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  45015. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  45016. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  45017. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  45018. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  45019. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  45020. return sp;
  45021. };
  45022. return SphericalPolynomial;
  45023. }());
  45024. BABYLON.SphericalPolynomial = SphericalPolynomial;
  45025. /**
  45026. * Class representing spherical harmonics coefficients to the 3rd degree
  45027. */
  45028. var SphericalHarmonics = /** @class */ (function () {
  45029. function SphericalHarmonics() {
  45030. /**
  45031. * The l0,0 coefficients of the spherical harmonics
  45032. */
  45033. this.l00 = BABYLON.Vector3.Zero();
  45034. /**
  45035. * The l1,-1 coefficients of the spherical harmonics
  45036. */
  45037. this.l1_1 = BABYLON.Vector3.Zero();
  45038. /**
  45039. * The l1,0 coefficients of the spherical harmonics
  45040. */
  45041. this.l10 = BABYLON.Vector3.Zero();
  45042. /**
  45043. * The l1,1 coefficients of the spherical harmonics
  45044. */
  45045. this.l11 = BABYLON.Vector3.Zero();
  45046. /**
  45047. * The l2,-2 coefficients of the spherical harmonics
  45048. */
  45049. this.l2_2 = BABYLON.Vector3.Zero();
  45050. /**
  45051. * The l2,-1 coefficients of the spherical harmonics
  45052. */
  45053. this.l2_1 = BABYLON.Vector3.Zero();
  45054. /**
  45055. * The l2,0 coefficients of the spherical harmonics
  45056. */
  45057. this.l20 = BABYLON.Vector3.Zero();
  45058. /**
  45059. * The l2,1 coefficients of the spherical harmonics
  45060. */
  45061. this.l21 = BABYLON.Vector3.Zero();
  45062. /**
  45063. * The l2,2 coefficients of the spherical harmonics
  45064. */
  45065. this.lL22 = BABYLON.Vector3.Zero();
  45066. }
  45067. /**
  45068. * Adds a light to the spherical harmonics
  45069. * @param direction the direction of the light
  45070. * @param color the color of the light
  45071. * @param deltaSolidAngle the delta solid angle of the light
  45072. */
  45073. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  45074. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  45075. var c = colorVector.scale(deltaSolidAngle);
  45076. this.l00 = this.l00.add(c.scale(0.282095));
  45077. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  45078. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  45079. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  45080. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  45081. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  45082. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  45083. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  45084. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  45085. };
  45086. /**
  45087. * Scales the spherical harmonics by the given amount
  45088. * @param scale the amount to scale
  45089. */
  45090. SphericalHarmonics.prototype.scale = function (scale) {
  45091. this.l00 = this.l00.scale(scale);
  45092. this.l1_1 = this.l1_1.scale(scale);
  45093. this.l10 = this.l10.scale(scale);
  45094. this.l11 = this.l11.scale(scale);
  45095. this.l2_2 = this.l2_2.scale(scale);
  45096. this.l2_1 = this.l2_1.scale(scale);
  45097. this.l20 = this.l20.scale(scale);
  45098. this.l21 = this.l21.scale(scale);
  45099. this.lL22 = this.lL22.scale(scale);
  45100. };
  45101. /**
  45102. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  45103. *
  45104. * ```
  45105. * E_lm = A_l * L_lm
  45106. * ```
  45107. *
  45108. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  45109. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  45110. * the scaling factors are given in equation 9.
  45111. */
  45112. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  45113. // Constant (Band 0)
  45114. this.l00 = this.l00.scale(3.141593);
  45115. // Linear (Band 1)
  45116. this.l1_1 = this.l1_1.scale(2.094395);
  45117. this.l10 = this.l10.scale(2.094395);
  45118. this.l11 = this.l11.scale(2.094395);
  45119. // Quadratic (Band 2)
  45120. this.l2_2 = this.l2_2.scale(0.785398);
  45121. this.l2_1 = this.l2_1.scale(0.785398);
  45122. this.l20 = this.l20.scale(0.785398);
  45123. this.l21 = this.l21.scale(0.785398);
  45124. this.lL22 = this.lL22.scale(0.785398);
  45125. };
  45126. /**
  45127. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  45128. *
  45129. * ```
  45130. * L = (1/pi) * E * rho
  45131. * ```
  45132. *
  45133. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  45134. */
  45135. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  45136. this.scale(1.0 / Math.PI);
  45137. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  45138. // (The pixel shader must apply albedo after texture fetches, etc).
  45139. };
  45140. /**
  45141. * Gets the spherical harmonics from polynomial
  45142. * @param polynomial the spherical polynomial
  45143. * @returns the spherical harmonics
  45144. */
  45145. SphericalHarmonics.FromPolynomial = function (polynomial) {
  45146. var result = new SphericalHarmonics();
  45147. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  45148. result.l1_1 = polynomial.y.scale(0.977204);
  45149. result.l10 = polynomial.z.scale(0.977204);
  45150. result.l11 = polynomial.x.scale(0.977204);
  45151. result.l2_2 = polynomial.xy.scale(1.16538);
  45152. result.l2_1 = polynomial.yz.scale(1.16538);
  45153. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  45154. result.l21 = polynomial.zx.scale(1.16538);
  45155. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  45156. result.scale(Math.PI);
  45157. return result;
  45158. };
  45159. /**
  45160. * Constructs a spherical harmonics from an array.
  45161. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  45162. * @returns the spherical harmonics
  45163. */
  45164. SphericalHarmonics.FromArray = function (data) {
  45165. var sh = new SphericalHarmonics();
  45166. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  45167. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  45168. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  45169. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  45170. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  45171. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  45172. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  45173. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  45174. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  45175. return sh;
  45176. };
  45177. return SphericalHarmonics;
  45178. }());
  45179. BABYLON.SphericalHarmonics = SphericalHarmonics;
  45180. })(BABYLON || (BABYLON = {}));
  45181. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  45182. var BABYLON;
  45183. (function (BABYLON) {
  45184. var FileFaceOrientation = /** @class */ (function () {
  45185. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  45186. this.name = name;
  45187. this.worldAxisForNormal = worldAxisForNormal;
  45188. this.worldAxisForFileX = worldAxisForFileX;
  45189. this.worldAxisForFileY = worldAxisForFileY;
  45190. }
  45191. return FileFaceOrientation;
  45192. }());
  45193. /**
  45194. * Helper class dealing with the extraction of spherical polynomial dataArray
  45195. * from a cube map.
  45196. */
  45197. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  45198. function CubeMapToSphericalPolynomialTools() {
  45199. }
  45200. /**
  45201. * Converts a texture to the according Spherical Polynomial data.
  45202. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45203. *
  45204. * @param texture The texture to extract the information from.
  45205. * @return The Spherical Polynomial data.
  45206. */
  45207. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  45208. if (!texture.isCube) {
  45209. // Only supports cube Textures currently.
  45210. return null;
  45211. }
  45212. var size = texture.getSize().width;
  45213. var right = texture.readPixels(0);
  45214. var left = texture.readPixels(1);
  45215. var up;
  45216. var down;
  45217. if (texture.isRenderTarget) {
  45218. up = texture.readPixels(3);
  45219. down = texture.readPixels(2);
  45220. }
  45221. else {
  45222. up = texture.readPixels(2);
  45223. down = texture.readPixels(3);
  45224. }
  45225. var front = texture.readPixels(4);
  45226. var back = texture.readPixels(5);
  45227. var gammaSpace = texture.gammaSpace;
  45228. // Always read as RGBA.
  45229. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  45230. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  45231. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45232. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  45233. }
  45234. var cubeInfo = {
  45235. size: size,
  45236. right: right,
  45237. left: left,
  45238. up: up,
  45239. down: down,
  45240. front: front,
  45241. back: back,
  45242. format: format,
  45243. type: type,
  45244. gammaSpace: gammaSpace,
  45245. };
  45246. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  45247. };
  45248. /**
  45249. * Converts a cubemap to the according Spherical Polynomial data.
  45250. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45251. *
  45252. * @param cubeInfo The Cube map to extract the information from.
  45253. * @return The Spherical Polynomial data.
  45254. */
  45255. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  45256. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  45257. var totalSolidAngle = 0.0;
  45258. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  45259. var du = 2.0 / cubeInfo.size;
  45260. var dv = du;
  45261. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  45262. var minUV = du * 0.5 - 1.0;
  45263. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  45264. var fileFace = this.FileFaces[faceIndex];
  45265. var dataArray = cubeInfo[fileFace.name];
  45266. var v = minUV;
  45267. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  45268. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  45269. // Because SP is still linear, so summation is fine in that basis.
  45270. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  45271. for (var y = 0; y < cubeInfo.size; y++) {
  45272. var u = minUV;
  45273. for (var x = 0; x < cubeInfo.size; x++) {
  45274. // World direction (not normalised)
  45275. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  45276. worldDirection.normalize();
  45277. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  45278. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  45279. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  45280. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  45281. // Handle Integer types.
  45282. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45283. r /= 255;
  45284. g /= 255;
  45285. b /= 255;
  45286. }
  45287. // Handle Gamma space textures.
  45288. if (cubeInfo.gammaSpace) {
  45289. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  45290. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  45291. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  45292. }
  45293. var color = new BABYLON.Color3(r, g, b);
  45294. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45295. totalSolidAngle += deltaSolidAngle;
  45296. u += du;
  45297. }
  45298. v += dv;
  45299. }
  45300. }
  45301. // Solid angle for entire sphere is 4*pi
  45302. var sphereSolidAngle = 4.0 * Math.PI;
  45303. // Adjust the solid angle to allow for how many faces we processed.
  45304. var facesProcessed = 6.0;
  45305. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  45306. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  45307. // This is needed because the numerical integration over the cube uses a
  45308. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  45309. // and also to compensate for accumulative error due to float precision in the summation.
  45310. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  45311. sphericalHarmonics.scale(correctionFactor);
  45312. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  45313. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  45314. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  45315. };
  45316. CubeMapToSphericalPolynomialTools.FileFaces = [
  45317. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  45318. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  45319. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  45320. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  45321. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  45322. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  45323. ];
  45324. return CubeMapToSphericalPolynomialTools;
  45325. }());
  45326. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  45327. })(BABYLON || (BABYLON = {}));
  45328. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  45329. var BABYLON;
  45330. (function (BABYLON) {
  45331. /**
  45332. * Manages the defines for the PBR Material.
  45333. * @hiddenChildren
  45334. */
  45335. var PBRMaterialDefines = /** @class */ (function (_super) {
  45336. __extends(PBRMaterialDefines, _super);
  45337. /**
  45338. * Initializes the PBR Material defines.
  45339. */
  45340. function PBRMaterialDefines() {
  45341. var _this = _super.call(this) || this;
  45342. _this.PBR = true;
  45343. _this.MAINUV1 = false;
  45344. _this.MAINUV2 = false;
  45345. _this.UV1 = false;
  45346. _this.UV2 = false;
  45347. _this.ALBEDO = false;
  45348. _this.ALBEDODIRECTUV = 0;
  45349. _this.VERTEXCOLOR = false;
  45350. _this.AMBIENT = false;
  45351. _this.AMBIENTDIRECTUV = 0;
  45352. _this.AMBIENTINGRAYSCALE = false;
  45353. _this.OPACITY = false;
  45354. _this.VERTEXALPHA = false;
  45355. _this.OPACITYDIRECTUV = 0;
  45356. _this.OPACITYRGB = false;
  45357. _this.ALPHATEST = false;
  45358. _this.DEPTHPREPASS = false;
  45359. _this.ALPHABLEND = false;
  45360. _this.ALPHAFROMALBEDO = false;
  45361. _this.ALPHATESTVALUE = "0.5";
  45362. _this.SPECULAROVERALPHA = false;
  45363. _this.RADIANCEOVERALPHA = false;
  45364. _this.ALPHAFRESNEL = false;
  45365. _this.LINEARALPHAFRESNEL = false;
  45366. _this.PREMULTIPLYALPHA = false;
  45367. _this.EMISSIVE = false;
  45368. _this.EMISSIVEDIRECTUV = 0;
  45369. _this.REFLECTIVITY = false;
  45370. _this.REFLECTIVITYDIRECTUV = 0;
  45371. _this.SPECULARTERM = false;
  45372. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  45373. _this.MICROSURFACEAUTOMATIC = false;
  45374. _this.LODBASEDMICROSFURACE = false;
  45375. _this.MICROSURFACEMAP = false;
  45376. _this.MICROSURFACEMAPDIRECTUV = 0;
  45377. _this.METALLICWORKFLOW = false;
  45378. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  45379. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  45380. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  45381. _this.AOSTOREINMETALMAPRED = false;
  45382. _this.ENVIRONMENTBRDF = false;
  45383. _this.NORMAL = false;
  45384. _this.TANGENT = false;
  45385. _this.BUMP = false;
  45386. _this.BUMPDIRECTUV = 0;
  45387. _this.OBJECTSPACE_NORMALMAP = false;
  45388. _this.PARALLAX = false;
  45389. _this.PARALLAXOCCLUSION = false;
  45390. _this.NORMALXYSCALE = true;
  45391. _this.LIGHTMAP = false;
  45392. _this.LIGHTMAPDIRECTUV = 0;
  45393. _this.USELIGHTMAPASSHADOWMAP = false;
  45394. _this.GAMMALIGHTMAP = false;
  45395. _this.REFLECTION = false;
  45396. _this.REFLECTIONMAP_3D = false;
  45397. _this.REFLECTIONMAP_SPHERICAL = false;
  45398. _this.REFLECTIONMAP_PLANAR = false;
  45399. _this.REFLECTIONMAP_CUBIC = false;
  45400. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45401. _this.REFLECTIONMAP_PROJECTION = false;
  45402. _this.REFLECTIONMAP_SKYBOX = false;
  45403. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45404. _this.REFLECTIONMAP_EXPLICIT = false;
  45405. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45406. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45407. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45408. _this.INVERTCUBICMAP = false;
  45409. _this.USESPHERICALFROMREFLECTIONMAP = false;
  45410. _this.USESPHERICALINVERTEX = false;
  45411. _this.REFLECTIONMAP_OPPOSITEZ = false;
  45412. _this.LODINREFLECTIONALPHA = false;
  45413. _this.GAMMAREFLECTION = false;
  45414. _this.RGBDREFLECTION = false;
  45415. _this.RADIANCEOCCLUSION = false;
  45416. _this.HORIZONOCCLUSION = false;
  45417. _this.REFRACTION = false;
  45418. _this.REFRACTIONMAP_3D = false;
  45419. _this.REFRACTIONMAP_OPPOSITEZ = false;
  45420. _this.LODINREFRACTIONALPHA = false;
  45421. _this.GAMMAREFRACTION = false;
  45422. _this.RGBDREFRACTION = false;
  45423. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  45424. _this.INSTANCES = false;
  45425. _this.NUM_BONE_INFLUENCERS = 0;
  45426. _this.BonesPerMesh = 0;
  45427. _this.BONETEXTURE = false;
  45428. _this.NONUNIFORMSCALING = false;
  45429. _this.MORPHTARGETS = false;
  45430. _this.MORPHTARGETS_NORMAL = false;
  45431. _this.MORPHTARGETS_TANGENT = false;
  45432. _this.NUM_MORPH_INFLUENCERS = 0;
  45433. _this.IMAGEPROCESSING = false;
  45434. _this.VIGNETTE = false;
  45435. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  45436. _this.VIGNETTEBLENDMODEOPAQUE = false;
  45437. _this.TONEMAPPING = false;
  45438. _this.TONEMAPPING_ACES = false;
  45439. _this.CONTRAST = false;
  45440. _this.COLORCURVES = false;
  45441. _this.COLORGRADING = false;
  45442. _this.COLORGRADING3D = false;
  45443. _this.SAMPLER3DGREENDEPTH = false;
  45444. _this.SAMPLER3DBGRMAP = false;
  45445. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  45446. _this.EXPOSURE = false;
  45447. _this.USEPHYSICALLIGHTFALLOFF = false;
  45448. _this.USEGLTFLIGHTFALLOFF = false;
  45449. _this.TWOSIDEDLIGHTING = false;
  45450. _this.SHADOWFLOAT = false;
  45451. _this.CLIPPLANE = false;
  45452. _this.CLIPPLANE2 = false;
  45453. _this.CLIPPLANE3 = false;
  45454. _this.CLIPPLANE4 = false;
  45455. _this.POINTSIZE = false;
  45456. _this.FOG = false;
  45457. _this.LOGARITHMICDEPTH = false;
  45458. _this.FORCENORMALFORWARD = false;
  45459. _this.SPECULARAA = false;
  45460. _this.UNLIT = false;
  45461. _this.rebuild();
  45462. return _this;
  45463. }
  45464. /**
  45465. * Resets the PBR Material defines.
  45466. */
  45467. PBRMaterialDefines.prototype.reset = function () {
  45468. _super.prototype.reset.call(this);
  45469. this.ALPHATESTVALUE = "0.5";
  45470. this.PBR = true;
  45471. };
  45472. return PBRMaterialDefines;
  45473. }(BABYLON.MaterialDefines));
  45474. /**
  45475. * The Physically based material base class of BJS.
  45476. *
  45477. * This offers the main features of a standard PBR material.
  45478. * For more information, please refer to the documentation :
  45479. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45480. */
  45481. var PBRBaseMaterial = /** @class */ (function (_super) {
  45482. __extends(PBRBaseMaterial, _super);
  45483. /**
  45484. * Instantiates a new PBRMaterial instance.
  45485. *
  45486. * @param name The material name
  45487. * @param scene The scene the material will be use in.
  45488. */
  45489. function PBRBaseMaterial(name, scene) {
  45490. var _this = _super.call(this, name, scene) || this;
  45491. /**
  45492. * Intensity of the direct lights e.g. the four lights available in your scene.
  45493. * This impacts both the direct diffuse and specular highlights.
  45494. */
  45495. _this._directIntensity = 1.0;
  45496. /**
  45497. * Intensity of the emissive part of the material.
  45498. * This helps controlling the emissive effect without modifying the emissive color.
  45499. */
  45500. _this._emissiveIntensity = 1.0;
  45501. /**
  45502. * Intensity of the environment e.g. how much the environment will light the object
  45503. * either through harmonics for rough material or through the refelction for shiny ones.
  45504. */
  45505. _this._environmentIntensity = 1.0;
  45506. /**
  45507. * This is a special control allowing the reduction of the specular highlights coming from the
  45508. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45509. */
  45510. _this._specularIntensity = 1.0;
  45511. /**
  45512. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  45513. */
  45514. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  45515. /**
  45516. * Debug Control allowing disabling the bump map on this material.
  45517. */
  45518. _this._disableBumpMap = false;
  45519. /**
  45520. * AKA Occlusion Texture Intensity in other nomenclature.
  45521. */
  45522. _this._ambientTextureStrength = 1.0;
  45523. /**
  45524. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45525. * 1 means it completely occludes it
  45526. * 0 mean it has no impact
  45527. */
  45528. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45529. /**
  45530. * The color of a material in ambient lighting.
  45531. */
  45532. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  45533. /**
  45534. * AKA Diffuse Color in other nomenclature.
  45535. */
  45536. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  45537. /**
  45538. * AKA Specular Color in other nomenclature.
  45539. */
  45540. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45541. /**
  45542. * The color applied when light is reflected from a material.
  45543. */
  45544. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  45545. /**
  45546. * The color applied when light is emitted from a material.
  45547. */
  45548. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  45549. /**
  45550. * AKA Glossiness in other nomenclature.
  45551. */
  45552. _this._microSurface = 0.9;
  45553. /**
  45554. * source material index of refraction (IOR)' / 'destination material IOR.
  45555. */
  45556. _this._indexOfRefraction = 0.66;
  45557. /**
  45558. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45559. */
  45560. _this._invertRefractionY = false;
  45561. /**
  45562. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45563. * Materials half opaque for instance using refraction could benefit from this control.
  45564. */
  45565. _this._linkRefractionWithTransparency = false;
  45566. /**
  45567. * Specifies that the material will use the light map as a show map.
  45568. */
  45569. _this._useLightmapAsShadowmap = false;
  45570. /**
  45571. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45572. * makes the reflect vector face the model (under horizon).
  45573. */
  45574. _this._useHorizonOcclusion = true;
  45575. /**
  45576. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45577. * too much the area relying on ambient texture to define their ambient occlusion.
  45578. */
  45579. _this._useRadianceOcclusion = true;
  45580. /**
  45581. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45582. */
  45583. _this._useAlphaFromAlbedoTexture = false;
  45584. /**
  45585. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45586. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45587. */
  45588. _this._useSpecularOverAlpha = true;
  45589. /**
  45590. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45591. */
  45592. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  45593. /**
  45594. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45595. */
  45596. _this._useRoughnessFromMetallicTextureAlpha = true;
  45597. /**
  45598. * Specifies if the metallic texture contains the roughness information in its green channel.
  45599. */
  45600. _this._useRoughnessFromMetallicTextureGreen = false;
  45601. /**
  45602. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45603. */
  45604. _this._useMetallnessFromMetallicTextureBlue = false;
  45605. /**
  45606. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45607. */
  45608. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  45609. /**
  45610. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45611. */
  45612. _this._useAmbientInGrayScale = false;
  45613. /**
  45614. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45615. * The material will try to infer what glossiness each pixel should be.
  45616. */
  45617. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  45618. /**
  45619. * Defines the falloff type used in this material.
  45620. * It by default is Physical.
  45621. */
  45622. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45623. /**
  45624. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45625. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45626. */
  45627. _this._useRadianceOverAlpha = true;
  45628. /**
  45629. * Allows using an object space normal map (instead of tangent space).
  45630. */
  45631. _this._useObjectSpaceNormalMap = false;
  45632. /**
  45633. * Allows using the bump map in parallax mode.
  45634. */
  45635. _this._useParallax = false;
  45636. /**
  45637. * Allows using the bump map in parallax occlusion mode.
  45638. */
  45639. _this._useParallaxOcclusion = false;
  45640. /**
  45641. * Controls the scale bias of the parallax mode.
  45642. */
  45643. _this._parallaxScaleBias = 0.05;
  45644. /**
  45645. * If sets to true, disables all the lights affecting the material.
  45646. */
  45647. _this._disableLighting = false;
  45648. /**
  45649. * Number of Simultaneous lights allowed on the material.
  45650. */
  45651. _this._maxSimultaneousLights = 4;
  45652. /**
  45653. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  45654. */
  45655. _this._invertNormalMapX = false;
  45656. /**
  45657. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  45658. */
  45659. _this._invertNormalMapY = false;
  45660. /**
  45661. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45662. */
  45663. _this._twoSidedLighting = false;
  45664. /**
  45665. * Defines the alpha limits in alpha test mode.
  45666. */
  45667. _this._alphaCutOff = 0.4;
  45668. /**
  45669. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45670. */
  45671. _this._forceAlphaTest = false;
  45672. /**
  45673. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45674. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45675. */
  45676. _this._useAlphaFresnel = false;
  45677. /**
  45678. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45679. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45680. */
  45681. _this._useLinearAlphaFresnel = false;
  45682. /**
  45683. * The transparency mode of the material.
  45684. */
  45685. _this._transparencyMode = null;
  45686. /**
  45687. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45688. * from cos thetav and roughness:
  45689. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45690. */
  45691. _this._environmentBRDFTexture = null;
  45692. /**
  45693. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45694. */
  45695. _this._forceIrradianceInFragment = false;
  45696. /**
  45697. * Force normal to face away from face.
  45698. */
  45699. _this._forceNormalForward = false;
  45700. /**
  45701. * Enables specular anti aliasing in the PBR shader.
  45702. * It will both interacts on the Geometry for analytical and IBL lighting.
  45703. * It also prefilter the roughness map based on the bump values.
  45704. */
  45705. _this._enableSpecularAntiAliasing = false;
  45706. /**
  45707. * Stores the available render targets.
  45708. */
  45709. _this._renderTargets = new BABYLON.SmartArray(16);
  45710. /**
  45711. * Sets the global ambient color for the material used in lighting calculations.
  45712. */
  45713. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45714. /**
  45715. * If set to true, no lighting calculations will be applied.
  45716. */
  45717. _this._unlit = false;
  45718. // Setup the default processing configuration to the scene.
  45719. _this._attachImageProcessingConfiguration(null);
  45720. _this.getRenderTargetTextures = function () {
  45721. _this._renderTargets.reset();
  45722. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45723. _this._renderTargets.push(_this._reflectionTexture);
  45724. }
  45725. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45726. _this._renderTargets.push(_this._refractionTexture);
  45727. }
  45728. return _this._renderTargets;
  45729. };
  45730. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45731. return _this;
  45732. }
  45733. /**
  45734. * Attaches a new image processing configuration to the PBR Material.
  45735. * @param configuration
  45736. */
  45737. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45738. var _this = this;
  45739. if (configuration === this._imageProcessingConfiguration) {
  45740. return;
  45741. }
  45742. // Detaches observer.
  45743. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45744. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45745. }
  45746. // Pick the scene configuration if needed.
  45747. if (!configuration) {
  45748. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45749. }
  45750. else {
  45751. this._imageProcessingConfiguration = configuration;
  45752. }
  45753. // Attaches observer.
  45754. if (this._imageProcessingConfiguration) {
  45755. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45756. _this._markAllSubMeshesAsImageProcessingDirty();
  45757. });
  45758. }
  45759. };
  45760. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  45761. /**
  45762. * Gets a boolean indicating that current material needs to register RTT
  45763. */
  45764. get: function () {
  45765. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45766. return true;
  45767. }
  45768. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45769. return true;
  45770. }
  45771. return false;
  45772. },
  45773. enumerable: true,
  45774. configurable: true
  45775. });
  45776. /**
  45777. * Gets the name of the material class.
  45778. */
  45779. PBRBaseMaterial.prototype.getClassName = function () {
  45780. return "PBRBaseMaterial";
  45781. };
  45782. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45783. /**
  45784. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45785. */
  45786. get: function () {
  45787. return this._useLogarithmicDepth;
  45788. },
  45789. /**
  45790. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45791. */
  45792. set: function (value) {
  45793. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45794. },
  45795. enumerable: true,
  45796. configurable: true
  45797. });
  45798. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45799. /**
  45800. * Gets the current transparency mode.
  45801. */
  45802. get: function () {
  45803. return this._transparencyMode;
  45804. },
  45805. /**
  45806. * Sets the transparency mode of the material.
  45807. *
  45808. * | Value | Type | Description |
  45809. * | ----- | ----------------------------------- | ----------- |
  45810. * | 0 | OPAQUE | |
  45811. * | 1 | ALPHATEST | |
  45812. * | 2 | ALPHABLEND | |
  45813. * | 3 | ALPHATESTANDBLEND | |
  45814. *
  45815. */
  45816. set: function (value) {
  45817. if (this._transparencyMode === value) {
  45818. return;
  45819. }
  45820. this._transparencyMode = value;
  45821. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45822. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45823. },
  45824. enumerable: true,
  45825. configurable: true
  45826. });
  45827. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45828. /**
  45829. * Returns true if alpha blending should be disabled.
  45830. */
  45831. get: function () {
  45832. return (this._linkRefractionWithTransparency ||
  45833. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45834. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45835. },
  45836. enumerable: true,
  45837. configurable: true
  45838. });
  45839. /**
  45840. * Specifies whether or not this material should be rendered in alpha blend mode.
  45841. */
  45842. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45843. if (this._disableAlphaBlending) {
  45844. return false;
  45845. }
  45846. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45847. };
  45848. /**
  45849. * Specifies if the mesh will require alpha blending.
  45850. * @param mesh - BJS mesh.
  45851. */
  45852. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45853. if (this._disableAlphaBlending) {
  45854. return false;
  45855. }
  45856. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45857. };
  45858. /**
  45859. * Specifies whether or not this material should be rendered in alpha test mode.
  45860. */
  45861. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45862. if (this._forceAlphaTest) {
  45863. return true;
  45864. }
  45865. if (this._linkRefractionWithTransparency) {
  45866. return false;
  45867. }
  45868. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45869. };
  45870. /**
  45871. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45872. */
  45873. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45874. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45875. };
  45876. /**
  45877. * Gets the texture used for the alpha test.
  45878. */
  45879. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45880. return this._albedoTexture;
  45881. };
  45882. /**
  45883. * Specifies that the submesh is ready to be used.
  45884. * @param mesh - BJS mesh.
  45885. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45886. * @param useInstances - Specifies that instances should be used.
  45887. * @returns - boolean indicating that the submesh is ready or not.
  45888. */
  45889. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45890. if (subMesh.effect && this.isFrozen) {
  45891. if (this._wasPreviouslyReady) {
  45892. return true;
  45893. }
  45894. }
  45895. if (!subMesh._materialDefines) {
  45896. subMesh._materialDefines = new PBRMaterialDefines();
  45897. }
  45898. var defines = subMesh._materialDefines;
  45899. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45900. if (defines._renderId === this.getScene().getRenderId()) {
  45901. return true;
  45902. }
  45903. }
  45904. var scene = this.getScene();
  45905. var engine = scene.getEngine();
  45906. if (defines._areTexturesDirty) {
  45907. if (scene.texturesEnabled) {
  45908. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45909. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45910. return false;
  45911. }
  45912. }
  45913. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45914. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45915. return false;
  45916. }
  45917. }
  45918. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45919. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45920. return false;
  45921. }
  45922. }
  45923. var reflectionTexture = this._getReflectionTexture();
  45924. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45925. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45926. return false;
  45927. }
  45928. }
  45929. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45930. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45931. return false;
  45932. }
  45933. }
  45934. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45935. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45936. return false;
  45937. }
  45938. }
  45939. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45940. if (this._metallicTexture) {
  45941. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45942. return false;
  45943. }
  45944. }
  45945. else if (this._reflectivityTexture) {
  45946. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45947. return false;
  45948. }
  45949. }
  45950. if (this._microSurfaceTexture) {
  45951. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45952. return false;
  45953. }
  45954. }
  45955. }
  45956. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45957. // Bump texture cannot be not blocking.
  45958. if (!this._bumpTexture.isReady()) {
  45959. return false;
  45960. }
  45961. }
  45962. var refractionTexture = this._getRefractionTexture();
  45963. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45964. if (!refractionTexture.isReadyOrNotBlocking()) {
  45965. return false;
  45966. }
  45967. }
  45968. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45969. // This is blocking.
  45970. if (!this._environmentBRDFTexture.isReady()) {
  45971. return false;
  45972. }
  45973. }
  45974. }
  45975. }
  45976. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45977. if (!this._imageProcessingConfiguration.isReady()) {
  45978. return false;
  45979. }
  45980. }
  45981. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45982. mesh.createNormals(true);
  45983. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45984. }
  45985. var previousEffect = subMesh.effect;
  45986. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45987. if (effect) {
  45988. // Use previous effect while new one is compiling
  45989. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  45990. effect = previousEffect;
  45991. defines.markAsUnprocessed();
  45992. }
  45993. else {
  45994. scene.resetCachedMaterial();
  45995. subMesh.setEffect(effect, defines);
  45996. this.buildUniformLayout();
  45997. }
  45998. }
  45999. if (!subMesh.effect || !subMesh.effect.isReady()) {
  46000. return false;
  46001. }
  46002. defines._renderId = scene.getRenderId();
  46003. this._wasPreviouslyReady = true;
  46004. return true;
  46005. };
  46006. /**
  46007. * Specifies if the material uses metallic roughness workflow.
  46008. * @returns boolean specifiying if the material uses metallic roughness workflow.
  46009. */
  46010. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  46011. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  46012. return true;
  46013. }
  46014. return false;
  46015. };
  46016. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  46017. if (onCompiled === void 0) { onCompiled = null; }
  46018. if (onError === void 0) { onError = null; }
  46019. if (useInstances === void 0) { useInstances = null; }
  46020. if (useClipPlane === void 0) { useClipPlane = null; }
  46021. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  46022. if (!defines.isDirty) {
  46023. return null;
  46024. }
  46025. defines.markAsProcessed();
  46026. var scene = this.getScene();
  46027. var engine = scene.getEngine();
  46028. // Fallbacks
  46029. var fallbacks = new BABYLON.EffectFallbacks();
  46030. var fallbackRank = 0;
  46031. if (defines.USESPHERICALINVERTEX) {
  46032. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  46033. }
  46034. if (defines.FOG) {
  46035. fallbacks.addFallback(fallbackRank, "FOG");
  46036. }
  46037. if (defines.SPECULARAA) {
  46038. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  46039. }
  46040. if (defines.POINTSIZE) {
  46041. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  46042. }
  46043. if (defines.LOGARITHMICDEPTH) {
  46044. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  46045. }
  46046. if (defines.PARALLAX) {
  46047. fallbacks.addFallback(fallbackRank, "PARALLAX");
  46048. }
  46049. if (defines.PARALLAXOCCLUSION) {
  46050. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  46051. }
  46052. if (defines.ENVIRONMENTBRDF) {
  46053. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  46054. }
  46055. if (defines.TANGENT) {
  46056. fallbacks.addFallback(fallbackRank++, "TANGENT");
  46057. }
  46058. if (defines.BUMP) {
  46059. fallbacks.addFallback(fallbackRank++, "BUMP");
  46060. }
  46061. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  46062. if (defines.SPECULARTERM) {
  46063. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  46064. }
  46065. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  46066. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  46067. }
  46068. if (defines.LIGHTMAP) {
  46069. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  46070. }
  46071. if (defines.NORMAL) {
  46072. fallbacks.addFallback(fallbackRank++, "NORMAL");
  46073. }
  46074. if (defines.AMBIENT) {
  46075. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  46076. }
  46077. if (defines.EMISSIVE) {
  46078. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  46079. }
  46080. if (defines.VERTEXCOLOR) {
  46081. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  46082. }
  46083. if (defines.NUM_BONE_INFLUENCERS > 0) {
  46084. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  46085. }
  46086. if (defines.MORPHTARGETS) {
  46087. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  46088. }
  46089. //Attributes
  46090. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46091. if (defines.NORMAL) {
  46092. attribs.push(BABYLON.VertexBuffer.NormalKind);
  46093. }
  46094. if (defines.TANGENT) {
  46095. attribs.push(BABYLON.VertexBuffer.TangentKind);
  46096. }
  46097. if (defines.UV1) {
  46098. attribs.push(BABYLON.VertexBuffer.UVKind);
  46099. }
  46100. if (defines.UV2) {
  46101. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46102. }
  46103. if (defines.VERTEXCOLOR) {
  46104. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46105. }
  46106. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  46107. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  46108. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  46109. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  46110. "vFogInfos", "vFogColor", "pointSize",
  46111. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  46112. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  46113. "mBones",
  46114. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  46115. "vLightingIntensity",
  46116. "logarithmicDepthConstant",
  46117. "vSphericalX", "vSphericalY", "vSphericalZ",
  46118. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  46119. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  46120. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  46121. "vTangentSpaceParams", "boneTextureWidth"
  46122. ];
  46123. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  46124. "bumpSampler", "lightmapSampler", "opacitySampler",
  46125. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  46126. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  46127. "microSurfaceSampler", "environmentBrdfSampler", "boneSampler"];
  46128. var uniformBuffers = ["Material", "Scene"];
  46129. if (BABYLON.ImageProcessingConfiguration) {
  46130. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  46131. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  46132. }
  46133. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  46134. uniformsNames: uniforms,
  46135. uniformBuffersNames: uniformBuffers,
  46136. samplers: samplers,
  46137. defines: defines,
  46138. maxSimultaneousLights: this._maxSimultaneousLights
  46139. });
  46140. var join = defines.toString();
  46141. return engine.createEffect("pbr", {
  46142. attributes: attribs,
  46143. uniformsNames: uniforms,
  46144. uniformBuffersNames: uniformBuffers,
  46145. samplers: samplers,
  46146. defines: join,
  46147. fallbacks: fallbacks,
  46148. onCompiled: onCompiled,
  46149. onError: onError,
  46150. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  46151. }, engine);
  46152. };
  46153. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  46154. if (useInstances === void 0) { useInstances = null; }
  46155. if (useClipPlane === void 0) { useClipPlane = null; }
  46156. var scene = this.getScene();
  46157. var engine = scene.getEngine();
  46158. // Lights
  46159. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  46160. defines._needNormals = true;
  46161. // Textures
  46162. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  46163. if (defines._areTexturesDirty) {
  46164. defines._needUVs = false;
  46165. if (scene.texturesEnabled) {
  46166. if (scene.getEngine().getCaps().textureLOD) {
  46167. defines.LODBASEDMICROSFURACE = true;
  46168. }
  46169. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46170. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  46171. }
  46172. else {
  46173. defines.ALBEDO = false;
  46174. }
  46175. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46176. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  46177. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  46178. }
  46179. else {
  46180. defines.AMBIENT = false;
  46181. }
  46182. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46183. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  46184. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  46185. }
  46186. else {
  46187. defines.OPACITY = false;
  46188. }
  46189. var reflectionTexture = this._getReflectionTexture();
  46190. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46191. defines.REFLECTION = true;
  46192. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  46193. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  46194. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  46195. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  46196. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  46197. defines.INVERTCUBICMAP = true;
  46198. }
  46199. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  46200. switch (reflectionTexture.coordinatesMode) {
  46201. case BABYLON.Texture.EXPLICIT_MODE:
  46202. defines.REFLECTIONMAP_EXPLICIT = true;
  46203. break;
  46204. case BABYLON.Texture.PLANAR_MODE:
  46205. defines.REFLECTIONMAP_PLANAR = true;
  46206. break;
  46207. case BABYLON.Texture.PROJECTION_MODE:
  46208. defines.REFLECTIONMAP_PROJECTION = true;
  46209. break;
  46210. case BABYLON.Texture.SKYBOX_MODE:
  46211. defines.REFLECTIONMAP_SKYBOX = true;
  46212. break;
  46213. case BABYLON.Texture.SPHERICAL_MODE:
  46214. defines.REFLECTIONMAP_SPHERICAL = true;
  46215. break;
  46216. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  46217. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  46218. break;
  46219. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  46220. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  46221. break;
  46222. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  46223. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  46224. break;
  46225. case BABYLON.Texture.CUBIC_MODE:
  46226. case BABYLON.Texture.INVCUBIC_MODE:
  46227. default:
  46228. defines.REFLECTIONMAP_CUBIC = true;
  46229. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  46230. break;
  46231. }
  46232. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  46233. if (reflectionTexture.sphericalPolynomial) {
  46234. defines.USESPHERICALFROMREFLECTIONMAP = true;
  46235. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  46236. defines.USESPHERICALINVERTEX = false;
  46237. }
  46238. else {
  46239. defines.USESPHERICALINVERTEX = true;
  46240. }
  46241. }
  46242. }
  46243. else {
  46244. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  46245. }
  46246. }
  46247. else {
  46248. defines.REFLECTION = false;
  46249. defines.REFLECTIONMAP_3D = false;
  46250. defines.REFLECTIONMAP_SPHERICAL = false;
  46251. defines.REFLECTIONMAP_PLANAR = false;
  46252. defines.REFLECTIONMAP_CUBIC = false;
  46253. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  46254. defines.REFLECTIONMAP_PROJECTION = false;
  46255. defines.REFLECTIONMAP_SKYBOX = false;
  46256. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  46257. defines.REFLECTIONMAP_EXPLICIT = false;
  46258. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  46259. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  46260. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  46261. defines.INVERTCUBICMAP = false;
  46262. defines.USESPHERICALFROMREFLECTIONMAP = false;
  46263. defines.USESPHERICALINVERTEX = false;
  46264. defines.REFLECTIONMAP_OPPOSITEZ = false;
  46265. defines.LODINREFLECTIONALPHA = false;
  46266. defines.GAMMAREFLECTION = false;
  46267. defines.RGBDREFLECTION = false;
  46268. }
  46269. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46270. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  46271. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  46272. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  46273. }
  46274. else {
  46275. defines.LIGHTMAP = false;
  46276. }
  46277. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46278. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  46279. }
  46280. else {
  46281. defines.EMISSIVE = false;
  46282. }
  46283. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46284. if (this._metallicTexture) {
  46285. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  46286. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  46287. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  46288. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  46289. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  46290. }
  46291. else if (this._reflectivityTexture) {
  46292. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  46293. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  46294. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  46295. }
  46296. else {
  46297. defines.REFLECTIVITY = false;
  46298. }
  46299. if (this._microSurfaceTexture) {
  46300. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  46301. }
  46302. else {
  46303. defines.MICROSURFACEMAP = false;
  46304. }
  46305. }
  46306. else {
  46307. defines.REFLECTIVITY = false;
  46308. defines.MICROSURFACEMAP = false;
  46309. }
  46310. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46311. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  46312. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46313. defines.PARALLAX = true;
  46314. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  46315. }
  46316. else {
  46317. defines.PARALLAX = false;
  46318. }
  46319. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  46320. }
  46321. else {
  46322. defines.BUMP = false;
  46323. }
  46324. var refractionTexture = this._getRefractionTexture();
  46325. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46326. defines.REFRACTION = true;
  46327. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  46328. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  46329. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  46330. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  46331. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  46332. if (this._linkRefractionWithTransparency) {
  46333. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  46334. }
  46335. }
  46336. else {
  46337. defines.REFRACTION = false;
  46338. }
  46339. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46340. defines.ENVIRONMENTBRDF = true;
  46341. }
  46342. else {
  46343. defines.ENVIRONMENTBRDF = false;
  46344. }
  46345. if (this._shouldUseAlphaFromAlbedoTexture()) {
  46346. defines.ALPHAFROMALBEDO = true;
  46347. }
  46348. else {
  46349. defines.ALPHAFROMALBEDO = false;
  46350. }
  46351. }
  46352. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  46353. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  46354. defines.USEPHYSICALLIGHTFALLOFF = false;
  46355. defines.USEGLTFLIGHTFALLOFF = false;
  46356. }
  46357. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  46358. defines.USEPHYSICALLIGHTFALLOFF = false;
  46359. defines.USEGLTFLIGHTFALLOFF = true;
  46360. }
  46361. else {
  46362. defines.USEPHYSICALLIGHTFALLOFF = true;
  46363. defines.USEGLTFLIGHTFALLOFF = false;
  46364. }
  46365. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  46366. if (!this.backFaceCulling && this._twoSidedLighting) {
  46367. defines.TWOSIDEDLIGHTING = true;
  46368. }
  46369. else {
  46370. defines.TWOSIDEDLIGHTING = false;
  46371. }
  46372. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  46373. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  46374. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  46375. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  46376. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  46377. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  46378. }
  46379. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46380. this._imageProcessingConfiguration.prepareDefines(defines);
  46381. }
  46382. defines.FORCENORMALFORWARD = this._forceNormalForward;
  46383. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  46384. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  46385. // Misc.
  46386. if (defines._areMiscDirty) {
  46387. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  46388. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  46389. }
  46390. // Values that need to be evaluated on every frame
  46391. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  46392. // Attribs
  46393. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  46394. };
  46395. /**
  46396. * Force shader compilation
  46397. */
  46398. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  46399. var _this = this;
  46400. var localOptions = __assign({ clipPlane: false }, options);
  46401. var defines = new PBRMaterialDefines();
  46402. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  46403. if (effect.isReady()) {
  46404. if (onCompiled) {
  46405. onCompiled(this);
  46406. }
  46407. }
  46408. else {
  46409. effect.onCompileObservable.add(function () {
  46410. if (onCompiled) {
  46411. onCompiled(_this);
  46412. }
  46413. });
  46414. }
  46415. };
  46416. /**
  46417. * Initializes the uniform buffer layout for the shader.
  46418. */
  46419. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  46420. // Order is important !
  46421. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  46422. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  46423. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  46424. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  46425. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  46426. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  46427. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  46428. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  46429. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  46430. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  46431. this._uniformBuffer.addUniform("vReflectionSize", 3);
  46432. this._uniformBuffer.addUniform("vBumpInfos", 3);
  46433. this._uniformBuffer.addUniform("albedoMatrix", 16);
  46434. this._uniformBuffer.addUniform("ambientMatrix", 16);
  46435. this._uniformBuffer.addUniform("opacityMatrix", 16);
  46436. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  46437. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  46438. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  46439. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  46440. this._uniformBuffer.addUniform("bumpMatrix", 16);
  46441. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  46442. this._uniformBuffer.addUniform("refractionMatrix", 16);
  46443. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  46444. this._uniformBuffer.addUniform("vReflectionColor", 3);
  46445. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  46446. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  46447. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  46448. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  46449. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  46450. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  46451. this._uniformBuffer.addUniform("pointSize", 1);
  46452. this._uniformBuffer.create();
  46453. };
  46454. /**
  46455. * Unbinds the textures.
  46456. */
  46457. PBRBaseMaterial.prototype.unbind = function () {
  46458. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46459. this._uniformBuffer.setTexture("reflectionSampler", null);
  46460. }
  46461. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46462. this._uniformBuffer.setTexture("refractionSampler", null);
  46463. }
  46464. _super.prototype.unbind.call(this);
  46465. };
  46466. /**
  46467. * Binds the submesh data.
  46468. * @param world - The world matrix.
  46469. * @param mesh - The BJS mesh.
  46470. * @param subMesh - A submesh of the BJS mesh.
  46471. */
  46472. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  46473. var scene = this.getScene();
  46474. var defines = subMesh._materialDefines;
  46475. if (!defines) {
  46476. return;
  46477. }
  46478. var effect = subMesh.effect;
  46479. if (!effect) {
  46480. return;
  46481. }
  46482. this._activeEffect = effect;
  46483. // Matrices
  46484. this.bindOnlyWorldMatrix(world);
  46485. // Normal Matrix
  46486. if (defines.OBJECTSPACE_NORMALMAP) {
  46487. world.toNormalMatrix(this._normalMatrix);
  46488. this.bindOnlyNormalMatrix(this._normalMatrix);
  46489. }
  46490. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  46491. // Bones
  46492. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  46493. var reflectionTexture = null;
  46494. if (mustRebind) {
  46495. this._uniformBuffer.bindToEffect(effect, "Material");
  46496. this.bindViewProjection(effect);
  46497. reflectionTexture = this._getReflectionTexture();
  46498. var refractionTexture = this._getRefractionTexture();
  46499. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  46500. // Texture uniforms
  46501. if (scene.texturesEnabled) {
  46502. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46503. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  46504. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  46505. }
  46506. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46507. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  46508. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  46509. }
  46510. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46511. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  46512. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  46513. }
  46514. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46515. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  46516. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  46517. if (reflectionTexture.boundingBoxSize) {
  46518. var cubeTexture = reflectionTexture;
  46519. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  46520. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  46521. }
  46522. var polynomials = reflectionTexture.sphericalPolynomial;
  46523. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  46524. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  46525. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  46526. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  46527. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  46528. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  46529. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  46530. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  46531. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  46532. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  46533. }
  46534. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  46535. }
  46536. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46537. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  46538. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  46539. }
  46540. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46541. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  46542. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  46543. }
  46544. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46545. if (this._metallicTexture) {
  46546. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  46547. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  46548. }
  46549. else if (this._reflectivityTexture) {
  46550. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  46551. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  46552. }
  46553. if (this._microSurfaceTexture) {
  46554. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  46555. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  46556. }
  46557. }
  46558. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46559. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  46560. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  46561. if (scene._mirroredCameraPosition) {
  46562. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  46563. }
  46564. else {
  46565. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  46566. }
  46567. }
  46568. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46569. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  46570. var depth = 1.0;
  46571. if (!refractionTexture.isCube) {
  46572. if (refractionTexture.depth) {
  46573. depth = refractionTexture.depth;
  46574. }
  46575. }
  46576. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  46577. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  46578. }
  46579. }
  46580. // Point size
  46581. if (this.pointsCloud) {
  46582. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  46583. }
  46584. // Colors
  46585. if (defines.METALLICWORKFLOW) {
  46586. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  46587. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  46588. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  46589. }
  46590. else {
  46591. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  46592. }
  46593. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  46594. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  46595. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  46596. // Misc
  46597. this._lightingInfos.x = this._directIntensity;
  46598. this._lightingInfos.y = this._emissiveIntensity;
  46599. this._lightingInfos.z = this._environmentIntensity;
  46600. this._lightingInfos.w = this._specularIntensity;
  46601. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  46602. }
  46603. // Textures
  46604. if (scene.texturesEnabled) {
  46605. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46606. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  46607. }
  46608. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46609. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  46610. }
  46611. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46612. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  46613. }
  46614. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46615. if (defines.LODBASEDMICROSFURACE) {
  46616. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  46617. }
  46618. else {
  46619. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  46620. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  46621. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  46622. }
  46623. }
  46624. if (defines.ENVIRONMENTBRDF) {
  46625. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  46626. }
  46627. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46628. if (defines.LODBASEDMICROSFURACE) {
  46629. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  46630. }
  46631. else {
  46632. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  46633. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  46634. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  46635. }
  46636. }
  46637. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46638. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  46639. }
  46640. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46641. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  46642. }
  46643. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46644. if (this._metallicTexture) {
  46645. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  46646. }
  46647. else if (this._reflectivityTexture) {
  46648. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  46649. }
  46650. if (this._microSurfaceTexture) {
  46651. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  46652. }
  46653. }
  46654. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46655. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  46656. }
  46657. }
  46658. // Clip plane
  46659. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  46660. // Colors
  46661. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  46662. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  46663. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  46664. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  46665. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46666. }
  46667. if (mustRebind || !this.isFrozen) {
  46668. // Lights
  46669. if (scene.lightsEnabled && !this._disableLighting) {
  46670. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  46671. }
  46672. // View
  46673. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  46674. this.bindView(effect);
  46675. }
  46676. // Fog
  46677. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  46678. // Morph targets
  46679. if (defines.NUM_MORPH_INFLUENCERS) {
  46680. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  46681. }
  46682. // image processing
  46683. this._imageProcessingConfiguration.bind(this._activeEffect);
  46684. // Log. depth
  46685. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  46686. }
  46687. this._uniformBuffer.update();
  46688. this._afterBind(mesh, this._activeEffect);
  46689. };
  46690. /**
  46691. * Returns the animatable textures.
  46692. * @returns - Array of animatable textures.
  46693. */
  46694. PBRBaseMaterial.prototype.getAnimatables = function () {
  46695. var results = [];
  46696. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  46697. results.push(this._albedoTexture);
  46698. }
  46699. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  46700. results.push(this._ambientTexture);
  46701. }
  46702. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  46703. results.push(this._opacityTexture);
  46704. }
  46705. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  46706. results.push(this._reflectionTexture);
  46707. }
  46708. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  46709. results.push(this._emissiveTexture);
  46710. }
  46711. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  46712. results.push(this._metallicTexture);
  46713. }
  46714. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  46715. results.push(this._reflectivityTexture);
  46716. }
  46717. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  46718. results.push(this._bumpTexture);
  46719. }
  46720. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  46721. results.push(this._lightmapTexture);
  46722. }
  46723. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46724. results.push(this._refractionTexture);
  46725. }
  46726. return results;
  46727. };
  46728. /**
  46729. * Returns the texture used for reflections.
  46730. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46731. */
  46732. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46733. if (this._reflectionTexture) {
  46734. return this._reflectionTexture;
  46735. }
  46736. return this.getScene().environmentTexture;
  46737. };
  46738. /**
  46739. * Returns the texture used for refraction or null if none is used.
  46740. * @returns - Refection texture if present. If no refraction texture and refraction
  46741. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46742. */
  46743. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46744. if (this._refractionTexture) {
  46745. return this._refractionTexture;
  46746. }
  46747. if (this._linkRefractionWithTransparency) {
  46748. return this.getScene().environmentTexture;
  46749. }
  46750. return null;
  46751. };
  46752. /**
  46753. * Disposes the resources of the material.
  46754. * @param forceDisposeEffect - Forces the disposal of effects.
  46755. * @param forceDisposeTextures - Forces the disposal of all textures.
  46756. */
  46757. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46758. if (forceDisposeTextures) {
  46759. if (this._albedoTexture) {
  46760. this._albedoTexture.dispose();
  46761. }
  46762. if (this._ambientTexture) {
  46763. this._ambientTexture.dispose();
  46764. }
  46765. if (this._opacityTexture) {
  46766. this._opacityTexture.dispose();
  46767. }
  46768. if (this._reflectionTexture) {
  46769. this._reflectionTexture.dispose();
  46770. }
  46771. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46772. this._environmentBRDFTexture.dispose();
  46773. }
  46774. if (this._emissiveTexture) {
  46775. this._emissiveTexture.dispose();
  46776. }
  46777. if (this._metallicTexture) {
  46778. this._metallicTexture.dispose();
  46779. }
  46780. if (this._reflectivityTexture) {
  46781. this._reflectivityTexture.dispose();
  46782. }
  46783. if (this._bumpTexture) {
  46784. this._bumpTexture.dispose();
  46785. }
  46786. if (this._lightmapTexture) {
  46787. this._lightmapTexture.dispose();
  46788. }
  46789. if (this._refractionTexture) {
  46790. this._refractionTexture.dispose();
  46791. }
  46792. }
  46793. this._renderTargets.dispose();
  46794. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46795. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46796. }
  46797. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46798. };
  46799. /**
  46800. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  46801. */
  46802. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  46803. /**
  46804. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  46805. * to enhance interoperability with other engines.
  46806. */
  46807. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  46808. /**
  46809. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  46810. * to enhance interoperability with other materials.
  46811. */
  46812. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  46813. /**
  46814. * Stores the reflectivity values based on metallic roughness workflow.
  46815. */
  46816. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46817. __decorate([
  46818. BABYLON.serializeAsImageProcessingConfiguration()
  46819. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46820. __decorate([
  46821. BABYLON.serialize()
  46822. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46823. __decorate([
  46824. BABYLON.serialize()
  46825. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46826. return PBRBaseMaterial;
  46827. }(BABYLON.PushMaterial));
  46828. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46829. })(BABYLON || (BABYLON = {}));
  46830. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46831. var BABYLON;
  46832. (function (BABYLON) {
  46833. /**
  46834. * The Physically based simple base material of BJS.
  46835. *
  46836. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46837. * It is used as the base class for both the specGloss and metalRough conventions.
  46838. */
  46839. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46840. __extends(PBRBaseSimpleMaterial, _super);
  46841. /**
  46842. * Instantiates a new PBRMaterial instance.
  46843. *
  46844. * @param name The material name
  46845. * @param scene The scene the material will be use in.
  46846. */
  46847. function PBRBaseSimpleMaterial(name, scene) {
  46848. var _this = _super.call(this, name, scene) || this;
  46849. /**
  46850. * Number of Simultaneous lights allowed on the material.
  46851. */
  46852. _this.maxSimultaneousLights = 4;
  46853. /**
  46854. * If sets to true, disables all the lights affecting the material.
  46855. */
  46856. _this.disableLighting = false;
  46857. /**
  46858. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46859. */
  46860. _this.invertNormalMapX = false;
  46861. /**
  46862. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46863. */
  46864. _this.invertNormalMapY = false;
  46865. /**
  46866. * Emissivie color used to self-illuminate the model.
  46867. */
  46868. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46869. /**
  46870. * Occlusion Channel Strenght.
  46871. */
  46872. _this.occlusionStrength = 1.0;
  46873. /**
  46874. * If true, the light map contains occlusion information instead of lighting info.
  46875. */
  46876. _this.useLightmapAsShadowmap = false;
  46877. _this._useAlphaFromAlbedoTexture = true;
  46878. _this._useAmbientInGrayScale = true;
  46879. return _this;
  46880. }
  46881. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46882. /**
  46883. * Gets the current double sided mode.
  46884. */
  46885. get: function () {
  46886. return this._twoSidedLighting;
  46887. },
  46888. /**
  46889. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46890. */
  46891. set: function (value) {
  46892. if (this._twoSidedLighting === value) {
  46893. return;
  46894. }
  46895. this._twoSidedLighting = value;
  46896. this.backFaceCulling = !value;
  46897. this._markAllSubMeshesAsTexturesDirty();
  46898. },
  46899. enumerable: true,
  46900. configurable: true
  46901. });
  46902. /**
  46903. * Return the active textures of the material.
  46904. */
  46905. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46906. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46907. if (this.environmentTexture) {
  46908. activeTextures.push(this.environmentTexture);
  46909. }
  46910. if (this.normalTexture) {
  46911. activeTextures.push(this.normalTexture);
  46912. }
  46913. if (this.emissiveTexture) {
  46914. activeTextures.push(this.emissiveTexture);
  46915. }
  46916. if (this.occlusionTexture) {
  46917. activeTextures.push(this.occlusionTexture);
  46918. }
  46919. if (this.lightmapTexture) {
  46920. activeTextures.push(this.lightmapTexture);
  46921. }
  46922. return activeTextures;
  46923. };
  46924. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46925. if (_super.prototype.hasTexture.call(this, texture)) {
  46926. return true;
  46927. }
  46928. if (this.lightmapTexture === texture) {
  46929. return true;
  46930. }
  46931. return false;
  46932. };
  46933. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46934. return "PBRBaseSimpleMaterial";
  46935. };
  46936. __decorate([
  46937. BABYLON.serialize(),
  46938. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46939. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46940. __decorate([
  46941. BABYLON.serialize(),
  46942. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46943. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46944. __decorate([
  46945. BABYLON.serializeAsTexture(),
  46946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46947. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46948. __decorate([
  46949. BABYLON.serialize(),
  46950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46951. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46952. __decorate([
  46953. BABYLON.serialize(),
  46954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46955. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46956. __decorate([
  46957. BABYLON.serializeAsTexture(),
  46958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46959. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46960. __decorate([
  46961. BABYLON.serializeAsColor3("emissive"),
  46962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46963. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46964. __decorate([
  46965. BABYLON.serializeAsTexture(),
  46966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46967. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46968. __decorate([
  46969. BABYLON.serialize(),
  46970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46971. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46972. __decorate([
  46973. BABYLON.serializeAsTexture(),
  46974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46975. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46976. __decorate([
  46977. BABYLON.serialize(),
  46978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46979. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46980. __decorate([
  46981. BABYLON.serialize()
  46982. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46983. __decorate([
  46984. BABYLON.serializeAsTexture(),
  46985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46986. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46987. __decorate([
  46988. BABYLON.serialize(),
  46989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46990. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46991. return PBRBaseSimpleMaterial;
  46992. }(BABYLON.PBRBaseMaterial));
  46993. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46994. })(BABYLON || (BABYLON = {}));
  46995. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46996. var BABYLON;
  46997. (function (BABYLON) {
  46998. /**
  46999. * The Physically based material of BJS.
  47000. *
  47001. * This offers the main features of a standard PBR material.
  47002. * For more information, please refer to the documentation :
  47003. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  47004. */
  47005. var PBRMaterial = /** @class */ (function (_super) {
  47006. __extends(PBRMaterial, _super);
  47007. /**
  47008. * Instantiates a new PBRMaterial instance.
  47009. *
  47010. * @param name The material name
  47011. * @param scene The scene the material will be use in.
  47012. */
  47013. function PBRMaterial(name, scene) {
  47014. var _this = _super.call(this, name, scene) || this;
  47015. /**
  47016. * Intensity of the direct lights e.g. the four lights available in your scene.
  47017. * This impacts both the direct diffuse and specular highlights.
  47018. */
  47019. _this.directIntensity = 1.0;
  47020. /**
  47021. * Intensity of the emissive part of the material.
  47022. * This helps controlling the emissive effect without modifying the emissive color.
  47023. */
  47024. _this.emissiveIntensity = 1.0;
  47025. /**
  47026. * Intensity of the environment e.g. how much the environment will light the object
  47027. * either through harmonics for rough material or through the refelction for shiny ones.
  47028. */
  47029. _this.environmentIntensity = 1.0;
  47030. /**
  47031. * This is a special control allowing the reduction of the specular highlights coming from the
  47032. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  47033. */
  47034. _this.specularIntensity = 1.0;
  47035. /**
  47036. * Debug Control allowing disabling the bump map on this material.
  47037. */
  47038. _this.disableBumpMap = false;
  47039. /**
  47040. * AKA Occlusion Texture Intensity in other nomenclature.
  47041. */
  47042. _this.ambientTextureStrength = 1.0;
  47043. /**
  47044. * Defines how much the AO map is occluding the analytical lights (point spot...).
  47045. * 1 means it completely occludes it
  47046. * 0 mean it has no impact
  47047. */
  47048. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  47049. /**
  47050. * The color of a material in ambient lighting.
  47051. */
  47052. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  47053. /**
  47054. * AKA Diffuse Color in other nomenclature.
  47055. */
  47056. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  47057. /**
  47058. * AKA Specular Color in other nomenclature.
  47059. */
  47060. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  47061. /**
  47062. * The color reflected from the material.
  47063. */
  47064. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  47065. /**
  47066. * The color emitted from the material.
  47067. */
  47068. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  47069. /**
  47070. * AKA Glossiness in other nomenclature.
  47071. */
  47072. _this.microSurface = 1.0;
  47073. /**
  47074. * source material index of refraction (IOR)' / 'destination material IOR.
  47075. */
  47076. _this.indexOfRefraction = 0.66;
  47077. /**
  47078. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  47079. */
  47080. _this.invertRefractionY = false;
  47081. /**
  47082. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  47083. * Materials half opaque for instance using refraction could benefit from this control.
  47084. */
  47085. _this.linkRefractionWithTransparency = false;
  47086. /**
  47087. * If true, the light map contains occlusion information instead of lighting info.
  47088. */
  47089. _this.useLightmapAsShadowmap = false;
  47090. /**
  47091. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  47092. */
  47093. _this.useAlphaFromAlbedoTexture = false;
  47094. /**
  47095. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  47096. */
  47097. _this.forceAlphaTest = false;
  47098. /**
  47099. * Defines the alpha limits in alpha test mode.
  47100. */
  47101. _this.alphaCutOff = 0.4;
  47102. /**
  47103. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  47104. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  47105. */
  47106. _this.useSpecularOverAlpha = true;
  47107. /**
  47108. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  47109. */
  47110. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  47111. /**
  47112. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  47113. */
  47114. _this.useRoughnessFromMetallicTextureAlpha = true;
  47115. /**
  47116. * Specifies if the metallic texture contains the roughness information in its green channel.
  47117. */
  47118. _this.useRoughnessFromMetallicTextureGreen = false;
  47119. /**
  47120. * Specifies if the metallic texture contains the metallness information in its blue channel.
  47121. */
  47122. _this.useMetallnessFromMetallicTextureBlue = false;
  47123. /**
  47124. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  47125. */
  47126. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  47127. /**
  47128. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  47129. */
  47130. _this.useAmbientInGrayScale = false;
  47131. /**
  47132. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  47133. * The material will try to infer what glossiness each pixel should be.
  47134. */
  47135. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  47136. /**
  47137. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  47138. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  47139. */
  47140. _this.useRadianceOverAlpha = true;
  47141. /**
  47142. * Allows using an object space normal map (instead of tangent space).
  47143. */
  47144. _this.useObjectSpaceNormalMap = false;
  47145. /**
  47146. * Allows using the bump map in parallax mode.
  47147. */
  47148. _this.useParallax = false;
  47149. /**
  47150. * Allows using the bump map in parallax occlusion mode.
  47151. */
  47152. _this.useParallaxOcclusion = false;
  47153. /**
  47154. * Controls the scale bias of the parallax mode.
  47155. */
  47156. _this.parallaxScaleBias = 0.05;
  47157. /**
  47158. * If sets to true, disables all the lights affecting the material.
  47159. */
  47160. _this.disableLighting = false;
  47161. /**
  47162. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  47163. */
  47164. _this.forceIrradianceInFragment = false;
  47165. /**
  47166. * Number of Simultaneous lights allowed on the material.
  47167. */
  47168. _this.maxSimultaneousLights = 4;
  47169. /**
  47170. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  47171. */
  47172. _this.invertNormalMapX = false;
  47173. /**
  47174. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  47175. */
  47176. _this.invertNormalMapY = false;
  47177. /**
  47178. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  47179. */
  47180. _this.twoSidedLighting = false;
  47181. /**
  47182. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47183. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  47184. */
  47185. _this.useAlphaFresnel = false;
  47186. /**
  47187. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47188. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  47189. */
  47190. _this.useLinearAlphaFresnel = false;
  47191. /**
  47192. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47193. * And/Or occlude the blended part.
  47194. */
  47195. _this.environmentBRDFTexture = null;
  47196. /**
  47197. * Force normal to face away from face.
  47198. */
  47199. _this.forceNormalForward = false;
  47200. /**
  47201. * Enables specular anti aliasing in the PBR shader.
  47202. * It will both interacts on the Geometry for analytical and IBL lighting.
  47203. * It also prefilter the roughness map based on the bump values.
  47204. */
  47205. _this.enableSpecularAntiAliasing = false;
  47206. /**
  47207. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  47208. * makes the reflect vector face the model (under horizon).
  47209. */
  47210. _this.useHorizonOcclusion = true;
  47211. /**
  47212. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  47213. * too much the area relying on ambient texture to define their ambient occlusion.
  47214. */
  47215. _this.useRadianceOcclusion = true;
  47216. /**
  47217. * If set to true, no lighting calculations will be applied.
  47218. */
  47219. _this.unlit = false;
  47220. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  47221. return _this;
  47222. }
  47223. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  47224. /**
  47225. * BJS is using an harcoded light falloff based on a manually sets up range.
  47226. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  47227. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  47228. */
  47229. get: function () {
  47230. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  47231. },
  47232. /**
  47233. * BJS is using an harcoded light falloff based on a manually sets up range.
  47234. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  47235. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  47236. */
  47237. set: function (value) {
  47238. if (value !== this.usePhysicalLightFalloff) {
  47239. // Ensure the effect will be rebuilt.
  47240. this._markAllSubMeshesAsTexturesDirty();
  47241. if (value) {
  47242. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  47243. }
  47244. else {
  47245. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47246. }
  47247. }
  47248. },
  47249. enumerable: true,
  47250. configurable: true
  47251. });
  47252. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  47253. /**
  47254. * In order to support the falloff compatibility with gltf, a special mode has been added
  47255. * to reproduce the gltf light falloff.
  47256. */
  47257. get: function () {
  47258. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47259. },
  47260. /**
  47261. * In order to support the falloff compatibility with gltf, a special mode has been added
  47262. * to reproduce the gltf light falloff.
  47263. */
  47264. set: function (value) {
  47265. if (value !== this.useGLTFLightFalloff) {
  47266. // Ensure the effect will be rebuilt.
  47267. this._markAllSubMeshesAsTexturesDirty();
  47268. if (value) {
  47269. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47270. }
  47271. else {
  47272. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47273. }
  47274. }
  47275. },
  47276. enumerable: true,
  47277. configurable: true
  47278. });
  47279. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  47280. /**
  47281. * Gets the image processing configuration used either in this material.
  47282. */
  47283. get: function () {
  47284. return this._imageProcessingConfiguration;
  47285. },
  47286. /**
  47287. * Sets the Default image processing configuration used either in the this material.
  47288. *
  47289. * If sets to null, the scene one is in use.
  47290. */
  47291. set: function (value) {
  47292. this._attachImageProcessingConfiguration(value);
  47293. // Ensure the effect will be rebuilt.
  47294. this._markAllSubMeshesAsTexturesDirty();
  47295. },
  47296. enumerable: true,
  47297. configurable: true
  47298. });
  47299. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  47300. /**
  47301. * Gets wether the color curves effect is enabled.
  47302. */
  47303. get: function () {
  47304. return this.imageProcessingConfiguration.colorCurvesEnabled;
  47305. },
  47306. /**
  47307. * Sets wether the color curves effect is enabled.
  47308. */
  47309. set: function (value) {
  47310. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  47311. },
  47312. enumerable: true,
  47313. configurable: true
  47314. });
  47315. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  47316. /**
  47317. * Gets wether the color grading effect is enabled.
  47318. */
  47319. get: function () {
  47320. return this.imageProcessingConfiguration.colorGradingEnabled;
  47321. },
  47322. /**
  47323. * Gets wether the color grading effect is enabled.
  47324. */
  47325. set: function (value) {
  47326. this.imageProcessingConfiguration.colorGradingEnabled = value;
  47327. },
  47328. enumerable: true,
  47329. configurable: true
  47330. });
  47331. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  47332. /**
  47333. * Gets wether tonemapping is enabled or not.
  47334. */
  47335. get: function () {
  47336. return this._imageProcessingConfiguration.toneMappingEnabled;
  47337. },
  47338. /**
  47339. * Sets wether tonemapping is enabled or not
  47340. */
  47341. set: function (value) {
  47342. this._imageProcessingConfiguration.toneMappingEnabled = value;
  47343. },
  47344. enumerable: true,
  47345. configurable: true
  47346. });
  47347. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  47348. /**
  47349. * The camera exposure used on this material.
  47350. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47351. * This corresponds to a photographic exposure.
  47352. */
  47353. get: function () {
  47354. return this._imageProcessingConfiguration.exposure;
  47355. },
  47356. /**
  47357. * The camera exposure used on this material.
  47358. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47359. * This corresponds to a photographic exposure.
  47360. */
  47361. set: function (value) {
  47362. this._imageProcessingConfiguration.exposure = value;
  47363. },
  47364. enumerable: true,
  47365. configurable: true
  47366. });
  47367. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  47368. /**
  47369. * Gets The camera contrast used on this material.
  47370. */
  47371. get: function () {
  47372. return this._imageProcessingConfiguration.contrast;
  47373. },
  47374. /**
  47375. * Sets The camera contrast used on this material.
  47376. */
  47377. set: function (value) {
  47378. this._imageProcessingConfiguration.contrast = value;
  47379. },
  47380. enumerable: true,
  47381. configurable: true
  47382. });
  47383. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  47384. /**
  47385. * Gets the Color Grading 2D Lookup Texture.
  47386. */
  47387. get: function () {
  47388. return this._imageProcessingConfiguration.colorGradingTexture;
  47389. },
  47390. /**
  47391. * Sets the Color Grading 2D Lookup Texture.
  47392. */
  47393. set: function (value) {
  47394. this._imageProcessingConfiguration.colorGradingTexture = value;
  47395. },
  47396. enumerable: true,
  47397. configurable: true
  47398. });
  47399. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  47400. /**
  47401. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47402. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47403. * 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;
  47404. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47405. */
  47406. get: function () {
  47407. return this._imageProcessingConfiguration.colorCurves;
  47408. },
  47409. /**
  47410. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47411. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47412. * 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;
  47413. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47414. */
  47415. set: function (value) {
  47416. this._imageProcessingConfiguration.colorCurves = value;
  47417. },
  47418. enumerable: true,
  47419. configurable: true
  47420. });
  47421. /**
  47422. * Returns the name of this material class.
  47423. */
  47424. PBRMaterial.prototype.getClassName = function () {
  47425. return "PBRMaterial";
  47426. };
  47427. /**
  47428. * Returns an array of the actively used textures.
  47429. * @returns - Array of BaseTextures
  47430. */
  47431. PBRMaterial.prototype.getActiveTextures = function () {
  47432. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47433. if (this._albedoTexture) {
  47434. activeTextures.push(this._albedoTexture);
  47435. }
  47436. if (this._ambientTexture) {
  47437. activeTextures.push(this._ambientTexture);
  47438. }
  47439. if (this._opacityTexture) {
  47440. activeTextures.push(this._opacityTexture);
  47441. }
  47442. if (this._reflectionTexture) {
  47443. activeTextures.push(this._reflectionTexture);
  47444. }
  47445. if (this._emissiveTexture) {
  47446. activeTextures.push(this._emissiveTexture);
  47447. }
  47448. if (this._reflectivityTexture) {
  47449. activeTextures.push(this._reflectivityTexture);
  47450. }
  47451. if (this._metallicTexture) {
  47452. activeTextures.push(this._metallicTexture);
  47453. }
  47454. if (this._microSurfaceTexture) {
  47455. activeTextures.push(this._microSurfaceTexture);
  47456. }
  47457. if (this._bumpTexture) {
  47458. activeTextures.push(this._bumpTexture);
  47459. }
  47460. if (this._lightmapTexture) {
  47461. activeTextures.push(this._lightmapTexture);
  47462. }
  47463. if (this._refractionTexture) {
  47464. activeTextures.push(this._refractionTexture);
  47465. }
  47466. return activeTextures;
  47467. };
  47468. /**
  47469. * Checks to see if a texture is used in the material.
  47470. * @param texture - Base texture to use.
  47471. * @returns - Boolean specifying if a texture is used in the material.
  47472. */
  47473. PBRMaterial.prototype.hasTexture = function (texture) {
  47474. if (_super.prototype.hasTexture.call(this, texture)) {
  47475. return true;
  47476. }
  47477. if (this._albedoTexture === texture) {
  47478. return true;
  47479. }
  47480. if (this._ambientTexture === texture) {
  47481. return true;
  47482. }
  47483. if (this._opacityTexture === texture) {
  47484. return true;
  47485. }
  47486. if (this._reflectionTexture === texture) {
  47487. return true;
  47488. }
  47489. if (this._reflectivityTexture === texture) {
  47490. return true;
  47491. }
  47492. if (this._metallicTexture === texture) {
  47493. return true;
  47494. }
  47495. if (this._microSurfaceTexture === texture) {
  47496. return true;
  47497. }
  47498. if (this._bumpTexture === texture) {
  47499. return true;
  47500. }
  47501. if (this._lightmapTexture === texture) {
  47502. return true;
  47503. }
  47504. if (this._refractionTexture === texture) {
  47505. return true;
  47506. }
  47507. return false;
  47508. };
  47509. /**
  47510. * Makes a duplicate of the current material.
  47511. * @param name - name to use for the new material.
  47512. */
  47513. PBRMaterial.prototype.clone = function (name) {
  47514. var _this = this;
  47515. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  47516. clone.id = name;
  47517. clone.name = name;
  47518. return clone;
  47519. };
  47520. /**
  47521. * Serializes this PBR Material.
  47522. * @returns - An object with the serialized material.
  47523. */
  47524. PBRMaterial.prototype.serialize = function () {
  47525. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47526. serializationObject.customType = "BABYLON.PBRMaterial";
  47527. return serializationObject;
  47528. };
  47529. // Statics
  47530. /**
  47531. * Parses a PBR Material from a serialized object.
  47532. * @param source - Serialized object.
  47533. * @param scene - BJS scene instance.
  47534. * @param rootUrl - url for the scene object
  47535. * @returns - PBRMaterial
  47536. */
  47537. PBRMaterial.Parse = function (source, scene, rootUrl) {
  47538. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  47539. };
  47540. /**
  47541. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  47542. */
  47543. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  47544. /**
  47545. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  47546. */
  47547. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  47548. /**
  47549. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47550. */
  47551. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  47552. /**
  47553. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47554. * They are also discarded below the alpha cutoff threshold to improve performances.
  47555. */
  47556. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  47557. /**
  47558. * Defines the default value of how much AO map is occluding the analytical lights
  47559. * (point spot...).
  47560. */
  47561. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  47562. __decorate([
  47563. BABYLON.serialize(),
  47564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47565. ], PBRMaterial.prototype, "directIntensity", void 0);
  47566. __decorate([
  47567. BABYLON.serialize(),
  47568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47569. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  47570. __decorate([
  47571. BABYLON.serialize(),
  47572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47573. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  47574. __decorate([
  47575. BABYLON.serialize(),
  47576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47577. ], PBRMaterial.prototype, "specularIntensity", void 0);
  47578. __decorate([
  47579. BABYLON.serialize(),
  47580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47581. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  47582. __decorate([
  47583. BABYLON.serializeAsTexture(),
  47584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47585. ], PBRMaterial.prototype, "albedoTexture", void 0);
  47586. __decorate([
  47587. BABYLON.serializeAsTexture(),
  47588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47589. ], PBRMaterial.prototype, "ambientTexture", void 0);
  47590. __decorate([
  47591. BABYLON.serialize(),
  47592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47593. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  47594. __decorate([
  47595. BABYLON.serialize(),
  47596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47597. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  47598. __decorate([
  47599. BABYLON.serializeAsTexture(),
  47600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47601. ], PBRMaterial.prototype, "opacityTexture", void 0);
  47602. __decorate([
  47603. BABYLON.serializeAsTexture(),
  47604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47605. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  47606. __decorate([
  47607. BABYLON.serializeAsTexture(),
  47608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47609. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  47610. __decorate([
  47611. BABYLON.serializeAsTexture(),
  47612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47613. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  47614. __decorate([
  47615. BABYLON.serializeAsTexture(),
  47616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47617. ], PBRMaterial.prototype, "metallicTexture", void 0);
  47618. __decorate([
  47619. BABYLON.serialize(),
  47620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47621. ], PBRMaterial.prototype, "metallic", void 0);
  47622. __decorate([
  47623. BABYLON.serialize(),
  47624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47625. ], PBRMaterial.prototype, "roughness", void 0);
  47626. __decorate([
  47627. BABYLON.serializeAsTexture(),
  47628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47629. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  47630. __decorate([
  47631. BABYLON.serializeAsTexture(),
  47632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47633. ], PBRMaterial.prototype, "bumpTexture", void 0);
  47634. __decorate([
  47635. BABYLON.serializeAsTexture(),
  47636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47637. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  47638. __decorate([
  47639. BABYLON.serializeAsTexture(),
  47640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47641. ], PBRMaterial.prototype, "refractionTexture", void 0);
  47642. __decorate([
  47643. BABYLON.serializeAsColor3("ambient"),
  47644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47645. ], PBRMaterial.prototype, "ambientColor", void 0);
  47646. __decorate([
  47647. BABYLON.serializeAsColor3("albedo"),
  47648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47649. ], PBRMaterial.prototype, "albedoColor", void 0);
  47650. __decorate([
  47651. BABYLON.serializeAsColor3("reflectivity"),
  47652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47653. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  47654. __decorate([
  47655. BABYLON.serializeAsColor3("reflection"),
  47656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47657. ], PBRMaterial.prototype, "reflectionColor", void 0);
  47658. __decorate([
  47659. BABYLON.serializeAsColor3("emissive"),
  47660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47661. ], PBRMaterial.prototype, "emissiveColor", void 0);
  47662. __decorate([
  47663. BABYLON.serialize(),
  47664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47665. ], PBRMaterial.prototype, "microSurface", void 0);
  47666. __decorate([
  47667. BABYLON.serialize(),
  47668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47669. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  47670. __decorate([
  47671. BABYLON.serialize(),
  47672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47673. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  47674. __decorate([
  47675. BABYLON.serialize(),
  47676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47677. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  47678. __decorate([
  47679. BABYLON.serialize(),
  47680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47681. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47682. __decorate([
  47683. BABYLON.serialize(),
  47684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47685. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  47686. __decorate([
  47687. BABYLON.serialize(),
  47688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47689. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  47690. __decorate([
  47691. BABYLON.serialize(),
  47692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47693. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  47694. __decorate([
  47695. BABYLON.serialize(),
  47696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47697. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  47698. __decorate([
  47699. BABYLON.serialize(),
  47700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47701. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  47702. __decorate([
  47703. BABYLON.serialize(),
  47704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47705. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  47706. __decorate([
  47707. BABYLON.serialize(),
  47708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47709. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  47710. __decorate([
  47711. BABYLON.serialize(),
  47712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47713. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  47714. __decorate([
  47715. BABYLON.serialize(),
  47716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47717. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  47718. __decorate([
  47719. BABYLON.serialize(),
  47720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47721. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  47722. __decorate([
  47723. BABYLON.serialize(),
  47724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47725. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  47726. __decorate([
  47727. BABYLON.serialize()
  47728. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  47729. __decorate([
  47730. BABYLON.serialize()
  47731. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  47732. __decorate([
  47733. BABYLON.serialize(),
  47734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47735. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  47736. __decorate([
  47737. BABYLON.serialize(),
  47738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47739. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  47740. __decorate([
  47741. BABYLON.serialize(),
  47742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47743. ], PBRMaterial.prototype, "useParallax", void 0);
  47744. __decorate([
  47745. BABYLON.serialize(),
  47746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47747. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  47748. __decorate([
  47749. BABYLON.serialize(),
  47750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47751. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  47752. __decorate([
  47753. BABYLON.serialize(),
  47754. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47755. ], PBRMaterial.prototype, "disableLighting", void 0);
  47756. __decorate([
  47757. BABYLON.serialize(),
  47758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47759. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  47760. __decorate([
  47761. BABYLON.serialize(),
  47762. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47763. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  47764. __decorate([
  47765. BABYLON.serialize(),
  47766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47767. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  47768. __decorate([
  47769. BABYLON.serialize(),
  47770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47771. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47772. __decorate([
  47773. BABYLON.serialize(),
  47774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47775. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47776. __decorate([
  47777. BABYLON.serialize(),
  47778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47779. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47780. __decorate([
  47781. BABYLON.serialize(),
  47782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47783. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47784. __decorate([
  47785. BABYLON.serializeAsTexture(),
  47786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47787. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47788. __decorate([
  47789. BABYLON.serialize(),
  47790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47791. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47792. __decorate([
  47793. BABYLON.serialize(),
  47794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47795. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47796. __decorate([
  47797. BABYLON.serialize(),
  47798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47799. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47800. __decorate([
  47801. BABYLON.serialize(),
  47802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47803. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47804. __decorate([
  47805. BABYLON.serialize(),
  47806. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47807. ], PBRMaterial.prototype, "unlit", void 0);
  47808. return PBRMaterial;
  47809. }(BABYLON.PBRBaseMaterial));
  47810. BABYLON.PBRMaterial = PBRMaterial;
  47811. })(BABYLON || (BABYLON = {}));
  47812. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47813. var BABYLON;
  47814. (function (BABYLON) {
  47815. /**
  47816. * The PBR material of BJS following the metal roughness convention.
  47817. *
  47818. * This fits to the PBR convention in the GLTF definition:
  47819. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47820. */
  47821. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47822. __extends(PBRMetallicRoughnessMaterial, _super);
  47823. /**
  47824. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47825. *
  47826. * @param name The material name
  47827. * @param scene The scene the material will be use in.
  47828. */
  47829. function PBRMetallicRoughnessMaterial(name, scene) {
  47830. var _this = _super.call(this, name, scene) || this;
  47831. _this._useRoughnessFromMetallicTextureAlpha = false;
  47832. _this._useRoughnessFromMetallicTextureGreen = true;
  47833. _this._useMetallnessFromMetallicTextureBlue = true;
  47834. _this.metallic = 1.0;
  47835. _this.roughness = 1.0;
  47836. return _this;
  47837. }
  47838. /**
  47839. * Return the currrent class name of the material.
  47840. */
  47841. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47842. return "PBRMetallicRoughnessMaterial";
  47843. };
  47844. /**
  47845. * Return the active textures of the material.
  47846. */
  47847. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47848. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47849. if (this.baseTexture) {
  47850. activeTextures.push(this.baseTexture);
  47851. }
  47852. if (this.metallicRoughnessTexture) {
  47853. activeTextures.push(this.metallicRoughnessTexture);
  47854. }
  47855. return activeTextures;
  47856. };
  47857. /**
  47858. * Checks to see if a texture is used in the material.
  47859. * @param texture - Base texture to use.
  47860. * @returns - Boolean specifying if a texture is used in the material.
  47861. */
  47862. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47863. if (_super.prototype.hasTexture.call(this, texture)) {
  47864. return true;
  47865. }
  47866. if (this.baseTexture === texture) {
  47867. return true;
  47868. }
  47869. if (this.metallicRoughnessTexture === texture) {
  47870. return true;
  47871. }
  47872. return false;
  47873. };
  47874. /**
  47875. * Makes a duplicate of the current material.
  47876. * @param name - name to use for the new material.
  47877. */
  47878. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47879. var _this = this;
  47880. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47881. clone.id = name;
  47882. clone.name = name;
  47883. return clone;
  47884. };
  47885. /**
  47886. * Serialize the material to a parsable JSON object.
  47887. */
  47888. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47889. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47890. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47891. return serializationObject;
  47892. };
  47893. /**
  47894. * Parses a JSON object correponding to the serialize function.
  47895. */
  47896. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47897. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47898. };
  47899. __decorate([
  47900. BABYLON.serializeAsColor3(),
  47901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47902. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47903. __decorate([
  47904. BABYLON.serializeAsTexture(),
  47905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47906. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47907. __decorate([
  47908. BABYLON.serialize(),
  47909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47910. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47911. __decorate([
  47912. BABYLON.serialize(),
  47913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47914. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47915. __decorate([
  47916. BABYLON.serializeAsTexture(),
  47917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47918. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47919. return PBRMetallicRoughnessMaterial;
  47920. }(BABYLON.PBRBaseSimpleMaterial));
  47921. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47922. })(BABYLON || (BABYLON = {}));
  47923. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47924. var BABYLON;
  47925. (function (BABYLON) {
  47926. /**
  47927. * The PBR material of BJS following the specular glossiness convention.
  47928. *
  47929. * This fits to the PBR convention in the GLTF definition:
  47930. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47931. */
  47932. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47933. __extends(PBRSpecularGlossinessMaterial, _super);
  47934. /**
  47935. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47936. *
  47937. * @param name The material name
  47938. * @param scene The scene the material will be use in.
  47939. */
  47940. function PBRSpecularGlossinessMaterial(name, scene) {
  47941. var _this = _super.call(this, name, scene) || this;
  47942. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47943. return _this;
  47944. }
  47945. /**
  47946. * Return the currrent class name of the material.
  47947. */
  47948. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47949. return "PBRSpecularGlossinessMaterial";
  47950. };
  47951. /**
  47952. * Return the active textures of the material.
  47953. */
  47954. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47955. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47956. if (this.diffuseTexture) {
  47957. activeTextures.push(this.diffuseTexture);
  47958. }
  47959. if (this.specularGlossinessTexture) {
  47960. activeTextures.push(this.specularGlossinessTexture);
  47961. }
  47962. return activeTextures;
  47963. };
  47964. /**
  47965. * Checks to see if a texture is used in the material.
  47966. * @param texture - Base texture to use.
  47967. * @returns - Boolean specifying if a texture is used in the material.
  47968. */
  47969. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47970. if (_super.prototype.hasTexture.call(this, texture)) {
  47971. return true;
  47972. }
  47973. if (this.diffuseTexture === texture) {
  47974. return true;
  47975. }
  47976. if (this.specularGlossinessTexture === texture) {
  47977. return true;
  47978. }
  47979. return false;
  47980. };
  47981. /**
  47982. * Makes a duplicate of the current material.
  47983. * @param name - name to use for the new material.
  47984. */
  47985. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47986. var _this = this;
  47987. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47988. clone.id = name;
  47989. clone.name = name;
  47990. return clone;
  47991. };
  47992. /**
  47993. * Serialize the material to a parsable JSON object.
  47994. */
  47995. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47996. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47997. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47998. return serializationObject;
  47999. };
  48000. /**
  48001. * Parses a JSON object correponding to the serialize function.
  48002. */
  48003. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  48004. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  48005. };
  48006. __decorate([
  48007. BABYLON.serializeAsColor3("diffuse"),
  48008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  48009. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  48010. __decorate([
  48011. BABYLON.serializeAsTexture(),
  48012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  48013. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  48014. __decorate([
  48015. BABYLON.serializeAsColor3("specular"),
  48016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  48017. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  48018. __decorate([
  48019. BABYLON.serialize(),
  48020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  48021. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  48022. __decorate([
  48023. BABYLON.serializeAsTexture(),
  48024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  48025. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  48026. return PBRSpecularGlossinessMaterial;
  48027. }(BABYLON.PBRBaseSimpleMaterial));
  48028. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  48029. })(BABYLON || (BABYLON = {}));
  48030. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  48031. var BABYLON;
  48032. (function (BABYLON) {
  48033. /**
  48034. * @ignore
  48035. * This is a list of all the different input types that are available in the application.
  48036. * Fo instance: ArcRotateCameraGamepadInput...
  48037. */
  48038. BABYLON.CameraInputTypes = {};
  48039. /**
  48040. * This represents the input manager used within a camera.
  48041. * It helps dealing with all the different kind of input attached to a camera.
  48042. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48043. */
  48044. var CameraInputsManager = /** @class */ (function () {
  48045. /**
  48046. * Instantiate a new Camera Input Manager.
  48047. * @param camera Defines the camera the input manager blongs to
  48048. */
  48049. function CameraInputsManager(camera) {
  48050. this.attached = {};
  48051. this.camera = camera;
  48052. this.checkInputs = function () { };
  48053. }
  48054. /**
  48055. * Add an input method to a camera
  48056. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48057. * @param input camera input method
  48058. */
  48059. CameraInputsManager.prototype.add = function (input) {
  48060. var type = input.getSimpleName();
  48061. if (this.attached[type]) {
  48062. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  48063. return;
  48064. }
  48065. this.attached[type] = input;
  48066. input.camera = this.camera;
  48067. //for checkInputs, we are dynamically creating a function
  48068. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  48069. if (input.checkInputs) {
  48070. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  48071. }
  48072. if (this.attachedElement) {
  48073. input.attachControl(this.attachedElement);
  48074. }
  48075. };
  48076. /**
  48077. * Remove a specific input method from a camera
  48078. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  48079. * @param inputToRemove camera input method
  48080. */
  48081. CameraInputsManager.prototype.remove = function (inputToRemove) {
  48082. for (var cam in this.attached) {
  48083. var input = this.attached[cam];
  48084. if (input === inputToRemove) {
  48085. input.detachControl(this.attachedElement);
  48086. input.camera = null;
  48087. delete this.attached[cam];
  48088. this.rebuildInputCheck();
  48089. }
  48090. }
  48091. };
  48092. /**
  48093. * Remove a specific input type from a camera
  48094. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  48095. * @param inputType the type of the input to remove
  48096. */
  48097. CameraInputsManager.prototype.removeByType = function (inputType) {
  48098. for (var cam in this.attached) {
  48099. var input = this.attached[cam];
  48100. if (input.getClassName() === inputType) {
  48101. input.detachControl(this.attachedElement);
  48102. input.camera = null;
  48103. delete this.attached[cam];
  48104. this.rebuildInputCheck();
  48105. }
  48106. }
  48107. };
  48108. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  48109. var current = this.checkInputs;
  48110. return function () {
  48111. current();
  48112. fn();
  48113. };
  48114. };
  48115. /**
  48116. * Attach the input controls to the currently attached dom element to listen the events from.
  48117. * @param input Defines the input to attach
  48118. */
  48119. CameraInputsManager.prototype.attachInput = function (input) {
  48120. if (this.attachedElement) {
  48121. input.attachControl(this.attachedElement, this.noPreventDefault);
  48122. }
  48123. };
  48124. /**
  48125. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  48126. * @param element Defines the dom element to collect the events from
  48127. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48128. */
  48129. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  48130. if (noPreventDefault === void 0) { noPreventDefault = false; }
  48131. if (this.attachedElement) {
  48132. return;
  48133. }
  48134. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  48135. this.attachedElement = element;
  48136. this.noPreventDefault = noPreventDefault;
  48137. for (var cam in this.attached) {
  48138. this.attached[cam].attachControl(element, noPreventDefault);
  48139. }
  48140. };
  48141. /**
  48142. * Detach the current manager inputs controls from a specific dom element.
  48143. * @param element Defines the dom element to collect the events from
  48144. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  48145. */
  48146. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  48147. if (disconnect === void 0) { disconnect = false; }
  48148. if (this.attachedElement !== element) {
  48149. return;
  48150. }
  48151. for (var cam in this.attached) {
  48152. this.attached[cam].detachControl(element);
  48153. if (disconnect) {
  48154. this.attached[cam].camera = null;
  48155. }
  48156. }
  48157. this.attachedElement = null;
  48158. };
  48159. /**
  48160. * Rebuild the dynamic inputCheck function from the current list of
  48161. * defined inputs in the manager.
  48162. */
  48163. CameraInputsManager.prototype.rebuildInputCheck = function () {
  48164. this.checkInputs = function () { };
  48165. for (var cam in this.attached) {
  48166. var input = this.attached[cam];
  48167. if (input.checkInputs) {
  48168. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  48169. }
  48170. }
  48171. };
  48172. /**
  48173. * Remove all attached input methods from a camera
  48174. */
  48175. CameraInputsManager.prototype.clear = function () {
  48176. if (this.attachedElement) {
  48177. this.detachElement(this.attachedElement, true);
  48178. }
  48179. this.attached = {};
  48180. this.attachedElement = null;
  48181. this.checkInputs = function () { };
  48182. };
  48183. /**
  48184. * Serialize the current input manager attached to a camera.
  48185. * This ensures than once parsed,
  48186. * the input associated to the camera will be identical to the current ones
  48187. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  48188. */
  48189. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  48190. var inputs = {};
  48191. for (var cam in this.attached) {
  48192. var input = this.attached[cam];
  48193. var res = BABYLON.SerializationHelper.Serialize(input);
  48194. inputs[input.getClassName()] = res;
  48195. }
  48196. serializedCamera.inputsmgr = inputs;
  48197. };
  48198. /**
  48199. * Parses an input manager serialized JSON to restore the previous list of inputs
  48200. * and states associated to a camera.
  48201. * @param parsedCamera Defines the JSON to parse
  48202. */
  48203. CameraInputsManager.prototype.parse = function (parsedCamera) {
  48204. var parsedInputs = parsedCamera.inputsmgr;
  48205. if (parsedInputs) {
  48206. this.clear();
  48207. for (var n in parsedInputs) {
  48208. var construct = BABYLON.CameraInputTypes[n];
  48209. if (construct) {
  48210. var parsedinput = parsedInputs[n];
  48211. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  48212. this.add(input);
  48213. }
  48214. }
  48215. }
  48216. else {
  48217. //2016-03-08 this part is for managing backward compatibility
  48218. for (var n in this.attached) {
  48219. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  48220. if (construct) {
  48221. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  48222. this.remove(this.attached[n]);
  48223. this.add(input);
  48224. }
  48225. }
  48226. }
  48227. };
  48228. return CameraInputsManager;
  48229. }());
  48230. BABYLON.CameraInputsManager = CameraInputsManager;
  48231. })(BABYLON || (BABYLON = {}));
  48232. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  48233. var BABYLON;
  48234. (function (BABYLON) {
  48235. /**
  48236. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  48237. * This is the base of the follow, arc rotate cameras and Free camera
  48238. * @see http://doc.babylonjs.com/features/cameras
  48239. */
  48240. var TargetCamera = /** @class */ (function (_super) {
  48241. __extends(TargetCamera, _super);
  48242. /**
  48243. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  48244. * This is the base of the follow, arc rotate cameras and Free camera
  48245. * @see http://doc.babylonjs.com/features/cameras
  48246. * @param name Defines the name of the camera in the scene
  48247. * @param position Defines the start position of the camera in the scene
  48248. * @param scene Defines the scene the camera belongs to
  48249. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48250. */
  48251. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48252. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48253. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48254. /**
  48255. * Define the current direction the camera is moving to
  48256. */
  48257. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48258. /**
  48259. * Define the current rotation the camera is rotating to
  48260. */
  48261. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  48262. /**
  48263. * Define the current rotation of the camera
  48264. */
  48265. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  48266. /**
  48267. * Define the current speed of the camera
  48268. */
  48269. _this.speed = 2.0;
  48270. /**
  48271. * Add cconstraint to the camera to prevent it to move freely in all directions and
  48272. * around all axis.
  48273. */
  48274. _this.noRotationConstraint = false;
  48275. /**
  48276. * Define the current target of the camera as an object or a position.
  48277. */
  48278. _this.lockedTarget = null;
  48279. /** @hidden */
  48280. _this._currentTarget = BABYLON.Vector3.Zero();
  48281. /** @hidden */
  48282. _this._viewMatrix = BABYLON.Matrix.Zero();
  48283. /** @hidden */
  48284. _this._camMatrix = BABYLON.Matrix.Zero();
  48285. /** @hidden */
  48286. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  48287. /** @hidden */
  48288. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  48289. /** @hidden */
  48290. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  48291. /** @hidden */
  48292. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  48293. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  48294. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  48295. _this._defaultUp = BABYLON.Vector3.Up();
  48296. _this._cachedRotationZ = 0;
  48297. _this._cachedQuaternionRotationZ = 0;
  48298. return _this;
  48299. }
  48300. /**
  48301. * Gets the position in front of the camera at a given distance.
  48302. * @param distance The distance from the camera we want the position to be
  48303. * @returns the position
  48304. */
  48305. TargetCamera.prototype.getFrontPosition = function (distance) {
  48306. this.getWorldMatrix();
  48307. var direction = this.getTarget().subtract(this.position);
  48308. direction.normalize();
  48309. direction.scaleInPlace(distance);
  48310. return this.globalPosition.add(direction);
  48311. };
  48312. /** @hidden */
  48313. TargetCamera.prototype._getLockedTargetPosition = function () {
  48314. if (!this.lockedTarget) {
  48315. return null;
  48316. }
  48317. if (this.lockedTarget.absolutePosition) {
  48318. this.lockedTarget.computeWorldMatrix();
  48319. }
  48320. return this.lockedTarget.absolutePosition || this.lockedTarget;
  48321. };
  48322. /**
  48323. * Store current camera state of the camera (fov, position, rotation, etc..)
  48324. * @returns the camera
  48325. */
  48326. TargetCamera.prototype.storeState = function () {
  48327. this._storedPosition = this.position.clone();
  48328. this._storedRotation = this.rotation.clone();
  48329. if (this.rotationQuaternion) {
  48330. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  48331. }
  48332. return _super.prototype.storeState.call(this);
  48333. };
  48334. /**
  48335. * Restored camera state. You must call storeState() first
  48336. * @returns whether it was successful or not
  48337. * @hidden
  48338. */
  48339. TargetCamera.prototype._restoreStateValues = function () {
  48340. if (!_super.prototype._restoreStateValues.call(this)) {
  48341. return false;
  48342. }
  48343. this.position = this._storedPosition.clone();
  48344. this.rotation = this._storedRotation.clone();
  48345. if (this.rotationQuaternion) {
  48346. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  48347. }
  48348. this.cameraDirection.copyFromFloats(0, 0, 0);
  48349. this.cameraRotation.copyFromFloats(0, 0);
  48350. return true;
  48351. };
  48352. /** @hidden */
  48353. TargetCamera.prototype._initCache = function () {
  48354. _super.prototype._initCache.call(this);
  48355. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48356. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48357. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48358. };
  48359. /** @hidden */
  48360. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  48361. if (!ignoreParentClass) {
  48362. _super.prototype._updateCache.call(this);
  48363. }
  48364. var lockedTargetPosition = this._getLockedTargetPosition();
  48365. if (!lockedTargetPosition) {
  48366. this._cache.lockedTarget = null;
  48367. }
  48368. else {
  48369. if (!this._cache.lockedTarget) {
  48370. this._cache.lockedTarget = lockedTargetPosition.clone();
  48371. }
  48372. else {
  48373. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  48374. }
  48375. }
  48376. this._cache.rotation.copyFrom(this.rotation);
  48377. if (this.rotationQuaternion) {
  48378. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48379. }
  48380. };
  48381. // Synchronized
  48382. /** @hidden */
  48383. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  48384. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  48385. return false;
  48386. }
  48387. var lockedTargetPosition = this._getLockedTargetPosition();
  48388. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  48389. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  48390. };
  48391. // Methods
  48392. /** @hidden */
  48393. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  48394. var engine = this.getEngine();
  48395. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  48396. };
  48397. // Target
  48398. /** @hidden */
  48399. TargetCamera.prototype.setTarget = function (target) {
  48400. this.upVector.normalize();
  48401. if (this.position.z === target.z) {
  48402. this.position.z += BABYLON.Epsilon;
  48403. }
  48404. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  48405. this._camMatrix.invert();
  48406. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  48407. var vDir = target.subtract(this.position);
  48408. if (vDir.x >= 0.0) {
  48409. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  48410. }
  48411. else {
  48412. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  48413. }
  48414. this.rotation.z = 0;
  48415. if (isNaN(this.rotation.x)) {
  48416. this.rotation.x = 0;
  48417. }
  48418. if (isNaN(this.rotation.y)) {
  48419. this.rotation.y = 0;
  48420. }
  48421. if (isNaN(this.rotation.z)) {
  48422. this.rotation.z = 0;
  48423. }
  48424. if (this.rotationQuaternion) {
  48425. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48426. }
  48427. };
  48428. /**
  48429. * Return the current target position of the camera. This value is expressed in local space.
  48430. * @returns the target position
  48431. */
  48432. TargetCamera.prototype.getTarget = function () {
  48433. return this._currentTarget;
  48434. };
  48435. /** @hidden */
  48436. TargetCamera.prototype._decideIfNeedsToMove = function () {
  48437. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48438. };
  48439. /** @hidden */
  48440. TargetCamera.prototype._updatePosition = function () {
  48441. if (this.parent) {
  48442. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  48443. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  48444. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  48445. return;
  48446. }
  48447. this.position.addInPlace(this.cameraDirection);
  48448. };
  48449. /** @hidden */
  48450. TargetCamera.prototype._checkInputs = function () {
  48451. var needToMove = this._decideIfNeedsToMove();
  48452. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  48453. // Move
  48454. if (needToMove) {
  48455. this._updatePosition();
  48456. }
  48457. // Rotate
  48458. if (needToRotate) {
  48459. this.rotation.x += this.cameraRotation.x;
  48460. this.rotation.y += this.cameraRotation.y;
  48461. //rotate, if quaternion is set and rotation was used
  48462. if (this.rotationQuaternion) {
  48463. var len = this.rotation.lengthSquared();
  48464. if (len) {
  48465. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48466. }
  48467. }
  48468. if (!this.noRotationConstraint) {
  48469. var limit = (Math.PI / 2) * 0.95;
  48470. if (this.rotation.x > limit) {
  48471. this.rotation.x = limit;
  48472. }
  48473. if (this.rotation.x < -limit) {
  48474. this.rotation.x = -limit;
  48475. }
  48476. }
  48477. }
  48478. // Inertia
  48479. if (needToMove) {
  48480. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  48481. this.cameraDirection.x = 0;
  48482. }
  48483. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  48484. this.cameraDirection.y = 0;
  48485. }
  48486. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  48487. this.cameraDirection.z = 0;
  48488. }
  48489. this.cameraDirection.scaleInPlace(this.inertia);
  48490. }
  48491. if (needToRotate) {
  48492. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  48493. this.cameraRotation.x = 0;
  48494. }
  48495. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  48496. this.cameraRotation.y = 0;
  48497. }
  48498. this.cameraRotation.scaleInPlace(this.inertia);
  48499. }
  48500. _super.prototype._checkInputs.call(this);
  48501. };
  48502. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  48503. if (this.rotationQuaternion) {
  48504. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  48505. }
  48506. else {
  48507. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  48508. }
  48509. };
  48510. /**
  48511. * 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)
  48512. * @returns the current camera
  48513. */
  48514. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  48515. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  48516. return this;
  48517. };
  48518. /** @hidden */
  48519. TargetCamera.prototype._getViewMatrix = function () {
  48520. if (this.lockedTarget) {
  48521. this.setTarget(this._getLockedTargetPosition());
  48522. }
  48523. // Compute
  48524. this._updateCameraRotationMatrix();
  48525. // Apply the changed rotation to the upVector
  48526. if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
  48527. this._rotateUpVectorWithCameraRotationMatrix();
  48528. this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
  48529. }
  48530. else if (this._cachedRotationZ != this.rotation.z) {
  48531. this._rotateUpVectorWithCameraRotationMatrix();
  48532. this._cachedRotationZ = this.rotation.z;
  48533. }
  48534. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  48535. // Computing target and final matrix
  48536. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  48537. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  48538. return this._viewMatrix;
  48539. };
  48540. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  48541. if (this.parent) {
  48542. var parentWorldMatrix = this.parent.getWorldMatrix();
  48543. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  48544. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  48545. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  48546. this._markSyncedWithParent();
  48547. }
  48548. else {
  48549. this._globalPosition.copyFrom(position);
  48550. this._globalCurrentTarget.copyFrom(target);
  48551. this._globalCurrentUpVector.copyFrom(up);
  48552. }
  48553. if (this.getScene().useRightHandedSystem) {
  48554. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48555. }
  48556. else {
  48557. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48558. }
  48559. };
  48560. /**
  48561. * @hidden
  48562. */
  48563. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48564. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  48565. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  48566. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  48567. if (!this.rotationQuaternion) {
  48568. this.rotationQuaternion = new BABYLON.Quaternion();
  48569. }
  48570. rigCamera._cameraRigParams = {};
  48571. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  48572. }
  48573. return rigCamera;
  48574. }
  48575. return null;
  48576. };
  48577. /**
  48578. * @hidden
  48579. */
  48580. TargetCamera.prototype._updateRigCameras = function () {
  48581. var camLeft = this._rigCameras[0];
  48582. var camRight = this._rigCameras[1];
  48583. switch (this.cameraRigMode) {
  48584. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48585. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48586. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48587. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48588. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  48589. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  48590. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  48591. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  48592. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  48593. camLeft.setTarget(this.getTarget());
  48594. camRight.setTarget(this.getTarget());
  48595. break;
  48596. case BABYLON.Camera.RIG_MODE_VR:
  48597. if (camLeft.rotationQuaternion) {
  48598. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48599. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48600. }
  48601. else {
  48602. camLeft.rotation.copyFrom(this.rotation);
  48603. camRight.rotation.copyFrom(this.rotation);
  48604. }
  48605. camLeft.position.copyFrom(this.position);
  48606. camRight.position.copyFrom(this.position);
  48607. break;
  48608. }
  48609. _super.prototype._updateRigCameras.call(this);
  48610. };
  48611. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  48612. if (!this._rigCamTransformMatrix) {
  48613. this._rigCamTransformMatrix = new BABYLON.Matrix();
  48614. }
  48615. var target = this.getTarget();
  48616. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  48617. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  48618. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  48619. };
  48620. /**
  48621. * Gets the current object class name.
  48622. * @return the class name
  48623. */
  48624. TargetCamera.prototype.getClassName = function () {
  48625. return "TargetCamera";
  48626. };
  48627. __decorate([
  48628. BABYLON.serializeAsVector3()
  48629. ], TargetCamera.prototype, "rotation", void 0);
  48630. __decorate([
  48631. BABYLON.serialize()
  48632. ], TargetCamera.prototype, "speed", void 0);
  48633. __decorate([
  48634. BABYLON.serializeAsMeshReference("lockedTargetId")
  48635. ], TargetCamera.prototype, "lockedTarget", void 0);
  48636. return TargetCamera;
  48637. }(BABYLON.Camera));
  48638. BABYLON.TargetCamera = TargetCamera;
  48639. })(BABYLON || (BABYLON = {}));
  48640. //# sourceMappingURL=babylon.targetCamera.js.map
  48641. var BABYLON;
  48642. (function (BABYLON) {
  48643. /**
  48644. * Manage the mouse inputs to control the movement of a free camera.
  48645. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48646. */
  48647. var FreeCameraMouseInput = /** @class */ (function () {
  48648. /**
  48649. * Manage the mouse inputs to control the movement of a free camera.
  48650. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48651. * @param touchEnabled Defines if touch is enabled or not
  48652. */
  48653. function FreeCameraMouseInput(
  48654. /**
  48655. * Define if touch is enabled in the mouse input
  48656. */
  48657. touchEnabled) {
  48658. if (touchEnabled === void 0) { touchEnabled = true; }
  48659. this.touchEnabled = touchEnabled;
  48660. /**
  48661. * Defines the buttons associated with the input to handle camera move.
  48662. */
  48663. this.buttons = [0, 1, 2];
  48664. /**
  48665. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  48666. */
  48667. this.angularSensibility = 2000.0;
  48668. this.previousPosition = null;
  48669. }
  48670. /**
  48671. * Attach the input controls to a specific dom element to get the input from.
  48672. * @param element Defines the element the controls should be listened from
  48673. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48674. */
  48675. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  48676. var _this = this;
  48677. var engine = this.camera.getEngine();
  48678. if (!this._pointerInput) {
  48679. this._pointerInput = function (p, s) {
  48680. var evt = p.event;
  48681. if (engine.isInVRExclusivePointerMode) {
  48682. return;
  48683. }
  48684. if (!_this.touchEnabled && evt.pointerType === "touch") {
  48685. return;
  48686. }
  48687. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48688. return;
  48689. }
  48690. var srcElement = (evt.srcElement || evt.target);
  48691. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48692. try {
  48693. srcElement.setPointerCapture(evt.pointerId);
  48694. }
  48695. catch (e) {
  48696. //Nothing to do with the error. Execution will continue.
  48697. }
  48698. _this.previousPosition = {
  48699. x: evt.clientX,
  48700. y: evt.clientY
  48701. };
  48702. if (!noPreventDefault) {
  48703. evt.preventDefault();
  48704. element.focus();
  48705. }
  48706. }
  48707. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48708. try {
  48709. srcElement.releasePointerCapture(evt.pointerId);
  48710. }
  48711. catch (e) {
  48712. //Nothing to do with the error.
  48713. }
  48714. _this.previousPosition = null;
  48715. if (!noPreventDefault) {
  48716. evt.preventDefault();
  48717. }
  48718. }
  48719. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48720. if (!_this.previousPosition || engine.isPointerLock) {
  48721. return;
  48722. }
  48723. var offsetX = evt.clientX - _this.previousPosition.x;
  48724. if (_this.camera.getScene().useRightHandedSystem) {
  48725. offsetX *= -1;
  48726. }
  48727. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48728. offsetX *= -1;
  48729. }
  48730. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48731. var offsetY = evt.clientY - _this.previousPosition.y;
  48732. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48733. _this.previousPosition = {
  48734. x: evt.clientX,
  48735. y: evt.clientY
  48736. };
  48737. if (!noPreventDefault) {
  48738. evt.preventDefault();
  48739. }
  48740. }
  48741. };
  48742. }
  48743. this._onMouseMove = function (evt) {
  48744. if (!engine.isPointerLock) {
  48745. return;
  48746. }
  48747. if (engine.isInVRExclusivePointerMode) {
  48748. return;
  48749. }
  48750. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48751. if (_this.camera.getScene().useRightHandedSystem) {
  48752. offsetX *= -1;
  48753. }
  48754. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48755. offsetX *= -1;
  48756. }
  48757. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48758. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48759. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48760. _this.previousPosition = null;
  48761. if (!noPreventDefault) {
  48762. evt.preventDefault();
  48763. }
  48764. };
  48765. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48766. element.addEventListener("mousemove", this._onMouseMove, false);
  48767. };
  48768. /**
  48769. * Detach the current controls from the specified dom element.
  48770. * @param element Defines the element to stop listening the inputs from
  48771. */
  48772. FreeCameraMouseInput.prototype.detachControl = function (element) {
  48773. if (this._observer && element) {
  48774. this.camera.getScene().onPointerObservable.remove(this._observer);
  48775. if (this._onMouseMove) {
  48776. element.removeEventListener("mousemove", this._onMouseMove);
  48777. }
  48778. this._observer = null;
  48779. this._onMouseMove = null;
  48780. this.previousPosition = null;
  48781. }
  48782. };
  48783. /**
  48784. * Gets the class name of the current intput.
  48785. * @returns the class name
  48786. */
  48787. FreeCameraMouseInput.prototype.getClassName = function () {
  48788. return "FreeCameraMouseInput";
  48789. };
  48790. /**
  48791. * Get the friendly name associated with the input class.
  48792. * @returns the input friendly name
  48793. */
  48794. FreeCameraMouseInput.prototype.getSimpleName = function () {
  48795. return "mouse";
  48796. };
  48797. __decorate([
  48798. BABYLON.serialize()
  48799. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  48800. __decorate([
  48801. BABYLON.serialize()
  48802. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  48803. return FreeCameraMouseInput;
  48804. }());
  48805. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  48806. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  48807. })(BABYLON || (BABYLON = {}));
  48808. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  48809. var BABYLON;
  48810. (function (BABYLON) {
  48811. /**
  48812. * Manage the keyboard inputs to control the movement of a free camera.
  48813. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48814. */
  48815. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  48816. function FreeCameraKeyboardMoveInput() {
  48817. /**
  48818. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48819. */
  48820. this.keysUp = [38];
  48821. /**
  48822. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48823. */
  48824. this.keysDown = [40];
  48825. /**
  48826. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48827. */
  48828. this.keysLeft = [37];
  48829. /**
  48830. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48831. */
  48832. this.keysRight = [39];
  48833. this._keys = new Array();
  48834. }
  48835. /**
  48836. * Attach the input controls to a specific dom element to get the input from.
  48837. * @param element Defines the element the controls should be listened from
  48838. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48839. */
  48840. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48841. var _this = this;
  48842. if (this._onCanvasBlurObserver) {
  48843. return;
  48844. }
  48845. this._scene = this.camera.getScene();
  48846. this._engine = this._scene.getEngine();
  48847. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48848. _this._keys = [];
  48849. });
  48850. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48851. var evt = info.event;
  48852. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48853. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48854. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48855. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48856. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48857. var index = _this._keys.indexOf(evt.keyCode);
  48858. if (index === -1) {
  48859. _this._keys.push(evt.keyCode);
  48860. }
  48861. if (!noPreventDefault) {
  48862. evt.preventDefault();
  48863. }
  48864. }
  48865. }
  48866. else {
  48867. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48868. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48869. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48870. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48871. var index = _this._keys.indexOf(evt.keyCode);
  48872. if (index >= 0) {
  48873. _this._keys.splice(index, 1);
  48874. }
  48875. if (!noPreventDefault) {
  48876. evt.preventDefault();
  48877. }
  48878. }
  48879. }
  48880. });
  48881. };
  48882. /**
  48883. * Detach the current controls from the specified dom element.
  48884. * @param element Defines the element to stop listening the inputs from
  48885. */
  48886. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48887. if (this._scene) {
  48888. if (this._onKeyboardObserver) {
  48889. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48890. }
  48891. if (this._onCanvasBlurObserver) {
  48892. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48893. }
  48894. this._onKeyboardObserver = null;
  48895. this._onCanvasBlurObserver = null;
  48896. }
  48897. this._keys = [];
  48898. };
  48899. /**
  48900. * Update the current camera state depending on the inputs that have been used this frame.
  48901. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48902. */
  48903. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48904. if (this._onKeyboardObserver) {
  48905. var camera = this.camera;
  48906. // Keyboard
  48907. for (var index = 0; index < this._keys.length; index++) {
  48908. var keyCode = this._keys[index];
  48909. var speed = camera._computeLocalCameraSpeed();
  48910. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48911. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48912. }
  48913. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48914. camera._localDirection.copyFromFloats(0, 0, speed);
  48915. }
  48916. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48917. camera._localDirection.copyFromFloats(speed, 0, 0);
  48918. }
  48919. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48920. camera._localDirection.copyFromFloats(0, 0, -speed);
  48921. }
  48922. if (camera.getScene().useRightHandedSystem) {
  48923. camera._localDirection.z *= -1;
  48924. }
  48925. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48926. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48927. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48928. }
  48929. }
  48930. };
  48931. /**
  48932. * Gets the class name of the current intput.
  48933. * @returns the class name
  48934. */
  48935. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48936. return "FreeCameraKeyboardMoveInput";
  48937. };
  48938. /** @hidden */
  48939. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48940. this._keys = [];
  48941. };
  48942. /**
  48943. * Get the friendly name associated with the input class.
  48944. * @returns the input friendly name
  48945. */
  48946. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48947. return "keyboard";
  48948. };
  48949. __decorate([
  48950. BABYLON.serialize()
  48951. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48952. __decorate([
  48953. BABYLON.serialize()
  48954. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48955. __decorate([
  48956. BABYLON.serialize()
  48957. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48958. __decorate([
  48959. BABYLON.serialize()
  48960. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48961. return FreeCameraKeyboardMoveInput;
  48962. }());
  48963. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  48964. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  48965. })(BABYLON || (BABYLON = {}));
  48966. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  48967. var BABYLON;
  48968. (function (BABYLON) {
  48969. /**
  48970. * Default Inputs manager for the FreeCamera.
  48971. * It groups all the default supported inputs for ease of use.
  48972. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48973. */
  48974. var FreeCameraInputsManager = /** @class */ (function (_super) {
  48975. __extends(FreeCameraInputsManager, _super);
  48976. /**
  48977. * Instantiates a new FreeCameraInputsManager.
  48978. * @param camera Defines the camera the inputs belong to
  48979. */
  48980. function FreeCameraInputsManager(camera) {
  48981. return _super.call(this, camera) || this;
  48982. }
  48983. /**
  48984. * Add keyboard input support to the input manager.
  48985. * @returns the current input manager
  48986. */
  48987. FreeCameraInputsManager.prototype.addKeyboard = function () {
  48988. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  48989. return this;
  48990. };
  48991. /**
  48992. * Add mouse input support to the input manager.
  48993. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
  48994. * @returns the current input manager
  48995. */
  48996. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  48997. if (touchEnabled === void 0) { touchEnabled = true; }
  48998. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48999. return this;
  49000. };
  49001. /**
  49002. * Add orientation input support to the input manager.
  49003. * @returns the current input manager
  49004. */
  49005. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  49006. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  49007. return this;
  49008. };
  49009. /**
  49010. * Add touch input support to the input manager.
  49011. * @returns the current input manager
  49012. */
  49013. FreeCameraInputsManager.prototype.addTouch = function () {
  49014. this.add(new BABYLON.FreeCameraTouchInput());
  49015. return this;
  49016. };
  49017. /**
  49018. * Add virtual joystick input support to the input manager.
  49019. * @returns the current input manager
  49020. */
  49021. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  49022. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  49023. return this;
  49024. };
  49025. return FreeCameraInputsManager;
  49026. }(BABYLON.CameraInputsManager));
  49027. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  49028. })(BABYLON || (BABYLON = {}));
  49029. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  49030. var BABYLON;
  49031. (function (BABYLON) {
  49032. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  49033. // Forcing to use the Universal camera
  49034. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  49035. });
  49036. /**
  49037. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  49038. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  49039. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  49040. */
  49041. var FreeCamera = /** @class */ (function (_super) {
  49042. __extends(FreeCamera, _super);
  49043. /**
  49044. * Instantiates a Free Camera.
  49045. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  49046. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  49047. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  49048. * @param name Define the name of the camera in the scene
  49049. * @param position Define the start position of the camera in the scene
  49050. * @param scene Define the scene the camera belongs to
  49051. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49052. */
  49053. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  49054. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49055. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  49056. /**
  49057. * Define the collision ellipsoid of the camera.
  49058. * This is helpful to simulate a camera body like the player body around the camera
  49059. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49060. */
  49061. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  49062. /**
  49063. * Define an offset for the position of the ellipsoid around the camera.
  49064. * This can be helpful to determine the center of the body near the gravity center of the body
  49065. * instead of its head.
  49066. */
  49067. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  49068. /**
  49069. * Enable or disable collisions of the camera with the rest of the scene objects.
  49070. */
  49071. _this.checkCollisions = false;
  49072. /**
  49073. * Enable or disable gravity on the camera.
  49074. */
  49075. _this.applyGravity = false;
  49076. _this._needMoveForGravity = false;
  49077. _this._oldPosition = BABYLON.Vector3.Zero();
  49078. _this._diffPosition = BABYLON.Vector3.Zero();
  49079. _this._newPosition = BABYLON.Vector3.Zero();
  49080. // Collisions
  49081. _this._collisionMask = -1;
  49082. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49083. if (collidedMesh === void 0) { collidedMesh = null; }
  49084. //TODO move this to the collision coordinator!
  49085. if (_this.getScene().workerCollisions) {
  49086. newPosition.multiplyInPlace(_this._collider._radius);
  49087. }
  49088. var updatePosition = function (newPos) {
  49089. _this._newPosition.copyFrom(newPos);
  49090. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  49091. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  49092. _this.position.addInPlace(_this._diffPosition);
  49093. if (_this.onCollide && collidedMesh) {
  49094. _this.onCollide(collidedMesh);
  49095. }
  49096. }
  49097. };
  49098. updatePosition(newPosition);
  49099. };
  49100. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  49101. _this.inputs.addKeyboard().addMouse();
  49102. return _this;
  49103. }
  49104. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  49105. /**
  49106. * Gets the input sensibility for a mouse input. (default is 2000.0)
  49107. * Higher values reduce sensitivity.
  49108. */
  49109. get: function () {
  49110. var mouse = this.inputs.attached["mouse"];
  49111. if (mouse) {
  49112. return mouse.angularSensibility;
  49113. }
  49114. return 0;
  49115. },
  49116. /**
  49117. * Sets the input sensibility for a mouse input. (default is 2000.0)
  49118. * Higher values reduce sensitivity.
  49119. */
  49120. set: function (value) {
  49121. var mouse = this.inputs.attached["mouse"];
  49122. if (mouse) {
  49123. mouse.angularSensibility = value;
  49124. }
  49125. },
  49126. enumerable: true,
  49127. configurable: true
  49128. });
  49129. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  49130. /**
  49131. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  49132. */
  49133. get: function () {
  49134. var keyboard = this.inputs.attached["keyboard"];
  49135. if (keyboard) {
  49136. return keyboard.keysUp;
  49137. }
  49138. return [];
  49139. },
  49140. set: function (value) {
  49141. var keyboard = this.inputs.attached["keyboard"];
  49142. if (keyboard) {
  49143. keyboard.keysUp = value;
  49144. }
  49145. },
  49146. enumerable: true,
  49147. configurable: true
  49148. });
  49149. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  49150. /**
  49151. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  49152. */
  49153. get: function () {
  49154. var keyboard = this.inputs.attached["keyboard"];
  49155. if (keyboard) {
  49156. return keyboard.keysDown;
  49157. }
  49158. return [];
  49159. },
  49160. set: function (value) {
  49161. var keyboard = this.inputs.attached["keyboard"];
  49162. if (keyboard) {
  49163. keyboard.keysDown = value;
  49164. }
  49165. },
  49166. enumerable: true,
  49167. configurable: true
  49168. });
  49169. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  49170. /**
  49171. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  49172. */
  49173. get: function () {
  49174. var keyboard = this.inputs.attached["keyboard"];
  49175. if (keyboard) {
  49176. return keyboard.keysLeft;
  49177. }
  49178. return [];
  49179. },
  49180. set: function (value) {
  49181. var keyboard = this.inputs.attached["keyboard"];
  49182. if (keyboard) {
  49183. keyboard.keysLeft = value;
  49184. }
  49185. },
  49186. enumerable: true,
  49187. configurable: true
  49188. });
  49189. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  49190. /**
  49191. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  49192. */
  49193. get: function () {
  49194. var keyboard = this.inputs.attached["keyboard"];
  49195. if (keyboard) {
  49196. return keyboard.keysRight;
  49197. }
  49198. return [];
  49199. },
  49200. set: function (value) {
  49201. var keyboard = this.inputs.attached["keyboard"];
  49202. if (keyboard) {
  49203. keyboard.keysRight = value;
  49204. }
  49205. },
  49206. enumerable: true,
  49207. configurable: true
  49208. });
  49209. /**
  49210. * Attached controls to the current camera.
  49211. * @param element Defines the element the controls should be listened from
  49212. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49213. */
  49214. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  49215. this.inputs.attachElement(element, noPreventDefault);
  49216. };
  49217. /**
  49218. * Detach the current controls from the camera.
  49219. * The camera will stop reacting to inputs.
  49220. * @param element Defines the element to stop listening the inputs from
  49221. */
  49222. FreeCamera.prototype.detachControl = function (element) {
  49223. this.inputs.detachElement(element);
  49224. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  49225. this.cameraRotation = new BABYLON.Vector2(0, 0);
  49226. };
  49227. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  49228. /**
  49229. * Define a collision mask to limit the list of object the camera can collide with
  49230. */
  49231. get: function () {
  49232. return this._collisionMask;
  49233. },
  49234. set: function (mask) {
  49235. this._collisionMask = !isNaN(mask) ? mask : -1;
  49236. },
  49237. enumerable: true,
  49238. configurable: true
  49239. });
  49240. /** @hidden */
  49241. FreeCamera.prototype._collideWithWorld = function (displacement) {
  49242. var globalPosition;
  49243. if (this.parent) {
  49244. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  49245. }
  49246. else {
  49247. globalPosition = this.position;
  49248. }
  49249. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  49250. this._oldPosition.addInPlace(this.ellipsoidOffset);
  49251. if (!this._collider) {
  49252. this._collider = new BABYLON.Collider();
  49253. }
  49254. this._collider._radius = this.ellipsoid;
  49255. this._collider.collisionMask = this._collisionMask;
  49256. //no need for clone, as long as gravity is not on.
  49257. var actualDisplacement = displacement;
  49258. //add gravity to the direction to prevent the dual-collision checking
  49259. if (this.applyGravity) {
  49260. //this prevents mending with cameraDirection, a global variable of the free camera class.
  49261. actualDisplacement = displacement.add(this.getScene().gravity);
  49262. }
  49263. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49264. };
  49265. /** @hidden */
  49266. FreeCamera.prototype._checkInputs = function () {
  49267. if (!this._localDirection) {
  49268. this._localDirection = BABYLON.Vector3.Zero();
  49269. this._transformedDirection = BABYLON.Vector3.Zero();
  49270. }
  49271. this.inputs.checkInputs();
  49272. _super.prototype._checkInputs.call(this);
  49273. };
  49274. /** @hidden */
  49275. FreeCamera.prototype._decideIfNeedsToMove = function () {
  49276. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  49277. };
  49278. /** @hidden */
  49279. FreeCamera.prototype._updatePosition = function () {
  49280. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  49281. this._collideWithWorld(this.cameraDirection);
  49282. }
  49283. else {
  49284. _super.prototype._updatePosition.call(this);
  49285. }
  49286. };
  49287. /**
  49288. * Destroy the camera and release the current resources hold by it.
  49289. */
  49290. FreeCamera.prototype.dispose = function () {
  49291. this.inputs.clear();
  49292. _super.prototype.dispose.call(this);
  49293. };
  49294. /**
  49295. * Gets the current object class name.
  49296. * @return the class name
  49297. */
  49298. FreeCamera.prototype.getClassName = function () {
  49299. return "FreeCamera";
  49300. };
  49301. __decorate([
  49302. BABYLON.serializeAsVector3()
  49303. ], FreeCamera.prototype, "ellipsoid", void 0);
  49304. __decorate([
  49305. BABYLON.serializeAsVector3()
  49306. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  49307. __decorate([
  49308. BABYLON.serialize()
  49309. ], FreeCamera.prototype, "checkCollisions", void 0);
  49310. __decorate([
  49311. BABYLON.serialize()
  49312. ], FreeCamera.prototype, "applyGravity", void 0);
  49313. return FreeCamera;
  49314. }(BABYLON.TargetCamera));
  49315. BABYLON.FreeCamera = FreeCamera;
  49316. })(BABYLON || (BABYLON = {}));
  49317. //# sourceMappingURL=babylon.freeCamera.js.map
  49318. var BABYLON;
  49319. (function (BABYLON) {
  49320. /**
  49321. * Listen to mouse events to control the camera.
  49322. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49323. */
  49324. var FlyCameraMouseInput = /** @class */ (function () {
  49325. /**
  49326. * Listen to mouse events to control the camera.
  49327. * @param touchEnabled Define if touch is enabled. (Default is true.)
  49328. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49329. */
  49330. function FlyCameraMouseInput(touchEnabled) {
  49331. if (touchEnabled === void 0) { touchEnabled = true; }
  49332. /**
  49333. * Defines the buttons associated with the input to handle camera rotation.
  49334. */
  49335. this.buttons = [0, 1, 2];
  49336. /**
  49337. * Assign buttons for Yaw control.
  49338. */
  49339. this.buttonsYaw = [-1, 0, 1];
  49340. /**
  49341. * Assign buttons for Pitch control.
  49342. */
  49343. this.buttonsPitch = [-1, 0, 1];
  49344. /**
  49345. * Assign buttons for Roll control.
  49346. */
  49347. this.buttonsRoll = [2];
  49348. /**
  49349. * Detect if any button is being pressed while mouse is moved.
  49350. * -1 = Mouse locked.
  49351. * 0 = Left button.
  49352. * 1 = Middle Button.
  49353. * 2 = Right Button.
  49354. */
  49355. this.activeButton = -1;
  49356. /**
  49357. * Defines the pointer's angular sensibility, to control the camera rotation speed.
  49358. * Higher values reduce its sensitivity.
  49359. */
  49360. this.angularSensibility = 1000.0;
  49361. this.previousPosition = null;
  49362. }
  49363. /**
  49364. * Attach the mouse control to the HTML DOM element.
  49365. * @param element Defines the element that listens to the input events.
  49366. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault().
  49367. */
  49368. FlyCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  49369. var _this = this;
  49370. this.element = element;
  49371. this.noPreventDefault = noPreventDefault;
  49372. this._observer = this.camera.getScene().onPointerObservable.add(function (p, s) {
  49373. _this._pointerInput(p, s);
  49374. }, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  49375. // Correct Roll by rate, if enabled.
  49376. this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(function () {
  49377. if (_this.camera.rollCorrect) {
  49378. _this.camera.restoreRoll(_this.camera.rollCorrect);
  49379. }
  49380. });
  49381. // Helper function to keep 'this'.
  49382. this._mousemoveCallback = function (e) {
  49383. _this._onMouseMove(e);
  49384. };
  49385. element.addEventListener("mousemove", this._mousemoveCallback, false);
  49386. };
  49387. /**
  49388. * Detach the current controls from the specified dom element.
  49389. * @param element Defines the element to stop listening the inputs from
  49390. */
  49391. FlyCameraMouseInput.prototype.detachControl = function (element) {
  49392. if (this._observer && element) {
  49393. this.camera.getScene().onPointerObservable.remove(this._observer);
  49394. this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver);
  49395. if (this._mousemoveCallback) {
  49396. element.removeEventListener("mousemove", this._mousemoveCallback);
  49397. }
  49398. this._observer = null;
  49399. this._rollObserver = null;
  49400. this.previousPosition = null;
  49401. this.noPreventDefault = undefined;
  49402. }
  49403. };
  49404. /**
  49405. * Gets the class name of the current input.
  49406. * @returns the class name.
  49407. */
  49408. FlyCameraMouseInput.prototype.getClassName = function () {
  49409. return "FlyCameraMouseInput";
  49410. };
  49411. /**
  49412. * Get the friendly name associated with the input class.
  49413. * @returns the input's friendly name.
  49414. */
  49415. FlyCameraMouseInput.prototype.getSimpleName = function () {
  49416. return "mouse";
  49417. };
  49418. // Track mouse movement, when the pointer is not locked.
  49419. FlyCameraMouseInput.prototype._pointerInput = function (p, s) {
  49420. var e = p.event;
  49421. var camera = this.camera;
  49422. var engine = camera.getEngine();
  49423. if (engine.isInVRExclusivePointerMode) {
  49424. return;
  49425. }
  49426. if (!this.touchEnabled && e.pointerType === "touch") {
  49427. return;
  49428. }
  49429. // Mouse is moved but an unknown mouse button is pressed.
  49430. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && this.buttons.indexOf(e.button) === -1) {
  49431. return;
  49432. }
  49433. var srcElement = (e.srcElement || e.target);
  49434. // Mouse down.
  49435. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49436. try {
  49437. srcElement.setPointerCapture(e.pointerId);
  49438. }
  49439. catch (e) {
  49440. // Nothing to do with the error. Execution continues.
  49441. }
  49442. this.previousPosition = {
  49443. x: e.clientX,
  49444. y: e.clientY
  49445. };
  49446. this.activeButton = e.button;
  49447. if (!this.noPreventDefault) {
  49448. e.preventDefault();
  49449. this.element.focus();
  49450. }
  49451. }
  49452. else
  49453. // Mouse up.
  49454. if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49455. try {
  49456. srcElement.releasePointerCapture(e.pointerId);
  49457. }
  49458. catch (e) {
  49459. // Nothing to do with the error. Execution continues.
  49460. }
  49461. this.activeButton = -1;
  49462. this.previousPosition = null;
  49463. if (!this.noPreventDefault) {
  49464. e.preventDefault();
  49465. }
  49466. }
  49467. else
  49468. // Mouse move.
  49469. if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49470. if (!this.previousPosition || engine.isPointerLock) {
  49471. return;
  49472. }
  49473. var offsetX = e.clientX - this.previousPosition.x;
  49474. var offsetY = e.clientY - this.previousPosition.y;
  49475. this.rotateCamera(offsetX, offsetY);
  49476. this.previousPosition = {
  49477. x: e.clientX,
  49478. y: e.clientY
  49479. };
  49480. if (!this.noPreventDefault) {
  49481. e.preventDefault();
  49482. }
  49483. }
  49484. };
  49485. // Track mouse movement, when pointer is locked.
  49486. FlyCameraMouseInput.prototype._onMouseMove = function (e) {
  49487. var camera = this.camera;
  49488. var engine = camera.getEngine();
  49489. if (!engine.isPointerLock || engine.isInVRExclusivePointerMode) {
  49490. return;
  49491. }
  49492. var offsetX = e.movementX || e.mozMovementX || e.webkitMovementX || e.msMovementX || 0;
  49493. var offsetY = e.movementY || e.mozMovementY || e.webkitMovementY || e.msMovementY || 0;
  49494. this.rotateCamera(offsetX, offsetY);
  49495. this.previousPosition = null;
  49496. if (!this.noPreventDefault) {
  49497. e.preventDefault();
  49498. }
  49499. };
  49500. /**
  49501. * Rotate camera by mouse offset.
  49502. */
  49503. FlyCameraMouseInput.prototype.rotateCamera = function (offsetX, offsetY) {
  49504. var _this = this;
  49505. var camera = this.camera;
  49506. var scene = this.camera.getScene();
  49507. if (scene.useRightHandedSystem) {
  49508. offsetX *= -1;
  49509. }
  49510. if (camera.parent && camera.parent._getWorldMatrixDeterminant() < 0) {
  49511. offsetX *= -1;
  49512. }
  49513. var x = offsetX / this.angularSensibility;
  49514. var y = offsetY / this.angularSensibility;
  49515. // Initialize to current rotation.
  49516. var currentRotation = BABYLON.Quaternion.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z);
  49517. var rotationChange;
  49518. // Pitch.
  49519. if (this.buttonsPitch.some(function (v) { return v === _this.activeButton; })) {
  49520. // Apply change in Radians to vector Angle.
  49521. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.X, y);
  49522. // Apply Pitch to quaternion.
  49523. currentRotation.multiplyInPlace(rotationChange);
  49524. }
  49525. // Yaw.
  49526. if (this.buttonsYaw.some(function (v) { return v === _this.activeButton; })) {
  49527. // Apply change in Radians to vector Angle.
  49528. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Y, x);
  49529. // Apply Yaw to quaternion.
  49530. currentRotation.multiplyInPlace(rotationChange);
  49531. // Add Roll, if banked turning is enabled, within Roll limit.
  49532. var limit = (camera.bankedTurnLimit) + camera._trackRoll; // Defaults to 90° plus manual roll.
  49533. if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) {
  49534. var bankingDelta = camera.bankedTurnMultiplier * -x;
  49535. // Apply change in Radians to vector Angle.
  49536. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Z, bankingDelta);
  49537. // Apply Yaw to quaternion.
  49538. currentRotation.multiplyInPlace(rotationChange);
  49539. }
  49540. }
  49541. // Roll.
  49542. if (this.buttonsRoll.some(function (v) { return v === _this.activeButton; })) {
  49543. // Apply change in Radians to vector Angle.
  49544. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Z, -x);
  49545. // Track Rolling.
  49546. camera._trackRoll -= x;
  49547. // Apply Pitch to quaternion.
  49548. currentRotation.multiplyInPlace(rotationChange);
  49549. }
  49550. // Apply rotationQuaternion to Euler camera.rotation.
  49551. currentRotation.toEulerAnglesToRef(camera.rotation);
  49552. };
  49553. __decorate([
  49554. BABYLON.serialize()
  49555. ], FlyCameraMouseInput.prototype, "buttons", void 0);
  49556. __decorate([
  49557. BABYLON.serialize()
  49558. ], FlyCameraMouseInput.prototype, "angularSensibility", void 0);
  49559. return FlyCameraMouseInput;
  49560. }());
  49561. BABYLON.FlyCameraMouseInput = FlyCameraMouseInput;
  49562. BABYLON.CameraInputTypes["FlyCameraMouseInput"] = FlyCameraMouseInput;
  49563. })(BABYLON || (BABYLON = {}));
  49564. //# sourceMappingURL=babylon.flyCameraMouseInput.js.map
  49565. var BABYLON;
  49566. (function (BABYLON) {
  49567. /**
  49568. * Listen to keyboard events to control the camera.
  49569. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49570. */
  49571. var FlyCameraKeyboardInput = /** @class */ (function () {
  49572. function FlyCameraKeyboardInput() {
  49573. /**
  49574. * The list of keyboard keys used to control the forward move of the camera.
  49575. */
  49576. this.keysForward = [87];
  49577. /**
  49578. * The list of keyboard keys used to control the backward move of the camera.
  49579. */
  49580. this.keysBackward = [83];
  49581. /**
  49582. * The list of keyboard keys used to control the forward move of the camera.
  49583. */
  49584. this.keysUp = [69];
  49585. /**
  49586. * The list of keyboard keys used to control the backward move of the camera.
  49587. */
  49588. this.keysDown = [81];
  49589. /**
  49590. * The list of keyboard keys used to control the right strafe move of the camera.
  49591. */
  49592. this.keysRight = [68];
  49593. /**
  49594. * The list of keyboard keys used to control the left strafe move of the camera.
  49595. */
  49596. this.keysLeft = [65];
  49597. this._keys = new Array();
  49598. }
  49599. /**
  49600. * Attach the input controls to a specific dom element to get the input from.
  49601. * @param element Defines the element the controls should be listened from
  49602. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49603. */
  49604. FlyCameraKeyboardInput.prototype.attachControl = function (element, noPreventDefault) {
  49605. var _this = this;
  49606. if (this._onCanvasBlurObserver) {
  49607. return;
  49608. }
  49609. this._scene = this.camera.getScene();
  49610. this._engine = this._scene.getEngine();
  49611. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  49612. _this._keys = [];
  49613. });
  49614. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  49615. var evt = info.event;
  49616. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  49617. if (_this.keysForward.indexOf(evt.keyCode) !== -1 ||
  49618. _this.keysBackward.indexOf(evt.keyCode) !== -1 ||
  49619. _this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49620. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49621. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49622. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49623. var index = _this._keys.indexOf(evt.keyCode);
  49624. if (index === -1) {
  49625. _this._keys.push(evt.keyCode);
  49626. }
  49627. if (!noPreventDefault) {
  49628. evt.preventDefault();
  49629. }
  49630. }
  49631. }
  49632. else {
  49633. if (_this.keysForward.indexOf(evt.keyCode) !== -1 ||
  49634. _this.keysBackward.indexOf(evt.keyCode) !== -1 ||
  49635. _this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49636. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49637. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49638. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49639. var index = _this._keys.indexOf(evt.keyCode);
  49640. if (index >= 0) {
  49641. _this._keys.splice(index, 1);
  49642. }
  49643. if (!noPreventDefault) {
  49644. evt.preventDefault();
  49645. }
  49646. }
  49647. }
  49648. });
  49649. };
  49650. /**
  49651. * Detach the current controls from the specified dom element.
  49652. * @param element Defines the element to stop listening the inputs from
  49653. */
  49654. FlyCameraKeyboardInput.prototype.detachControl = function (element) {
  49655. if (this._scene) {
  49656. if (this._onKeyboardObserver) {
  49657. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  49658. }
  49659. if (this._onCanvasBlurObserver) {
  49660. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  49661. }
  49662. this._onKeyboardObserver = null;
  49663. this._onCanvasBlurObserver = null;
  49664. }
  49665. this._keys = [];
  49666. };
  49667. /**
  49668. * Gets the class name of the current intput.
  49669. * @returns the class name
  49670. */
  49671. FlyCameraKeyboardInput.prototype.getClassName = function () {
  49672. return "FlyCameraKeyboardInput";
  49673. };
  49674. /** @hidden */
  49675. FlyCameraKeyboardInput.prototype._onLostFocus = function (e) {
  49676. this._keys = [];
  49677. };
  49678. /**
  49679. * Get the friendly name associated with the input class.
  49680. * @returns the input friendly name
  49681. */
  49682. FlyCameraKeyboardInput.prototype.getSimpleName = function () {
  49683. return "keyboard";
  49684. };
  49685. /**
  49686. * Update the current camera state depending on the inputs that have been used this frame.
  49687. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49688. */
  49689. FlyCameraKeyboardInput.prototype.checkInputs = function () {
  49690. if (this._onKeyboardObserver) {
  49691. var camera = this.camera;
  49692. // Keyboard
  49693. for (var index = 0; index < this._keys.length; index++) {
  49694. var keyCode = this._keys[index];
  49695. var speed = camera._computeLocalCameraSpeed();
  49696. if (this.keysForward.indexOf(keyCode) !== -1) {
  49697. camera._localDirection.copyFromFloats(0, 0, speed);
  49698. }
  49699. else if (this.keysBackward.indexOf(keyCode) !== -1) {
  49700. camera._localDirection.copyFromFloats(0, 0, -speed);
  49701. }
  49702. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49703. camera._localDirection.copyFromFloats(0, speed, 0);
  49704. }
  49705. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49706. camera._localDirection.copyFromFloats(0, -speed, 0);
  49707. }
  49708. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49709. camera._localDirection.copyFromFloats(speed, 0, 0);
  49710. }
  49711. else if (this.keysLeft.indexOf(keyCode) !== -1) {
  49712. camera._localDirection.copyFromFloats(-speed, 0, 0);
  49713. }
  49714. if (camera.getScene().useRightHandedSystem) {
  49715. camera._localDirection.z *= -1;
  49716. }
  49717. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  49718. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  49719. camera.cameraDirection.addInPlace(camera._transformedDirection);
  49720. }
  49721. }
  49722. };
  49723. __decorate([
  49724. BABYLON.serialize()
  49725. ], FlyCameraKeyboardInput.prototype, "keysForward", void 0);
  49726. __decorate([
  49727. BABYLON.serialize()
  49728. ], FlyCameraKeyboardInput.prototype, "keysBackward", void 0);
  49729. __decorate([
  49730. BABYLON.serialize()
  49731. ], FlyCameraKeyboardInput.prototype, "keysUp", void 0);
  49732. __decorate([
  49733. BABYLON.serialize()
  49734. ], FlyCameraKeyboardInput.prototype, "keysDown", void 0);
  49735. __decorate([
  49736. BABYLON.serialize()
  49737. ], FlyCameraKeyboardInput.prototype, "keysRight", void 0);
  49738. __decorate([
  49739. BABYLON.serialize()
  49740. ], FlyCameraKeyboardInput.prototype, "keysLeft", void 0);
  49741. return FlyCameraKeyboardInput;
  49742. }());
  49743. BABYLON.FlyCameraKeyboardInput = FlyCameraKeyboardInput;
  49744. BABYLON.CameraInputTypes["FlyCameraKeyboardInput"] = FlyCameraKeyboardInput;
  49745. })(BABYLON || (BABYLON = {}));
  49746. //# sourceMappingURL=babylon.flyCameraKeyboardInput.js.map
  49747. var BABYLON;
  49748. (function (BABYLON) {
  49749. /**
  49750. * Default Inputs manager for the FlyCamera.
  49751. * It groups all the default supported inputs for ease of use.
  49752. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49753. */
  49754. var FlyCameraInputsManager = /** @class */ (function (_super) {
  49755. __extends(FlyCameraInputsManager, _super);
  49756. /**
  49757. * Instantiates a new FlyCameraInputsManager.
  49758. * @param camera Defines the camera the inputs belong to.
  49759. */
  49760. function FlyCameraInputsManager(camera) {
  49761. return _super.call(this, camera) || this;
  49762. }
  49763. /**
  49764. * Add keyboard input support to the input manager.
  49765. * @returns the new FlyCameraKeyboardMoveInput().
  49766. */
  49767. FlyCameraInputsManager.prototype.addKeyboard = function () {
  49768. this.add(new BABYLON.FlyCameraKeyboardInput());
  49769. return this;
  49770. };
  49771. /**
  49772. * Add mouse input support to the input manager.
  49773. * @param touchEnabled Enable touch screen support.
  49774. * @returns the new FlyCameraMouseInput().
  49775. */
  49776. FlyCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  49777. if (touchEnabled === void 0) { touchEnabled = true; }
  49778. this.add(new BABYLON.FlyCameraMouseInput(touchEnabled));
  49779. return this;
  49780. };
  49781. return FlyCameraInputsManager;
  49782. }(BABYLON.CameraInputsManager));
  49783. BABYLON.FlyCameraInputsManager = FlyCameraInputsManager;
  49784. })(BABYLON || (BABYLON = {}));
  49785. //# sourceMappingURL=babylon.flyCameraInputsManager.js.map
  49786. var BABYLON;
  49787. (function (BABYLON) {
  49788. /**
  49789. * This is a flying camera, designed for 3D movement and rotation in all directions,
  49790. * such as in a 3D Space Shooter or a Flight Simulator.
  49791. */
  49792. var FlyCamera = /** @class */ (function (_super) {
  49793. __extends(FlyCamera, _super);
  49794. /**
  49795. * Instantiates a FlyCamera.
  49796. * This is a flying camera, designed for 3D movement and rotation in all directions,
  49797. * such as in a 3D Space Shooter or a Flight Simulator.
  49798. * @param name Define the name of the camera in the scene.
  49799. * @param position Define the starting position of the camera in the scene.
  49800. * @param scene Define the scene the camera belongs to.
  49801. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active, if no other camera has been defined as active.
  49802. */
  49803. function FlyCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  49804. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49805. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  49806. /**
  49807. * Define the collision ellipsoid of the camera.
  49808. * This is helpful for simulating a camera body, like a player's body.
  49809. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49810. */
  49811. _this.ellipsoid = new BABYLON.Vector3(1, 1, 1);
  49812. /**
  49813. * Define an offset for the position of the ellipsoid around the camera.
  49814. * This can be helpful if the camera is attached away from the player's body center,
  49815. * such as at its head.
  49816. */
  49817. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  49818. /**
  49819. * Enable or disable collisions of the camera with the rest of the scene objects.
  49820. */
  49821. _this.checkCollisions = false;
  49822. /**
  49823. * Enable or disable gravity on the camera.
  49824. */
  49825. _this.applyGravity = false;
  49826. /**
  49827. * Define the current direction the camera is moving to.
  49828. */
  49829. _this.cameraDirection = BABYLON.Vector3.Zero();
  49830. /**
  49831. * Track Roll to maintain the wanted Rolling when looking around.
  49832. */
  49833. _this._trackRoll = 0;
  49834. /**
  49835. * Slowly correct the Roll to its original value after a Pitch+Yaw rotation.
  49836. */
  49837. _this.rollCorrect = 100;
  49838. /**
  49839. * Mimic a banked turn, Rolling the camera when Yawing.
  49840. * It's recommended to use rollCorrect = 10 for faster banking correction.
  49841. */
  49842. _this.bankedTurn = false;
  49843. /**
  49844. * Limit in radians for how much Roll banking will add. (Default: 90°)
  49845. */
  49846. _this.bankedTurnLimit = Math.PI / 2;
  49847. /**
  49848. * Value of 0 disables the banked Roll.
  49849. * Value of 1 is equal to the Yaw angle in radians.
  49850. */
  49851. _this.bankedTurnMultiplier = 1;
  49852. _this._needMoveForGravity = false;
  49853. _this._oldPosition = BABYLON.Vector3.Zero();
  49854. _this._diffPosition = BABYLON.Vector3.Zero();
  49855. _this._newPosition = BABYLON.Vector3.Zero();
  49856. // Collisions.
  49857. _this._collisionMask = -1;
  49858. /** @hidden */
  49859. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49860. if (collidedMesh === void 0) { collidedMesh = null; }
  49861. // TODO Move this to the collision coordinator!
  49862. if (_this.getScene().workerCollisions) {
  49863. newPosition.multiplyInPlace(_this._collider._radius);
  49864. }
  49865. var updatePosition = function (newPos) {
  49866. _this._newPosition.copyFrom(newPos);
  49867. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  49868. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  49869. _this.position.addInPlace(_this._diffPosition);
  49870. if (_this.onCollide && collidedMesh) {
  49871. _this.onCollide(collidedMesh);
  49872. }
  49873. }
  49874. };
  49875. updatePosition(newPosition);
  49876. };
  49877. _this.inputs = new BABYLON.FlyCameraInputsManager(_this);
  49878. _this.inputs.addKeyboard().addMouse();
  49879. return _this;
  49880. }
  49881. Object.defineProperty(FlyCamera.prototype, "angularSensibility", {
  49882. /**
  49883. * Gets the input sensibility for mouse input.
  49884. * Higher values reduce sensitivity.
  49885. */
  49886. get: function () {
  49887. var mouse = this.inputs.attached["mouse"];
  49888. if (mouse) {
  49889. return mouse.angularSensibility;
  49890. }
  49891. return 0;
  49892. },
  49893. /**
  49894. * Sets the input sensibility for a mouse input.
  49895. * Higher values reduce sensitivity.
  49896. */
  49897. set: function (value) {
  49898. var mouse = this.inputs.attached["mouse"];
  49899. if (mouse) {
  49900. mouse.angularSensibility = value;
  49901. }
  49902. },
  49903. enumerable: true,
  49904. configurable: true
  49905. });
  49906. Object.defineProperty(FlyCamera.prototype, "keysForward", {
  49907. /**
  49908. * Get the keys for camera movement forward.
  49909. */
  49910. get: function () {
  49911. var keyboard = this.inputs.attached["keyboard"];
  49912. if (keyboard) {
  49913. return keyboard.keysForward;
  49914. }
  49915. return [];
  49916. },
  49917. /**
  49918. * Set the keys for camera movement forward.
  49919. */
  49920. set: function (value) {
  49921. var keyboard = this.inputs.attached["keyboard"];
  49922. if (keyboard) {
  49923. keyboard.keysForward = value;
  49924. }
  49925. },
  49926. enumerable: true,
  49927. configurable: true
  49928. });
  49929. Object.defineProperty(FlyCamera.prototype, "keysBackward", {
  49930. /**
  49931. * Get the keys for camera movement backward.
  49932. */
  49933. get: function () {
  49934. var keyboard = this.inputs.attached["keyboard"];
  49935. if (keyboard) {
  49936. return keyboard.keysBackward;
  49937. }
  49938. return [];
  49939. },
  49940. set: function (value) {
  49941. var keyboard = this.inputs.attached["keyboard"];
  49942. if (keyboard) {
  49943. keyboard.keysBackward = value;
  49944. }
  49945. },
  49946. enumerable: true,
  49947. configurable: true
  49948. });
  49949. Object.defineProperty(FlyCamera.prototype, "keysUp", {
  49950. /**
  49951. * Get the keys for camera movement up.
  49952. */
  49953. get: function () {
  49954. var keyboard = this.inputs.attached["keyboard"];
  49955. if (keyboard) {
  49956. return keyboard.keysUp;
  49957. }
  49958. return [];
  49959. },
  49960. /**
  49961. * Set the keys for camera movement up.
  49962. */
  49963. set: function (value) {
  49964. var keyboard = this.inputs.attached["keyboard"];
  49965. if (keyboard) {
  49966. keyboard.keysUp = value;
  49967. }
  49968. },
  49969. enumerable: true,
  49970. configurable: true
  49971. });
  49972. Object.defineProperty(FlyCamera.prototype, "keysDown", {
  49973. /**
  49974. * Get the keys for camera movement down.
  49975. */
  49976. get: function () {
  49977. var keyboard = this.inputs.attached["keyboard"];
  49978. if (keyboard) {
  49979. return keyboard.keysDown;
  49980. }
  49981. return [];
  49982. },
  49983. /**
  49984. * Set the keys for camera movement down.
  49985. */
  49986. set: function (value) {
  49987. var keyboard = this.inputs.attached["keyboard"];
  49988. if (keyboard) {
  49989. keyboard.keysDown = value;
  49990. }
  49991. },
  49992. enumerable: true,
  49993. configurable: true
  49994. });
  49995. Object.defineProperty(FlyCamera.prototype, "keysLeft", {
  49996. /**
  49997. * Get the keys for camera movement left.
  49998. */
  49999. get: function () {
  50000. var keyboard = this.inputs.attached["keyboard"];
  50001. if (keyboard) {
  50002. return keyboard.keysLeft;
  50003. }
  50004. return [];
  50005. },
  50006. /**
  50007. * Set the keys for camera movement left.
  50008. */
  50009. set: function (value) {
  50010. var keyboard = this.inputs.attached["keyboard"];
  50011. if (keyboard) {
  50012. keyboard.keysLeft = value;
  50013. }
  50014. },
  50015. enumerable: true,
  50016. configurable: true
  50017. });
  50018. Object.defineProperty(FlyCamera.prototype, "keysRight", {
  50019. /**
  50020. * Set the keys for camera movement right.
  50021. */
  50022. get: function () {
  50023. var keyboard = this.inputs.attached["keyboard"];
  50024. if (keyboard) {
  50025. return keyboard.keysRight;
  50026. }
  50027. return [];
  50028. },
  50029. /**
  50030. * Set the keys for camera movement right.
  50031. */
  50032. set: function (value) {
  50033. var keyboard = this.inputs.attached["keyboard"];
  50034. if (keyboard) {
  50035. keyboard.keysRight = value;
  50036. }
  50037. },
  50038. enumerable: true,
  50039. configurable: true
  50040. });
  50041. /**
  50042. * Attach a control to the HTML DOM element.
  50043. * @param element Defines the element that listens to the input events.
  50044. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
  50045. */
  50046. FlyCamera.prototype.attachControl = function (element, noPreventDefault) {
  50047. this.inputs.attachElement(element, noPreventDefault);
  50048. };
  50049. /**
  50050. * Detach a control from the HTML DOM element.
  50051. * The camera will stop reacting to that input.
  50052. * @param element Defines the element that listens to the input events.
  50053. */
  50054. FlyCamera.prototype.detachControl = function (element) {
  50055. this.inputs.detachElement(element);
  50056. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  50057. };
  50058. Object.defineProperty(FlyCamera.prototype, "collisionMask", {
  50059. /**
  50060. * Get the mask that the camera ignores in collision events.
  50061. */
  50062. get: function () {
  50063. return this._collisionMask;
  50064. },
  50065. /**
  50066. * Set the mask that the camera ignores in collision events.
  50067. */
  50068. set: function (mask) {
  50069. this._collisionMask = !isNaN(mask) ? mask : -1;
  50070. },
  50071. enumerable: true,
  50072. configurable: true
  50073. });
  50074. /** @hidden */
  50075. FlyCamera.prototype._collideWithWorld = function (displacement) {
  50076. var globalPosition;
  50077. if (this.parent) {
  50078. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  50079. }
  50080. else {
  50081. globalPosition = this.position;
  50082. }
  50083. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  50084. this._oldPosition.addInPlace(this.ellipsoidOffset);
  50085. if (!this._collider) {
  50086. this._collider = new BABYLON.Collider();
  50087. }
  50088. this._collider._radius = this.ellipsoid;
  50089. this._collider.collisionMask = this._collisionMask;
  50090. // No need for clone, as long as gravity is not on.
  50091. var actualDisplacement = displacement;
  50092. // Add gravity to direction to prevent dual-collision checking.
  50093. if (this.applyGravity) {
  50094. // This prevents mending with cameraDirection, a global variable of the fly camera class.
  50095. actualDisplacement = displacement.add(this.getScene().gravity);
  50096. }
  50097. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50098. };
  50099. /** @hidden */
  50100. FlyCamera.prototype._checkInputs = function () {
  50101. if (!this._localDirection) {
  50102. this._localDirection = BABYLON.Vector3.Zero();
  50103. this._transformedDirection = BABYLON.Vector3.Zero();
  50104. }
  50105. this.inputs.checkInputs();
  50106. _super.prototype._checkInputs.call(this);
  50107. };
  50108. /** @hidden */
  50109. FlyCamera.prototype._decideIfNeedsToMove = function () {
  50110. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  50111. };
  50112. /** @hidden */
  50113. FlyCamera.prototype._updatePosition = function () {
  50114. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  50115. this._collideWithWorld(this.cameraDirection);
  50116. }
  50117. else {
  50118. _super.prototype._updatePosition.call(this);
  50119. }
  50120. };
  50121. /**
  50122. * Restore the Roll to its target value at the rate specified.
  50123. * @param rate - Higher means slower restoring.
  50124. * @hidden
  50125. */
  50126. FlyCamera.prototype.restoreRoll = function (rate) {
  50127. var limit = this._trackRoll; // Target Roll.
  50128. var z = this.rotation.z; // Current Roll.
  50129. var delta = limit - z; // Difference in Roll.
  50130. var minRad = 0.001; // Tenth of a radian is a barely noticable difference.
  50131. // If the difference is noticable, restore the Roll.
  50132. if (Math.abs(delta) >= minRad) {
  50133. // Change Z rotation towards the target Roll.
  50134. this.rotation.z += delta / rate;
  50135. // Match when near enough.
  50136. if (Math.abs(limit - this.rotation.z) <= minRad) {
  50137. this.rotation.z = limit;
  50138. }
  50139. }
  50140. };
  50141. /**
  50142. * Destroy the camera and release the current resources held by it.
  50143. */
  50144. FlyCamera.prototype.dispose = function () {
  50145. this.inputs.clear();
  50146. _super.prototype.dispose.call(this);
  50147. };
  50148. /**
  50149. * Get the current object class name.
  50150. * @returns the class name.
  50151. */
  50152. FlyCamera.prototype.getClassName = function () {
  50153. return "FlyCamera";
  50154. };
  50155. __decorate([
  50156. BABYLON.serializeAsVector3()
  50157. ], FlyCamera.prototype, "ellipsoid", void 0);
  50158. __decorate([
  50159. BABYLON.serializeAsVector3()
  50160. ], FlyCamera.prototype, "ellipsoidOffset", void 0);
  50161. __decorate([
  50162. BABYLON.serialize()
  50163. ], FlyCamera.prototype, "checkCollisions", void 0);
  50164. __decorate([
  50165. BABYLON.serialize()
  50166. ], FlyCamera.prototype, "applyGravity", void 0);
  50167. return FlyCamera;
  50168. }(BABYLON.TargetCamera));
  50169. BABYLON.FlyCamera = FlyCamera;
  50170. })(BABYLON || (BABYLON = {}));
  50171. //# sourceMappingURL=babylon.flyCamera.js.map
  50172. var BABYLON;
  50173. (function (BABYLON) {
  50174. /**
  50175. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  50176. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50177. */
  50178. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  50179. function ArcRotateCameraKeyboardMoveInput() {
  50180. /**
  50181. * Defines the list of key codes associated with the up action (increase alpha)
  50182. */
  50183. this.keysUp = [38];
  50184. /**
  50185. * Defines the list of key codes associated with the down action (decrease alpha)
  50186. */
  50187. this.keysDown = [40];
  50188. /**
  50189. * Defines the list of key codes associated with the left action (increase beta)
  50190. */
  50191. this.keysLeft = [37];
  50192. /**
  50193. * Defines the list of key codes associated with the right action (decrease beta)
  50194. */
  50195. this.keysRight = [39];
  50196. /**
  50197. * Defines the list of key codes associated with the reset action.
  50198. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  50199. */
  50200. this.keysReset = [220];
  50201. /**
  50202. * Defines the panning sensibility of the inputs.
  50203. * (How fast is the camera paning)
  50204. */
  50205. this.panningSensibility = 50.0;
  50206. /**
  50207. * Defines the zooming sensibility of the inputs.
  50208. * (How fast is the camera zooming)
  50209. */
  50210. this.zoomingSensibility = 25.0;
  50211. /**
  50212. * Defines wether maintaining the alt key down switch the movement mode from
  50213. * orientation to zoom.
  50214. */
  50215. this.useAltToZoom = true;
  50216. /**
  50217. * Rotation speed of the camera
  50218. */
  50219. this.angularSpeed = 0.01;
  50220. this._keys = new Array();
  50221. }
  50222. /**
  50223. * Attach the input controls to a specific dom element to get the input from.
  50224. * @param element Defines the element the controls should be listened from
  50225. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50226. */
  50227. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  50228. var _this = this;
  50229. if (this._onCanvasBlurObserver) {
  50230. return;
  50231. }
  50232. this._scene = this.camera.getScene();
  50233. this._engine = this._scene.getEngine();
  50234. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  50235. _this._keys = [];
  50236. });
  50237. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  50238. var evt = info.event;
  50239. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  50240. _this._ctrlPressed = evt.ctrlKey;
  50241. _this._altPressed = evt.altKey;
  50242. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50243. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50244. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50245. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  50246. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  50247. var index = _this._keys.indexOf(evt.keyCode);
  50248. if (index === -1) {
  50249. _this._keys.push(evt.keyCode);
  50250. }
  50251. if (evt.preventDefault) {
  50252. if (!noPreventDefault) {
  50253. evt.preventDefault();
  50254. }
  50255. }
  50256. }
  50257. }
  50258. else {
  50259. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50260. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50261. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50262. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  50263. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  50264. var index = _this._keys.indexOf(evt.keyCode);
  50265. if (index >= 0) {
  50266. _this._keys.splice(index, 1);
  50267. }
  50268. if (evt.preventDefault) {
  50269. if (!noPreventDefault) {
  50270. evt.preventDefault();
  50271. }
  50272. }
  50273. }
  50274. }
  50275. });
  50276. };
  50277. /**
  50278. * Detach the current controls from the specified dom element.
  50279. * @param element Defines the element to stop listening the inputs from
  50280. */
  50281. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  50282. if (this._scene) {
  50283. if (this._onKeyboardObserver) {
  50284. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  50285. }
  50286. if (this._onCanvasBlurObserver) {
  50287. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  50288. }
  50289. this._onKeyboardObserver = null;
  50290. this._onCanvasBlurObserver = null;
  50291. }
  50292. this._keys = [];
  50293. };
  50294. /**
  50295. * Update the current camera state depending on the inputs that have been used this frame.
  50296. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  50297. */
  50298. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  50299. if (this._onKeyboardObserver) {
  50300. var camera = this.camera;
  50301. for (var index = 0; index < this._keys.length; index++) {
  50302. var keyCode = this._keys[index];
  50303. if (this.keysLeft.indexOf(keyCode) !== -1) {
  50304. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50305. camera.inertialPanningX -= 1 / this.panningSensibility;
  50306. }
  50307. else {
  50308. camera.inertialAlphaOffset -= this.angularSpeed;
  50309. }
  50310. }
  50311. else if (this.keysUp.indexOf(keyCode) !== -1) {
  50312. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50313. camera.inertialPanningY += 1 / this.panningSensibility;
  50314. }
  50315. else if (this._altPressed && this.useAltToZoom) {
  50316. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  50317. }
  50318. else {
  50319. camera.inertialBetaOffset -= this.angularSpeed;
  50320. }
  50321. }
  50322. else if (this.keysRight.indexOf(keyCode) !== -1) {
  50323. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50324. camera.inertialPanningX += 1 / this.panningSensibility;
  50325. }
  50326. else {
  50327. camera.inertialAlphaOffset += this.angularSpeed;
  50328. }
  50329. }
  50330. else if (this.keysDown.indexOf(keyCode) !== -1) {
  50331. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50332. camera.inertialPanningY -= 1 / this.panningSensibility;
  50333. }
  50334. else if (this._altPressed && this.useAltToZoom) {
  50335. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  50336. }
  50337. else {
  50338. camera.inertialBetaOffset += this.angularSpeed;
  50339. }
  50340. }
  50341. else if (this.keysReset.indexOf(keyCode) !== -1) {
  50342. if (camera.useInputToRestoreState) {
  50343. camera.restoreState();
  50344. }
  50345. }
  50346. }
  50347. }
  50348. };
  50349. /**
  50350. * Gets the class name of the current intput.
  50351. * @returns the class name
  50352. */
  50353. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  50354. return "ArcRotateCameraKeyboardMoveInput";
  50355. };
  50356. /**
  50357. * Get the friendly name associated with the input class.
  50358. * @returns the input friendly name
  50359. */
  50360. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  50361. return "keyboard";
  50362. };
  50363. __decorate([
  50364. BABYLON.serialize()
  50365. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  50366. __decorate([
  50367. BABYLON.serialize()
  50368. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  50369. __decorate([
  50370. BABYLON.serialize()
  50371. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  50372. __decorate([
  50373. BABYLON.serialize()
  50374. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  50375. __decorate([
  50376. BABYLON.serialize()
  50377. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  50378. __decorate([
  50379. BABYLON.serialize()
  50380. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  50381. __decorate([
  50382. BABYLON.serialize()
  50383. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  50384. __decorate([
  50385. BABYLON.serialize()
  50386. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  50387. __decorate([
  50388. BABYLON.serialize()
  50389. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  50390. return ArcRotateCameraKeyboardMoveInput;
  50391. }());
  50392. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  50393. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  50394. })(BABYLON || (BABYLON = {}));
  50395. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  50396. var BABYLON;
  50397. (function (BABYLON) {
  50398. /**
  50399. * Manage the mouse wheel inputs to control an arc rotate camera.
  50400. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50401. */
  50402. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  50403. function ArcRotateCameraMouseWheelInput() {
  50404. /**
  50405. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  50406. */
  50407. this.wheelPrecision = 3.0;
  50408. /**
  50409. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  50410. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  50411. */
  50412. this.wheelDeltaPercentage = 0;
  50413. }
  50414. /**
  50415. * Attach the input controls to a specific dom element to get the input from.
  50416. * @param element Defines the element the controls should be listened from
  50417. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50418. */
  50419. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  50420. var _this = this;
  50421. this._wheel = function (p, s) {
  50422. //sanity check - this should be a PointerWheel event.
  50423. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL) {
  50424. return;
  50425. }
  50426. var event = p.event;
  50427. var delta = 0;
  50428. if (event.wheelDelta) {
  50429. if (_this.wheelDeltaPercentage) {
  50430. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  50431. if (event.wheelDelta > 0) {
  50432. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  50433. }
  50434. else {
  50435. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  50436. }
  50437. }
  50438. else {
  50439. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  50440. }
  50441. }
  50442. else {
  50443. var deltaValue = event.deltaY || event.detail;
  50444. delta = -deltaValue / _this.wheelPrecision;
  50445. }
  50446. if (delta) {
  50447. _this.camera.inertialRadiusOffset += delta;
  50448. }
  50449. if (event.preventDefault) {
  50450. if (!noPreventDefault) {
  50451. event.preventDefault();
  50452. }
  50453. }
  50454. };
  50455. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  50456. };
  50457. /**
  50458. * Detach the current controls from the specified dom element.
  50459. * @param element Defines the element to stop listening the inputs from
  50460. */
  50461. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  50462. if (this._observer && element) {
  50463. this.camera.getScene().onPointerObservable.remove(this._observer);
  50464. this._observer = null;
  50465. this._wheel = null;
  50466. }
  50467. };
  50468. /**
  50469. * Gets the class name of the current intput.
  50470. * @returns the class name
  50471. */
  50472. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  50473. return "ArcRotateCameraMouseWheelInput";
  50474. };
  50475. /**
  50476. * Get the friendly name associated with the input class.
  50477. * @returns the input friendly name
  50478. */
  50479. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  50480. return "mousewheel";
  50481. };
  50482. __decorate([
  50483. BABYLON.serialize()
  50484. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  50485. __decorate([
  50486. BABYLON.serialize()
  50487. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  50488. return ArcRotateCameraMouseWheelInput;
  50489. }());
  50490. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  50491. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  50492. })(BABYLON || (BABYLON = {}));
  50493. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  50494. var BABYLON;
  50495. (function (BABYLON) {
  50496. /**
  50497. * Manage the pointers inputs to control an arc rotate camera.
  50498. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50499. */
  50500. var ArcRotateCameraPointersInput = /** @class */ (function () {
  50501. function ArcRotateCameraPointersInput() {
  50502. /**
  50503. * Defines the buttons associated with the input to handle camera move.
  50504. */
  50505. this.buttons = [0, 1, 2];
  50506. /**
  50507. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  50508. */
  50509. this.angularSensibilityX = 1000.0;
  50510. /**
  50511. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  50512. */
  50513. this.angularSensibilityY = 1000.0;
  50514. /**
  50515. * Defines the pointer pinch precision or how fast is the camera zooming.
  50516. */
  50517. this.pinchPrecision = 12.0;
  50518. /**
  50519. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  50520. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50521. */
  50522. this.pinchDeltaPercentage = 0;
  50523. /**
  50524. * Defines the pointer panning sensibility or how fast is the camera moving.
  50525. */
  50526. this.panningSensibility = 1000.0;
  50527. /**
  50528. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  50529. */
  50530. this.multiTouchPanning = true;
  50531. /**
  50532. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  50533. */
  50534. this.multiTouchPanAndZoom = true;
  50535. /**
  50536. * Revers pinch action direction.
  50537. */
  50538. this.pinchInwards = true;
  50539. this._isPanClick = false;
  50540. }
  50541. /**
  50542. * Attach the input controls to a specific dom element to get the input from.
  50543. * @param element Defines the element the controls should be listened from
  50544. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50545. */
  50546. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  50547. var _this = this;
  50548. var engine = this.camera.getEngine();
  50549. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  50550. var pointA = null;
  50551. var pointB = null;
  50552. var previousPinchSquaredDistance = 0;
  50553. var initialDistance = 0;
  50554. var twoFingerActivityCount = 0;
  50555. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  50556. this._pointerInput = function (p, s) {
  50557. var evt = p.event;
  50558. var isTouch = p.event.pointerType === "touch";
  50559. if (engine.isInVRExclusivePointerMode) {
  50560. return;
  50561. }
  50562. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  50563. return;
  50564. }
  50565. var srcElement = (evt.srcElement || evt.target);
  50566. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  50567. try {
  50568. srcElement.setPointerCapture(evt.pointerId);
  50569. }
  50570. catch (e) {
  50571. //Nothing to do with the error. Execution will continue.
  50572. }
  50573. // Manage panning with pan button click
  50574. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  50575. // manage pointers
  50576. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  50577. if (pointA === null) {
  50578. pointA = cacheSoloPointer;
  50579. }
  50580. else if (pointB === null) {
  50581. pointB = cacheSoloPointer;
  50582. }
  50583. if (!noPreventDefault) {
  50584. evt.preventDefault();
  50585. element.focus();
  50586. }
  50587. }
  50588. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  50589. if (_this.camera.useInputToRestoreState) {
  50590. _this.camera.restoreState();
  50591. }
  50592. }
  50593. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  50594. try {
  50595. srcElement.releasePointerCapture(evt.pointerId);
  50596. }
  50597. catch (e) {
  50598. //Nothing to do with the error.
  50599. }
  50600. cacheSoloPointer = null;
  50601. previousPinchSquaredDistance = 0;
  50602. previousMultiTouchPanPosition.isPaning = false;
  50603. previousMultiTouchPanPosition.isPinching = false;
  50604. twoFingerActivityCount = 0;
  50605. initialDistance = 0;
  50606. if (!isTouch) {
  50607. pointB = null; // Mouse and pen are mono pointer
  50608. }
  50609. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  50610. //but emptying completly pointers collection is required to fix a bug on iPhone :
  50611. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  50612. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  50613. if (engine._badOS) {
  50614. pointA = pointB = null;
  50615. }
  50616. else {
  50617. //only remove the impacted pointer in case of multitouch allowing on most
  50618. //platforms switching from rotate to zoom and pan seamlessly.
  50619. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  50620. pointA = pointB;
  50621. pointB = null;
  50622. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  50623. }
  50624. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  50625. pointB = null;
  50626. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  50627. }
  50628. else {
  50629. pointA = pointB = null;
  50630. }
  50631. }
  50632. if (!noPreventDefault) {
  50633. evt.preventDefault();
  50634. }
  50635. }
  50636. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  50637. if (!noPreventDefault) {
  50638. evt.preventDefault();
  50639. }
  50640. // One button down
  50641. if (pointA && pointB === null && cacheSoloPointer) {
  50642. if (_this.panningSensibility !== 0 &&
  50643. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  50644. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  50645. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  50646. }
  50647. else {
  50648. var offsetX = evt.clientX - cacheSoloPointer.x;
  50649. var offsetY = evt.clientY - cacheSoloPointer.y;
  50650. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  50651. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  50652. }
  50653. cacheSoloPointer.x = evt.clientX;
  50654. cacheSoloPointer.y = evt.clientY;
  50655. }
  50656. // Two buttons down: pinch/pan
  50657. else if (pointA && pointB) {
  50658. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  50659. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  50660. ed.x = evt.clientX;
  50661. ed.y = evt.clientY;
  50662. var direction = _this.pinchInwards ? 1 : -1;
  50663. var distX = pointA.x - pointB.x;
  50664. var distY = pointA.y - pointB.y;
  50665. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  50666. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  50667. if (previousPinchSquaredDistance === 0) {
  50668. initialDistance = pinchDistance;
  50669. previousPinchSquaredDistance = pinchSquaredDistance;
  50670. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  50671. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  50672. return;
  50673. }
  50674. if (_this.multiTouchPanAndZoom) {
  50675. if (_this.pinchDeltaPercentage) {
  50676. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  50677. }
  50678. else {
  50679. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  50680. (_this.pinchPrecision *
  50681. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  50682. direction);
  50683. }
  50684. if (_this.panningSensibility !== 0) {
  50685. var pointersCenterX = (pointA.x + pointB.x) / 2;
  50686. var pointersCenterY = (pointA.y + pointB.y) / 2;
  50687. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  50688. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  50689. previousMultiTouchPanPosition.x = pointersCenterX;
  50690. previousMultiTouchPanPosition.y = pointersCenterY;
  50691. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  50692. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  50693. }
  50694. }
  50695. else {
  50696. twoFingerActivityCount++;
  50697. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  50698. if (_this.pinchDeltaPercentage) {
  50699. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  50700. }
  50701. else {
  50702. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  50703. (_this.pinchPrecision *
  50704. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  50705. direction);
  50706. }
  50707. previousMultiTouchPanPosition.isPaning = false;
  50708. previousMultiTouchPanPosition.isPinching = true;
  50709. }
  50710. else {
  50711. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  50712. if (!previousMultiTouchPanPosition.isPaning) {
  50713. previousMultiTouchPanPosition.isPaning = true;
  50714. previousMultiTouchPanPosition.isPinching = false;
  50715. previousMultiTouchPanPosition.x = ed.x;
  50716. previousMultiTouchPanPosition.y = ed.y;
  50717. return;
  50718. }
  50719. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  50720. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  50721. }
  50722. }
  50723. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  50724. previousMultiTouchPanPosition.x = ed.x;
  50725. previousMultiTouchPanPosition.y = ed.y;
  50726. }
  50727. }
  50728. previousPinchSquaredDistance = pinchSquaredDistance;
  50729. }
  50730. }
  50731. };
  50732. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  50733. this._onContextMenu = function (evt) {
  50734. evt.preventDefault();
  50735. };
  50736. if (!this.camera._useCtrlForPanning) {
  50737. element.addEventListener("contextmenu", this._onContextMenu, false);
  50738. }
  50739. this._onLostFocus = function () {
  50740. //this._keys = [];
  50741. pointA = pointB = null;
  50742. previousPinchSquaredDistance = 0;
  50743. previousMultiTouchPanPosition.isPaning = false;
  50744. previousMultiTouchPanPosition.isPinching = false;
  50745. twoFingerActivityCount = 0;
  50746. cacheSoloPointer = null;
  50747. initialDistance = 0;
  50748. };
  50749. this._onMouseMove = function (evt) {
  50750. if (!engine.isPointerLock) {
  50751. return;
  50752. }
  50753. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  50754. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  50755. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  50756. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  50757. if (!noPreventDefault) {
  50758. evt.preventDefault();
  50759. }
  50760. };
  50761. this._onGestureStart = function (e) {
  50762. if (window.MSGesture === undefined) {
  50763. return;
  50764. }
  50765. if (!_this._MSGestureHandler) {
  50766. _this._MSGestureHandler = new MSGesture();
  50767. _this._MSGestureHandler.target = element;
  50768. }
  50769. _this._MSGestureHandler.addPointer(e.pointerId);
  50770. };
  50771. this._onGesture = function (e) {
  50772. _this.camera.radius *= e.scale;
  50773. if (e.preventDefault) {
  50774. if (!noPreventDefault) {
  50775. e.stopPropagation();
  50776. e.preventDefault();
  50777. }
  50778. }
  50779. };
  50780. element.addEventListener("mousemove", this._onMouseMove, false);
  50781. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  50782. element.addEventListener("MSGestureChange", this._onGesture, false);
  50783. BABYLON.Tools.RegisterTopRootEvents([
  50784. { name: "blur", handler: this._onLostFocus }
  50785. ]);
  50786. };
  50787. /**
  50788. * Detach the current controls from the specified dom element.
  50789. * @param element Defines the element to stop listening the inputs from
  50790. */
  50791. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  50792. if (this._onLostFocus) {
  50793. BABYLON.Tools.UnregisterTopRootEvents([
  50794. { name: "blur", handler: this._onLostFocus }
  50795. ]);
  50796. }
  50797. if (element && this._observer) {
  50798. this.camera.getScene().onPointerObservable.remove(this._observer);
  50799. this._observer = null;
  50800. if (this._onContextMenu) {
  50801. element.removeEventListener("contextmenu", this._onContextMenu);
  50802. }
  50803. if (this._onMouseMove) {
  50804. element.removeEventListener("mousemove", this._onMouseMove);
  50805. }
  50806. if (this._onGestureStart) {
  50807. element.removeEventListener("MSPointerDown", this._onGestureStart);
  50808. }
  50809. if (this._onGesture) {
  50810. element.removeEventListener("MSGestureChange", this._onGesture);
  50811. }
  50812. this._isPanClick = false;
  50813. this.pinchInwards = true;
  50814. this._onMouseMove = null;
  50815. this._onGestureStart = null;
  50816. this._onGesture = null;
  50817. this._MSGestureHandler = null;
  50818. this._onLostFocus = null;
  50819. this._onContextMenu = null;
  50820. }
  50821. };
  50822. /**
  50823. * Gets the class name of the current intput.
  50824. * @returns the class name
  50825. */
  50826. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  50827. return "ArcRotateCameraPointersInput";
  50828. };
  50829. /**
  50830. * Get the friendly name associated with the input class.
  50831. * @returns the input friendly name
  50832. */
  50833. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  50834. return "pointers";
  50835. };
  50836. __decorate([
  50837. BABYLON.serialize()
  50838. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  50839. __decorate([
  50840. BABYLON.serialize()
  50841. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  50842. __decorate([
  50843. BABYLON.serialize()
  50844. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  50845. __decorate([
  50846. BABYLON.serialize()
  50847. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  50848. __decorate([
  50849. BABYLON.serialize()
  50850. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  50851. __decorate([
  50852. BABYLON.serialize()
  50853. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  50854. __decorate([
  50855. BABYLON.serialize()
  50856. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  50857. __decorate([
  50858. BABYLON.serialize()
  50859. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  50860. return ArcRotateCameraPointersInput;
  50861. }());
  50862. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  50863. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  50864. })(BABYLON || (BABYLON = {}));
  50865. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  50866. var BABYLON;
  50867. (function (BABYLON) {
  50868. /**
  50869. * Default Inputs manager for the ArcRotateCamera.
  50870. * It groups all the default supported inputs for ease of use.
  50871. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50872. */
  50873. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  50874. __extends(ArcRotateCameraInputsManager, _super);
  50875. /**
  50876. * Instantiates a new ArcRotateCameraInputsManager.
  50877. * @param camera Defines the camera the inputs belong to
  50878. */
  50879. function ArcRotateCameraInputsManager(camera) {
  50880. return _super.call(this, camera) || this;
  50881. }
  50882. /**
  50883. * Add mouse wheel input support to the input manager.
  50884. * @returns the current input manager
  50885. */
  50886. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  50887. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  50888. return this;
  50889. };
  50890. /**
  50891. * Add pointers input support to the input manager.
  50892. * @returns the current input manager
  50893. */
  50894. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  50895. this.add(new BABYLON.ArcRotateCameraPointersInput());
  50896. return this;
  50897. };
  50898. /**
  50899. * Add keyboard input support to the input manager.
  50900. * @returns the current input manager
  50901. */
  50902. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  50903. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  50904. return this;
  50905. };
  50906. /**
  50907. * Add orientation input support to the input manager.
  50908. * @returns the current input manager
  50909. */
  50910. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  50911. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  50912. return this;
  50913. };
  50914. return ArcRotateCameraInputsManager;
  50915. }(BABYLON.CameraInputsManager));
  50916. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  50917. })(BABYLON || (BABYLON = {}));
  50918. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  50919. var BABYLON;
  50920. (function (BABYLON) {
  50921. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  50922. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  50923. });
  50924. /**
  50925. * This represents an orbital type of camera.
  50926. *
  50927. * 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.
  50928. * 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.
  50929. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  50930. */
  50931. var ArcRotateCamera = /** @class */ (function (_super) {
  50932. __extends(ArcRotateCamera, _super);
  50933. /**
  50934. * Instantiates a new ArcRotateCamera in a given scene
  50935. * @param name Defines the name of the camera
  50936. * @param alpha Defines the camera rotation along the logitudinal axis
  50937. * @param beta Defines the camera rotation along the latitudinal axis
  50938. * @param radius Defines the camera distance from its target
  50939. * @param target Defines the camera target
  50940. * @param scene Defines the scene the camera belongs to
  50941. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  50942. */
  50943. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  50944. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  50945. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  50946. /**
  50947. * Current inertia value on the longitudinal axis.
  50948. * The bigger this number the longer it will take for the camera to stop.
  50949. */
  50950. _this.inertialAlphaOffset = 0;
  50951. /**
  50952. * Current inertia value on the latitudinal axis.
  50953. * The bigger this number the longer it will take for the camera to stop.
  50954. */
  50955. _this.inertialBetaOffset = 0;
  50956. /**
  50957. * Current inertia value on the radius axis.
  50958. * The bigger this number the longer it will take for the camera to stop.
  50959. */
  50960. _this.inertialRadiusOffset = 0;
  50961. /**
  50962. * Minimum allowed angle on the longitudinal axis.
  50963. * This can help limiting how the Camera is able to move in the scene.
  50964. */
  50965. _this.lowerAlphaLimit = null;
  50966. /**
  50967. * Maximum allowed angle on the longitudinal axis.
  50968. * This can help limiting how the Camera is able to move in the scene.
  50969. */
  50970. _this.upperAlphaLimit = null;
  50971. /**
  50972. * Minimum allowed angle on the latitudinal axis.
  50973. * This can help limiting how the Camera is able to move in the scene.
  50974. */
  50975. _this.lowerBetaLimit = 0.01;
  50976. /**
  50977. * Maximum allowed angle on the latitudinal axis.
  50978. * This can help limiting how the Camera is able to move in the scene.
  50979. */
  50980. _this.upperBetaLimit = Math.PI;
  50981. /**
  50982. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  50983. * This can help limiting how the Camera is able to move in the scene.
  50984. */
  50985. _this.lowerRadiusLimit = null;
  50986. /**
  50987. * Maximum allowed distance of the camera to the target (The camera can not get further).
  50988. * This can help limiting how the Camera is able to move in the scene.
  50989. */
  50990. _this.upperRadiusLimit = null;
  50991. /**
  50992. * Defines the current inertia value used during panning of the camera along the X axis.
  50993. */
  50994. _this.inertialPanningX = 0;
  50995. /**
  50996. * Defines the current inertia value used during panning of the camera along the Y axis.
  50997. */
  50998. _this.inertialPanningY = 0;
  50999. /**
  51000. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  51001. * Basically if your fingers moves away from more than this distance you will be considered
  51002. * in pinch mode.
  51003. */
  51004. _this.pinchToPanMaxDistance = 20;
  51005. /**
  51006. * Defines the maximum distance the camera can pan.
  51007. * This could help keeping the cammera always in your scene.
  51008. */
  51009. _this.panningDistanceLimit = null;
  51010. /**
  51011. * Defines the target of the camera before paning.
  51012. */
  51013. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  51014. /**
  51015. * Defines the value of the inertia used during panning.
  51016. * 0 would mean stop inertia and one would mean no decelleration at all.
  51017. */
  51018. _this.panningInertia = 0.9;
  51019. //-- end properties for backward compatibility for inputs
  51020. /**
  51021. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  51022. */
  51023. _this.zoomOnFactor = 1;
  51024. /**
  51025. * Defines a screen offset for the camera position.
  51026. */
  51027. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  51028. /**
  51029. * Allows the camera to be completely reversed.
  51030. * If false the camera can not arrive upside down.
  51031. */
  51032. _this.allowUpsideDown = true;
  51033. /**
  51034. * Define if double tap/click is used to restore the previously saved state of the camera.
  51035. */
  51036. _this.useInputToRestoreState = true;
  51037. /** @hidden */
  51038. _this._viewMatrix = new BABYLON.Matrix();
  51039. /**
  51040. * Defines the allowed panning axis.
  51041. */
  51042. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  51043. /**
  51044. * Observable triggered when the mesh target has been changed on the camera.
  51045. */
  51046. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  51047. /**
  51048. * Defines whether the camera should check collision with the objects oh the scene.
  51049. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  51050. */
  51051. _this.checkCollisions = false;
  51052. /**
  51053. * Defines the collision radius of the camera.
  51054. * This simulates a sphere around the camera.
  51055. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  51056. */
  51057. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51058. _this._previousPosition = BABYLON.Vector3.Zero();
  51059. _this._collisionVelocity = BABYLON.Vector3.Zero();
  51060. _this._newPosition = BABYLON.Vector3.Zero();
  51061. _this._computationVector = BABYLON.Vector3.Zero();
  51062. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  51063. if (collidedMesh === void 0) { collidedMesh = null; }
  51064. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  51065. newPosition.multiplyInPlace(_this._collider._radius);
  51066. }
  51067. if (!collidedMesh) {
  51068. _this._previousPosition.copyFrom(_this.position);
  51069. }
  51070. else {
  51071. _this.setPosition(newPosition);
  51072. if (_this.onCollide) {
  51073. _this.onCollide(collidedMesh);
  51074. }
  51075. }
  51076. // Recompute because of constraints
  51077. var cosa = Math.cos(_this.alpha);
  51078. var sina = Math.sin(_this.alpha);
  51079. var cosb = Math.cos(_this.beta);
  51080. var sinb = Math.sin(_this.beta);
  51081. if (sinb === 0) {
  51082. sinb = 0.0001;
  51083. }
  51084. var target = _this._getTargetPosition();
  51085. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  51086. target.addToRef(_this._computationVector, _this._newPosition);
  51087. _this.position.copyFrom(_this._newPosition);
  51088. var up = _this.upVector;
  51089. if (_this.allowUpsideDown && _this.beta < 0) {
  51090. up = up.clone();
  51091. up = up.negate();
  51092. }
  51093. _this._computeViewMatrix(_this.position, target, up);
  51094. _this._viewMatrix.addAtIndex(12, _this.targetScreenOffset.x);
  51095. _this._viewMatrix.addAtIndex(13, _this.targetScreenOffset.y);
  51096. _this._collisionTriggered = false;
  51097. };
  51098. _this._target = BABYLON.Vector3.Zero();
  51099. if (target) {
  51100. _this.setTarget(target);
  51101. }
  51102. _this.alpha = alpha;
  51103. _this.beta = beta;
  51104. _this.radius = radius;
  51105. _this.getViewMatrix();
  51106. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  51107. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  51108. return _this;
  51109. }
  51110. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  51111. /**
  51112. * Defines the target point of the camera.
  51113. * The camera looks towards it form the radius distance.
  51114. */
  51115. get: function () {
  51116. return this._target;
  51117. },
  51118. set: function (value) {
  51119. this.setTarget(value);
  51120. },
  51121. enumerable: true,
  51122. configurable: true
  51123. });
  51124. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  51125. //-- begin properties for backward compatibility for inputs
  51126. /**
  51127. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  51128. */
  51129. get: function () {
  51130. var pointers = this.inputs.attached["pointers"];
  51131. if (pointers) {
  51132. return pointers.angularSensibilityX;
  51133. }
  51134. return 0;
  51135. },
  51136. set: function (value) {
  51137. var pointers = this.inputs.attached["pointers"];
  51138. if (pointers) {
  51139. pointers.angularSensibilityX = value;
  51140. }
  51141. },
  51142. enumerable: true,
  51143. configurable: true
  51144. });
  51145. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  51146. /**
  51147. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  51148. */
  51149. get: function () {
  51150. var pointers = this.inputs.attached["pointers"];
  51151. if (pointers) {
  51152. return pointers.angularSensibilityY;
  51153. }
  51154. return 0;
  51155. },
  51156. set: function (value) {
  51157. var pointers = this.inputs.attached["pointers"];
  51158. if (pointers) {
  51159. pointers.angularSensibilityY = value;
  51160. }
  51161. },
  51162. enumerable: true,
  51163. configurable: true
  51164. });
  51165. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  51166. /**
  51167. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  51168. */
  51169. get: function () {
  51170. var pointers = this.inputs.attached["pointers"];
  51171. if (pointers) {
  51172. return pointers.pinchPrecision;
  51173. }
  51174. return 0;
  51175. },
  51176. set: function (value) {
  51177. var pointers = this.inputs.attached["pointers"];
  51178. if (pointers) {
  51179. pointers.pinchPrecision = value;
  51180. }
  51181. },
  51182. enumerable: true,
  51183. configurable: true
  51184. });
  51185. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  51186. /**
  51187. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  51188. * It will be used instead of pinchDeltaPrecision if different from 0.
  51189. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  51190. */
  51191. get: function () {
  51192. var pointers = this.inputs.attached["pointers"];
  51193. if (pointers) {
  51194. return pointers.pinchDeltaPercentage;
  51195. }
  51196. return 0;
  51197. },
  51198. set: function (value) {
  51199. var pointers = this.inputs.attached["pointers"];
  51200. if (pointers) {
  51201. pointers.pinchDeltaPercentage = value;
  51202. }
  51203. },
  51204. enumerable: true,
  51205. configurable: true
  51206. });
  51207. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  51208. /**
  51209. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  51210. */
  51211. get: function () {
  51212. var pointers = this.inputs.attached["pointers"];
  51213. if (pointers) {
  51214. return pointers.panningSensibility;
  51215. }
  51216. return 0;
  51217. },
  51218. set: function (value) {
  51219. var pointers = this.inputs.attached["pointers"];
  51220. if (pointers) {
  51221. pointers.panningSensibility = value;
  51222. }
  51223. },
  51224. enumerable: true,
  51225. configurable: true
  51226. });
  51227. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  51228. /**
  51229. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  51230. */
  51231. get: function () {
  51232. var keyboard = this.inputs.attached["keyboard"];
  51233. if (keyboard) {
  51234. return keyboard.keysUp;
  51235. }
  51236. return [];
  51237. },
  51238. set: function (value) {
  51239. var keyboard = this.inputs.attached["keyboard"];
  51240. if (keyboard) {
  51241. keyboard.keysUp = value;
  51242. }
  51243. },
  51244. enumerable: true,
  51245. configurable: true
  51246. });
  51247. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  51248. /**
  51249. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  51250. */
  51251. get: function () {
  51252. var keyboard = this.inputs.attached["keyboard"];
  51253. if (keyboard) {
  51254. return keyboard.keysDown;
  51255. }
  51256. return [];
  51257. },
  51258. set: function (value) {
  51259. var keyboard = this.inputs.attached["keyboard"];
  51260. if (keyboard) {
  51261. keyboard.keysDown = value;
  51262. }
  51263. },
  51264. enumerable: true,
  51265. configurable: true
  51266. });
  51267. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  51268. /**
  51269. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  51270. */
  51271. get: function () {
  51272. var keyboard = this.inputs.attached["keyboard"];
  51273. if (keyboard) {
  51274. return keyboard.keysLeft;
  51275. }
  51276. return [];
  51277. },
  51278. set: function (value) {
  51279. var keyboard = this.inputs.attached["keyboard"];
  51280. if (keyboard) {
  51281. keyboard.keysLeft = value;
  51282. }
  51283. },
  51284. enumerable: true,
  51285. configurable: true
  51286. });
  51287. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  51288. /**
  51289. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  51290. */
  51291. get: function () {
  51292. var keyboard = this.inputs.attached["keyboard"];
  51293. if (keyboard) {
  51294. return keyboard.keysRight;
  51295. }
  51296. return [];
  51297. },
  51298. set: function (value) {
  51299. var keyboard = this.inputs.attached["keyboard"];
  51300. if (keyboard) {
  51301. keyboard.keysRight = value;
  51302. }
  51303. },
  51304. enumerable: true,
  51305. configurable: true
  51306. });
  51307. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  51308. /**
  51309. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  51310. */
  51311. get: function () {
  51312. var mousewheel = this.inputs.attached["mousewheel"];
  51313. if (mousewheel) {
  51314. return mousewheel.wheelPrecision;
  51315. }
  51316. return 0;
  51317. },
  51318. set: function (value) {
  51319. var mousewheel = this.inputs.attached["mousewheel"];
  51320. if (mousewheel) {
  51321. mousewheel.wheelPrecision = value;
  51322. }
  51323. },
  51324. enumerable: true,
  51325. configurable: true
  51326. });
  51327. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  51328. /**
  51329. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  51330. * It will be used instead of pinchDeltaPrecision if different from 0.
  51331. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  51332. */
  51333. get: function () {
  51334. var mousewheel = this.inputs.attached["mousewheel"];
  51335. if (mousewheel) {
  51336. return mousewheel.wheelDeltaPercentage;
  51337. }
  51338. return 0;
  51339. },
  51340. set: function (value) {
  51341. var mousewheel = this.inputs.attached["mousewheel"];
  51342. if (mousewheel) {
  51343. mousewheel.wheelDeltaPercentage = value;
  51344. }
  51345. },
  51346. enumerable: true,
  51347. configurable: true
  51348. });
  51349. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  51350. /**
  51351. * Gets the bouncing behavior of the camera if it has been enabled.
  51352. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  51353. */
  51354. get: function () {
  51355. return this._bouncingBehavior;
  51356. },
  51357. enumerable: true,
  51358. configurable: true
  51359. });
  51360. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  51361. /**
  51362. * Defines if the bouncing behavior of the camera is enabled on the camera.
  51363. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  51364. */
  51365. get: function () {
  51366. return this._bouncingBehavior != null;
  51367. },
  51368. set: function (value) {
  51369. if (value === this.useBouncingBehavior) {
  51370. return;
  51371. }
  51372. if (value) {
  51373. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  51374. this.addBehavior(this._bouncingBehavior);
  51375. }
  51376. else if (this._bouncingBehavior) {
  51377. this.removeBehavior(this._bouncingBehavior);
  51378. this._bouncingBehavior = null;
  51379. }
  51380. },
  51381. enumerable: true,
  51382. configurable: true
  51383. });
  51384. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  51385. /**
  51386. * Gets the framing behavior of the camera if it has been enabled.
  51387. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  51388. */
  51389. get: function () {
  51390. return this._framingBehavior;
  51391. },
  51392. enumerable: true,
  51393. configurable: true
  51394. });
  51395. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  51396. /**
  51397. * Defines if the framing behavior of the camera is enabled on the camera.
  51398. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  51399. */
  51400. get: function () {
  51401. return this._framingBehavior != null;
  51402. },
  51403. set: function (value) {
  51404. if (value === this.useFramingBehavior) {
  51405. return;
  51406. }
  51407. if (value) {
  51408. this._framingBehavior = new BABYLON.FramingBehavior();
  51409. this.addBehavior(this._framingBehavior);
  51410. }
  51411. else if (this._framingBehavior) {
  51412. this.removeBehavior(this._framingBehavior);
  51413. this._framingBehavior = null;
  51414. }
  51415. },
  51416. enumerable: true,
  51417. configurable: true
  51418. });
  51419. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  51420. /**
  51421. * Gets the auto rotation behavior of the camera if it has been enabled.
  51422. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  51423. */
  51424. get: function () {
  51425. return this._autoRotationBehavior;
  51426. },
  51427. enumerable: true,
  51428. configurable: true
  51429. });
  51430. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  51431. /**
  51432. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  51433. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  51434. */
  51435. get: function () {
  51436. return this._autoRotationBehavior != null;
  51437. },
  51438. set: function (value) {
  51439. if (value === this.useAutoRotationBehavior) {
  51440. return;
  51441. }
  51442. if (value) {
  51443. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  51444. this.addBehavior(this._autoRotationBehavior);
  51445. }
  51446. else if (this._autoRotationBehavior) {
  51447. this.removeBehavior(this._autoRotationBehavior);
  51448. this._autoRotationBehavior = null;
  51449. }
  51450. },
  51451. enumerable: true,
  51452. configurable: true
  51453. });
  51454. // Cache
  51455. /** @hidden */
  51456. ArcRotateCamera.prototype._initCache = function () {
  51457. _super.prototype._initCache.call(this);
  51458. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  51459. this._cache.alpha = undefined;
  51460. this._cache.beta = undefined;
  51461. this._cache.radius = undefined;
  51462. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  51463. };
  51464. /** @hidden */
  51465. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  51466. if (!ignoreParentClass) {
  51467. _super.prototype._updateCache.call(this);
  51468. }
  51469. this._cache._target.copyFrom(this._getTargetPosition());
  51470. this._cache.alpha = this.alpha;
  51471. this._cache.beta = this.beta;
  51472. this._cache.radius = this.radius;
  51473. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  51474. };
  51475. ArcRotateCamera.prototype._getTargetPosition = function () {
  51476. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  51477. var pos = this._targetHost.absolutePosition;
  51478. if (this._targetBoundingCenter) {
  51479. pos.addToRef(this._targetBoundingCenter, this._target);
  51480. }
  51481. else {
  51482. this._target.copyFrom(pos);
  51483. }
  51484. }
  51485. var lockedTargetPosition = this._getLockedTargetPosition();
  51486. if (lockedTargetPosition) {
  51487. return lockedTargetPosition;
  51488. }
  51489. return this._target;
  51490. };
  51491. /**
  51492. * Stores the current state of the camera (alpha, beta, radius and target)
  51493. * @returns the camera itself
  51494. */
  51495. ArcRotateCamera.prototype.storeState = function () {
  51496. this._storedAlpha = this.alpha;
  51497. this._storedBeta = this.beta;
  51498. this._storedRadius = this.radius;
  51499. this._storedTarget = this._getTargetPosition().clone();
  51500. return _super.prototype.storeState.call(this);
  51501. };
  51502. /**
  51503. * @hidden
  51504. * Restored camera state. You must call storeState() first
  51505. */
  51506. ArcRotateCamera.prototype._restoreStateValues = function () {
  51507. if (!_super.prototype._restoreStateValues.call(this)) {
  51508. return false;
  51509. }
  51510. this.alpha = this._storedAlpha;
  51511. this.beta = this._storedBeta;
  51512. this.radius = this._storedRadius;
  51513. this.setTarget(this._storedTarget.clone());
  51514. this.inertialAlphaOffset = 0;
  51515. this.inertialBetaOffset = 0;
  51516. this.inertialRadiusOffset = 0;
  51517. this.inertialPanningX = 0;
  51518. this.inertialPanningY = 0;
  51519. return true;
  51520. };
  51521. // Synchronized
  51522. /** @hidden */
  51523. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  51524. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  51525. return false;
  51526. }
  51527. return this._cache._target.equals(this._getTargetPosition())
  51528. && this._cache.alpha === this.alpha
  51529. && this._cache.beta === this.beta
  51530. && this._cache.radius === this.radius
  51531. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  51532. };
  51533. /**
  51534. * Attached controls to the current camera.
  51535. * @param element Defines the element the controls should be listened from
  51536. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  51537. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  51538. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  51539. */
  51540. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  51541. var _this = this;
  51542. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  51543. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  51544. this._useCtrlForPanning = useCtrlForPanning;
  51545. this._panningMouseButton = panningMouseButton;
  51546. this.inputs.attachElement(element, noPreventDefault);
  51547. this._reset = function () {
  51548. _this.inertialAlphaOffset = 0;
  51549. _this.inertialBetaOffset = 0;
  51550. _this.inertialRadiusOffset = 0;
  51551. _this.inertialPanningX = 0;
  51552. _this.inertialPanningY = 0;
  51553. };
  51554. };
  51555. /**
  51556. * Detach the current controls from the camera.
  51557. * The camera will stop reacting to inputs.
  51558. * @param element Defines the element to stop listening the inputs from
  51559. */
  51560. ArcRotateCamera.prototype.detachControl = function (element) {
  51561. this.inputs.detachElement(element);
  51562. if (this._reset) {
  51563. this._reset();
  51564. }
  51565. };
  51566. /** @hidden */
  51567. ArcRotateCamera.prototype._checkInputs = function () {
  51568. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  51569. if (this._collisionTriggered) {
  51570. return;
  51571. }
  51572. this.inputs.checkInputs();
  51573. // Inertia
  51574. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  51575. var inertialAlphaOffset = this.inertialAlphaOffset;
  51576. if (this.beta <= 0) {
  51577. inertialAlphaOffset *= -1;
  51578. }
  51579. if (this.getScene().useRightHandedSystem) {
  51580. inertialAlphaOffset *= -1;
  51581. }
  51582. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
  51583. inertialAlphaOffset *= -1;
  51584. }
  51585. this.alpha += inertialAlphaOffset;
  51586. this.beta += this.inertialBetaOffset;
  51587. this.radius -= this.inertialRadiusOffset;
  51588. this.inertialAlphaOffset *= this.inertia;
  51589. this.inertialBetaOffset *= this.inertia;
  51590. this.inertialRadiusOffset *= this.inertia;
  51591. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon) {
  51592. this.inertialAlphaOffset = 0;
  51593. }
  51594. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon) {
  51595. this.inertialBetaOffset = 0;
  51596. }
  51597. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon) {
  51598. this.inertialRadiusOffset = 0;
  51599. }
  51600. }
  51601. // Panning inertia
  51602. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  51603. if (!this._localDirection) {
  51604. this._localDirection = BABYLON.Vector3.Zero();
  51605. this._transformedDirection = BABYLON.Vector3.Zero();
  51606. }
  51607. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  51608. this._localDirection.multiplyInPlace(this.panningAxis);
  51609. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  51610. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  51611. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  51612. if (!this.panningAxis.y) {
  51613. this._transformedDirection.y = 0;
  51614. }
  51615. if (!this._targetHost) {
  51616. if (this.panningDistanceLimit) {
  51617. this._transformedDirection.addInPlace(this._target);
  51618. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  51619. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  51620. this._target.copyFrom(this._transformedDirection);
  51621. }
  51622. }
  51623. else {
  51624. this._target.addInPlace(this._transformedDirection);
  51625. }
  51626. }
  51627. this.inertialPanningX *= this.panningInertia;
  51628. this.inertialPanningY *= this.panningInertia;
  51629. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon) {
  51630. this.inertialPanningX = 0;
  51631. }
  51632. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon) {
  51633. this.inertialPanningY = 0;
  51634. }
  51635. }
  51636. // Limits
  51637. this._checkLimits();
  51638. _super.prototype._checkInputs.call(this);
  51639. };
  51640. ArcRotateCamera.prototype._checkLimits = function () {
  51641. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  51642. if (this.allowUpsideDown && this.beta > Math.PI) {
  51643. this.beta = this.beta - (2 * Math.PI);
  51644. }
  51645. }
  51646. else {
  51647. if (this.beta < this.lowerBetaLimit) {
  51648. this.beta = this.lowerBetaLimit;
  51649. }
  51650. }
  51651. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  51652. if (this.allowUpsideDown && this.beta < -Math.PI) {
  51653. this.beta = this.beta + (2 * Math.PI);
  51654. }
  51655. }
  51656. else {
  51657. if (this.beta > this.upperBetaLimit) {
  51658. this.beta = this.upperBetaLimit;
  51659. }
  51660. }
  51661. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  51662. this.alpha = this.lowerAlphaLimit;
  51663. }
  51664. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  51665. this.alpha = this.upperAlphaLimit;
  51666. }
  51667. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  51668. this.radius = this.lowerRadiusLimit;
  51669. this.inertialRadiusOffset = 0;
  51670. }
  51671. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  51672. this.radius = this.upperRadiusLimit;
  51673. this.inertialRadiusOffset = 0;
  51674. }
  51675. };
  51676. /**
  51677. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  51678. */
  51679. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  51680. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  51681. this.radius = this._computationVector.length();
  51682. if (this.radius === 0) {
  51683. this.radius = 0.0001; // Just to avoid division by zero
  51684. }
  51685. // Alpha
  51686. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  51687. if (this._computationVector.z < 0) {
  51688. this.alpha = 2 * Math.PI - this.alpha;
  51689. }
  51690. // Beta
  51691. this.beta = Math.acos(this._computationVector.y / this.radius);
  51692. this._checkLimits();
  51693. };
  51694. /**
  51695. * Use a position to define the current camera related information like aplha, beta and radius
  51696. * @param position Defines the position to set the camera at
  51697. */
  51698. ArcRotateCamera.prototype.setPosition = function (position) {
  51699. if (this.position.equals(position)) {
  51700. return;
  51701. }
  51702. this.position.copyFrom(position);
  51703. this.rebuildAnglesAndRadius();
  51704. };
  51705. /**
  51706. * Defines the target the camera should look at.
  51707. * This will automatically adapt alpha beta and radius to fit within the new target.
  51708. * @param target Defines the new target as a Vector or a mesh
  51709. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  51710. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  51711. */
  51712. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  51713. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  51714. if (allowSamePosition === void 0) { allowSamePosition = false; }
  51715. if (target.getBoundingInfo) {
  51716. if (toBoundingCenter) {
  51717. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  51718. }
  51719. else {
  51720. this._targetBoundingCenter = null;
  51721. }
  51722. this._targetHost = target;
  51723. this._target = this._getTargetPosition();
  51724. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  51725. }
  51726. else {
  51727. var newTarget = target;
  51728. var currentTarget = this._getTargetPosition();
  51729. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  51730. return;
  51731. }
  51732. this._targetHost = null;
  51733. this._target = newTarget;
  51734. this._targetBoundingCenter = null;
  51735. this.onMeshTargetChangedObservable.notifyObservers(null);
  51736. }
  51737. this.rebuildAnglesAndRadius();
  51738. };
  51739. /** @hidden */
  51740. ArcRotateCamera.prototype._getViewMatrix = function () {
  51741. // Compute
  51742. var cosa = Math.cos(this.alpha);
  51743. var sina = Math.sin(this.alpha);
  51744. var cosb = Math.cos(this.beta);
  51745. var sinb = Math.sin(this.beta);
  51746. if (sinb === 0) {
  51747. sinb = 0.0001;
  51748. }
  51749. var target = this._getTargetPosition();
  51750. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  51751. target.addToRef(this._computationVector, this._newPosition);
  51752. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  51753. if (!this._collider) {
  51754. this._collider = new BABYLON.Collider();
  51755. }
  51756. this._collider._radius = this.collisionRadius;
  51757. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  51758. this._collisionTriggered = true;
  51759. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  51760. }
  51761. else {
  51762. this.position.copyFrom(this._newPosition);
  51763. var up = this.upVector;
  51764. if (this.allowUpsideDown && sinb < 0) {
  51765. up = up.clone();
  51766. up = up.negate();
  51767. }
  51768. this._computeViewMatrix(this.position, target, up);
  51769. this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);
  51770. this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);
  51771. }
  51772. this._currentTarget = target;
  51773. return this._viewMatrix;
  51774. };
  51775. /**
  51776. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  51777. * @param meshes Defines the mesh to zoom on
  51778. * @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)
  51779. */
  51780. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  51781. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  51782. meshes = meshes || this.getScene().meshes;
  51783. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  51784. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  51785. this.radius = distance * this.zoomOnFactor;
  51786. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  51787. };
  51788. /**
  51789. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  51790. * The target will be changed but the radius
  51791. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  51792. * @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)
  51793. */
  51794. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  51795. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  51796. var meshesOrMinMaxVector;
  51797. var distance;
  51798. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  51799. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  51800. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  51801. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  51802. }
  51803. else { //minMaxVector and distance
  51804. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  51805. meshesOrMinMaxVector = minMaxVectorAndDistance;
  51806. distance = minMaxVectorAndDistance.distance;
  51807. }
  51808. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  51809. if (!doNotUpdateMaxZ) {
  51810. this.maxZ = distance * 2;
  51811. }
  51812. };
  51813. /**
  51814. * @override
  51815. * Override Camera.createRigCamera
  51816. */
  51817. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  51818. var alphaShift = 0;
  51819. switch (this.cameraRigMode) {
  51820. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  51821. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  51822. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  51823. case BABYLON.Camera.RIG_MODE_VR:
  51824. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  51825. break;
  51826. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  51827. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  51828. break;
  51829. }
  51830. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  51831. rigCam._cameraRigParams = {};
  51832. return rigCam;
  51833. };
  51834. /**
  51835. * @hidden
  51836. * @override
  51837. * Override Camera._updateRigCameras
  51838. */
  51839. ArcRotateCamera.prototype._updateRigCameras = function () {
  51840. var camLeft = this._rigCameras[0];
  51841. var camRight = this._rigCameras[1];
  51842. camLeft.beta = camRight.beta = this.beta;
  51843. camLeft.radius = camRight.radius = this.radius;
  51844. switch (this.cameraRigMode) {
  51845. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  51846. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  51847. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  51848. case BABYLON.Camera.RIG_MODE_VR:
  51849. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  51850. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  51851. break;
  51852. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  51853. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  51854. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  51855. break;
  51856. }
  51857. _super.prototype._updateRigCameras.call(this);
  51858. };
  51859. /**
  51860. * Destroy the camera and release the current resources hold by it.
  51861. */
  51862. ArcRotateCamera.prototype.dispose = function () {
  51863. this.inputs.clear();
  51864. _super.prototype.dispose.call(this);
  51865. };
  51866. /**
  51867. * Gets the current object class name.
  51868. * @return the class name
  51869. */
  51870. ArcRotateCamera.prototype.getClassName = function () {
  51871. return "ArcRotateCamera";
  51872. };
  51873. __decorate([
  51874. BABYLON.serialize()
  51875. ], ArcRotateCamera.prototype, "alpha", void 0);
  51876. __decorate([
  51877. BABYLON.serialize()
  51878. ], ArcRotateCamera.prototype, "beta", void 0);
  51879. __decorate([
  51880. BABYLON.serialize()
  51881. ], ArcRotateCamera.prototype, "radius", void 0);
  51882. __decorate([
  51883. BABYLON.serializeAsVector3("target")
  51884. ], ArcRotateCamera.prototype, "_target", void 0);
  51885. __decorate([
  51886. BABYLON.serialize()
  51887. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  51888. __decorate([
  51889. BABYLON.serialize()
  51890. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  51891. __decorate([
  51892. BABYLON.serialize()
  51893. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  51894. __decorate([
  51895. BABYLON.serialize()
  51896. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  51897. __decorate([
  51898. BABYLON.serialize()
  51899. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  51900. __decorate([
  51901. BABYLON.serialize()
  51902. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  51903. __decorate([
  51904. BABYLON.serialize()
  51905. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  51906. __decorate([
  51907. BABYLON.serialize()
  51908. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  51909. __decorate([
  51910. BABYLON.serialize()
  51911. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  51912. __decorate([
  51913. BABYLON.serialize()
  51914. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  51915. __decorate([
  51916. BABYLON.serialize()
  51917. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  51918. __decorate([
  51919. BABYLON.serialize()
  51920. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  51921. __decorate([
  51922. BABYLON.serialize()
  51923. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  51924. __decorate([
  51925. BABYLON.serializeAsVector3()
  51926. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  51927. __decorate([
  51928. BABYLON.serialize()
  51929. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  51930. __decorate([
  51931. BABYLON.serialize()
  51932. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  51933. __decorate([
  51934. BABYLON.serialize()
  51935. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  51936. __decorate([
  51937. BABYLON.serialize()
  51938. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  51939. __decorate([
  51940. BABYLON.serialize()
  51941. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  51942. return ArcRotateCamera;
  51943. }(BABYLON.TargetCamera));
  51944. BABYLON.ArcRotateCamera = ArcRotateCamera;
  51945. })(BABYLON || (BABYLON = {}));
  51946. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  51947. var BABYLON;
  51948. (function (BABYLON) {
  51949. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  51950. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  51951. });
  51952. /**
  51953. * The HemisphericLight simulates the ambient environment light,
  51954. * so the passed direction is the light reflection direction, not the incoming direction.
  51955. */
  51956. var HemisphericLight = /** @class */ (function (_super) {
  51957. __extends(HemisphericLight, _super);
  51958. /**
  51959. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  51960. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  51961. * The HemisphericLight can't cast shadows.
  51962. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51963. * @param name The friendly name of the light
  51964. * @param direction The direction of the light reflection
  51965. * @param scene The scene the light belongs to
  51966. */
  51967. function HemisphericLight(name, direction, scene) {
  51968. var _this = _super.call(this, name, scene) || this;
  51969. /**
  51970. * The groundColor is the light in the opposite direction to the one specified during creation.
  51971. * 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.
  51972. */
  51973. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  51974. _this.direction = direction || BABYLON.Vector3.Up();
  51975. return _this;
  51976. }
  51977. HemisphericLight.prototype._buildUniformLayout = function () {
  51978. this._uniformBuffer.addUniform("vLightData", 4);
  51979. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51980. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51981. this._uniformBuffer.addUniform("vLightGround", 3);
  51982. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51983. this._uniformBuffer.addUniform("depthValues", 2);
  51984. this._uniformBuffer.create();
  51985. };
  51986. /**
  51987. * Returns the string "HemisphericLight".
  51988. * @return The class name
  51989. */
  51990. HemisphericLight.prototype.getClassName = function () {
  51991. return "HemisphericLight";
  51992. };
  51993. /**
  51994. * Sets the HemisphericLight direction towards the passed target (Vector3).
  51995. * Returns the updated direction.
  51996. * @param target The target the direction should point to
  51997. * @return The computed direction
  51998. */
  51999. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  52000. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  52001. return this.direction;
  52002. };
  52003. /**
  52004. * Returns the shadow generator associated to the light.
  52005. * @returns Always null for hemispheric lights because it does not support shadows.
  52006. */
  52007. HemisphericLight.prototype.getShadowGenerator = function () {
  52008. return null;
  52009. };
  52010. /**
  52011. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  52012. * @param effect The effect to update
  52013. * @param lightIndex The index of the light in the effect to update
  52014. * @returns The hemispheric light
  52015. */
  52016. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  52017. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  52018. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  52019. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  52020. return this;
  52021. };
  52022. /**
  52023. * Computes the world matrix of the node
  52024. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  52025. * @param useWasUpdatedFlag defines a reserved property
  52026. * @returns the world matrix
  52027. */
  52028. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  52029. if (!this._worldMatrix) {
  52030. this._worldMatrix = BABYLON.Matrix.Identity();
  52031. }
  52032. return this._worldMatrix;
  52033. };
  52034. /**
  52035. * Returns the integer 3.
  52036. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52037. */
  52038. HemisphericLight.prototype.getTypeID = function () {
  52039. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  52040. };
  52041. /**
  52042. * Prepares the list of defines specific to the light type.
  52043. * @param defines the list of defines
  52044. * @param lightIndex defines the index of the light for the effect
  52045. */
  52046. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52047. defines["HEMILIGHT" + lightIndex] = true;
  52048. };
  52049. __decorate([
  52050. BABYLON.serializeAsColor3()
  52051. ], HemisphericLight.prototype, "groundColor", void 0);
  52052. __decorate([
  52053. BABYLON.serializeAsVector3()
  52054. ], HemisphericLight.prototype, "direction", void 0);
  52055. return HemisphericLight;
  52056. }(BABYLON.Light));
  52057. BABYLON.HemisphericLight = HemisphericLight;
  52058. })(BABYLON || (BABYLON = {}));
  52059. //# sourceMappingURL=babylon.hemisphericLight.js.map
  52060. var BABYLON;
  52061. (function (BABYLON) {
  52062. /**
  52063. * Base implementation IShadowLight
  52064. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  52065. */
  52066. var ShadowLight = /** @class */ (function (_super) {
  52067. __extends(ShadowLight, _super);
  52068. function ShadowLight() {
  52069. var _this = _super !== null && _super.apply(this, arguments) || this;
  52070. _this._needProjectionMatrixCompute = true;
  52071. return _this;
  52072. }
  52073. ShadowLight.prototype._setPosition = function (value) {
  52074. this._position = value;
  52075. };
  52076. Object.defineProperty(ShadowLight.prototype, "position", {
  52077. /**
  52078. * Sets the position the shadow will be casted from. Also use as the light position for both
  52079. * point and spot lights.
  52080. */
  52081. get: function () {
  52082. return this._position;
  52083. },
  52084. /**
  52085. * Sets the position the shadow will be casted from. Also use as the light position for both
  52086. * point and spot lights.
  52087. */
  52088. set: function (value) {
  52089. this._setPosition(value);
  52090. },
  52091. enumerable: true,
  52092. configurable: true
  52093. });
  52094. ShadowLight.prototype._setDirection = function (value) {
  52095. this._direction = value;
  52096. };
  52097. Object.defineProperty(ShadowLight.prototype, "direction", {
  52098. /**
  52099. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  52100. * Also use as the light direction on spot and directional lights.
  52101. */
  52102. get: function () {
  52103. return this._direction;
  52104. },
  52105. /**
  52106. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  52107. * Also use as the light direction on spot and directional lights.
  52108. */
  52109. set: function (value) {
  52110. this._setDirection(value);
  52111. },
  52112. enumerable: true,
  52113. configurable: true
  52114. });
  52115. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  52116. /**
  52117. * Gets the shadow projection clipping minimum z value.
  52118. */
  52119. get: function () {
  52120. return this._shadowMinZ;
  52121. },
  52122. /**
  52123. * Sets the shadow projection clipping minimum z value.
  52124. */
  52125. set: function (value) {
  52126. this._shadowMinZ = value;
  52127. this.forceProjectionMatrixCompute();
  52128. },
  52129. enumerable: true,
  52130. configurable: true
  52131. });
  52132. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  52133. /**
  52134. * Sets the shadow projection clipping maximum z value.
  52135. */
  52136. get: function () {
  52137. return this._shadowMaxZ;
  52138. },
  52139. /**
  52140. * Gets the shadow projection clipping maximum z value.
  52141. */
  52142. set: function (value) {
  52143. this._shadowMaxZ = value;
  52144. this.forceProjectionMatrixCompute();
  52145. },
  52146. enumerable: true,
  52147. configurable: true
  52148. });
  52149. /**
  52150. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  52151. * @returns true if the information has been computed, false if it does not need to (no parenting)
  52152. */
  52153. ShadowLight.prototype.computeTransformedInformation = function () {
  52154. if (this.parent && this.parent.getWorldMatrix) {
  52155. if (!this.transformedPosition) {
  52156. this.transformedPosition = BABYLON.Vector3.Zero();
  52157. }
  52158. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  52159. // In case the direction is present.
  52160. if (this.direction) {
  52161. if (!this.transformedDirection) {
  52162. this.transformedDirection = BABYLON.Vector3.Zero();
  52163. }
  52164. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  52165. }
  52166. return true;
  52167. }
  52168. return false;
  52169. };
  52170. /**
  52171. * Return the depth scale used for the shadow map.
  52172. * @returns the depth scale.
  52173. */
  52174. ShadowLight.prototype.getDepthScale = function () {
  52175. return 50.0;
  52176. };
  52177. /**
  52178. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  52179. * @param faceIndex The index of the face we are computed the direction to generate shadow
  52180. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  52181. */
  52182. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  52183. return this.transformedDirection ? this.transformedDirection : this.direction;
  52184. };
  52185. /**
  52186. * Returns the ShadowLight absolute position in the World.
  52187. * @returns the position vector in world space
  52188. */
  52189. ShadowLight.prototype.getAbsolutePosition = function () {
  52190. return this.transformedPosition ? this.transformedPosition : this.position;
  52191. };
  52192. /**
  52193. * Sets the ShadowLight direction toward the passed target.
  52194. * @param target The point tot target in local space
  52195. * @returns the updated ShadowLight direction
  52196. */
  52197. ShadowLight.prototype.setDirectionToTarget = function (target) {
  52198. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  52199. return this.direction;
  52200. };
  52201. /**
  52202. * Returns the light rotation in euler definition.
  52203. * @returns the x y z rotation in local space.
  52204. */
  52205. ShadowLight.prototype.getRotation = function () {
  52206. this.direction.normalize();
  52207. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  52208. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  52209. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  52210. };
  52211. /**
  52212. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  52213. * @returns true if a cube texture needs to be use
  52214. */
  52215. ShadowLight.prototype.needCube = function () {
  52216. return false;
  52217. };
  52218. /**
  52219. * Detects if the projection matrix requires to be recomputed this frame.
  52220. * @returns true if it requires to be recomputed otherwise, false.
  52221. */
  52222. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  52223. return this._needProjectionMatrixCompute;
  52224. };
  52225. /**
  52226. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  52227. */
  52228. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  52229. this._needProjectionMatrixCompute = true;
  52230. };
  52231. /** @hidden */
  52232. ShadowLight.prototype._initCache = function () {
  52233. _super.prototype._initCache.call(this);
  52234. this._cache.position = BABYLON.Vector3.Zero();
  52235. };
  52236. /** @hidden */
  52237. ShadowLight.prototype._isSynchronized = function () {
  52238. if (!this._cache.position.equals(this.position)) {
  52239. return false;
  52240. }
  52241. return true;
  52242. };
  52243. /**
  52244. * Computes the world matrix of the node
  52245. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  52246. * @returns the world matrix
  52247. */
  52248. ShadowLight.prototype.computeWorldMatrix = function (force) {
  52249. if (!force && this.isSynchronized()) {
  52250. this._currentRenderId = this.getScene().getRenderId();
  52251. return this._worldMatrix;
  52252. }
  52253. this._updateCache();
  52254. this._cache.position.copyFrom(this.position);
  52255. if (!this._worldMatrix) {
  52256. this._worldMatrix = BABYLON.Matrix.Identity();
  52257. }
  52258. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  52259. if (this.parent && this.parent.getWorldMatrix) {
  52260. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  52261. this._markSyncedWithParent();
  52262. }
  52263. // Cache the determinant
  52264. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  52265. return this._worldMatrix;
  52266. };
  52267. /**
  52268. * Gets the minZ used for shadow according to both the scene and the light.
  52269. * @param activeCamera The camera we are returning the min for
  52270. * @returns the depth min z
  52271. */
  52272. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  52273. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  52274. };
  52275. /**
  52276. * Gets the maxZ used for shadow according to both the scene and the light.
  52277. * @param activeCamera The camera we are returning the max for
  52278. * @returns the depth max z
  52279. */
  52280. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  52281. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  52282. };
  52283. /**
  52284. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  52285. * @param matrix The materix to updated with the projection information
  52286. * @param viewMatrix The transform matrix of the light
  52287. * @param renderList The list of mesh to render in the map
  52288. * @returns The current light
  52289. */
  52290. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52291. if (this.customProjectionMatrixBuilder) {
  52292. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  52293. }
  52294. else {
  52295. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  52296. }
  52297. return this;
  52298. };
  52299. __decorate([
  52300. BABYLON.serializeAsVector3()
  52301. ], ShadowLight.prototype, "position", null);
  52302. __decorate([
  52303. BABYLON.serializeAsVector3()
  52304. ], ShadowLight.prototype, "direction", null);
  52305. __decorate([
  52306. BABYLON.serialize()
  52307. ], ShadowLight.prototype, "shadowMinZ", null);
  52308. __decorate([
  52309. BABYLON.serialize()
  52310. ], ShadowLight.prototype, "shadowMaxZ", null);
  52311. return ShadowLight;
  52312. }(BABYLON.Light));
  52313. BABYLON.ShadowLight = ShadowLight;
  52314. })(BABYLON || (BABYLON = {}));
  52315. //# sourceMappingURL=babylon.shadowLight.js.map
  52316. var BABYLON;
  52317. (function (BABYLON) {
  52318. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  52319. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  52320. });
  52321. /**
  52322. * A point light is a light defined by an unique point in world space.
  52323. * The light is emitted in every direction from this point.
  52324. * A good example of a point light is a standard light bulb.
  52325. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52326. */
  52327. var PointLight = /** @class */ (function (_super) {
  52328. __extends(PointLight, _super);
  52329. /**
  52330. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  52331. * A PointLight emits the light in every direction.
  52332. * It can cast shadows.
  52333. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  52334. * ```javascript
  52335. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  52336. * ```
  52337. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52338. * @param name The light friendly name
  52339. * @param position The position of the point light in the scene
  52340. * @param scene The scene the lights belongs to
  52341. */
  52342. function PointLight(name, position, scene) {
  52343. var _this = _super.call(this, name, scene) || this;
  52344. _this._shadowAngle = Math.PI / 2;
  52345. _this.position = position;
  52346. return _this;
  52347. }
  52348. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  52349. /**
  52350. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52351. * This specifies what angle the shadow will use to be created.
  52352. *
  52353. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  52354. */
  52355. get: function () {
  52356. return this._shadowAngle;
  52357. },
  52358. /**
  52359. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52360. * This specifies what angle the shadow will use to be created.
  52361. *
  52362. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  52363. */
  52364. set: function (value) {
  52365. this._shadowAngle = value;
  52366. this.forceProjectionMatrixCompute();
  52367. },
  52368. enumerable: true,
  52369. configurable: true
  52370. });
  52371. Object.defineProperty(PointLight.prototype, "direction", {
  52372. /**
  52373. * Gets the direction if it has been set.
  52374. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52375. */
  52376. get: function () {
  52377. return this._direction;
  52378. },
  52379. /**
  52380. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52381. */
  52382. set: function (value) {
  52383. var previousNeedCube = this.needCube();
  52384. this._direction = value;
  52385. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  52386. this._shadowGenerator.recreateShadowMap();
  52387. }
  52388. },
  52389. enumerable: true,
  52390. configurable: true
  52391. });
  52392. /**
  52393. * Returns the string "PointLight"
  52394. * @returns the class name
  52395. */
  52396. PointLight.prototype.getClassName = function () {
  52397. return "PointLight";
  52398. };
  52399. /**
  52400. * Returns the integer 0.
  52401. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52402. */
  52403. PointLight.prototype.getTypeID = function () {
  52404. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  52405. };
  52406. /**
  52407. * Specifies wether or not the shadowmap should be a cube texture.
  52408. * @returns true if the shadowmap needs to be a cube texture.
  52409. */
  52410. PointLight.prototype.needCube = function () {
  52411. return !this.direction;
  52412. };
  52413. /**
  52414. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  52415. * @param faceIndex The index of the face we are computed the direction to generate shadow
  52416. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  52417. */
  52418. PointLight.prototype.getShadowDirection = function (faceIndex) {
  52419. if (this.direction) {
  52420. return _super.prototype.getShadowDirection.call(this, faceIndex);
  52421. }
  52422. else {
  52423. switch (faceIndex) {
  52424. case 0:
  52425. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  52426. case 1:
  52427. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  52428. case 2:
  52429. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  52430. case 3:
  52431. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  52432. case 4:
  52433. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  52434. case 5:
  52435. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  52436. }
  52437. }
  52438. return BABYLON.Vector3.Zero();
  52439. };
  52440. /**
  52441. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  52442. * - fov = PI / 2
  52443. * - aspect ratio : 1.0
  52444. * - z-near and far equal to the active camera minZ and maxZ.
  52445. * Returns the PointLight.
  52446. */
  52447. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52448. var activeCamera = this.getScene().activeCamera;
  52449. if (!activeCamera) {
  52450. return;
  52451. }
  52452. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  52453. };
  52454. PointLight.prototype._buildUniformLayout = function () {
  52455. this._uniformBuffer.addUniform("vLightData", 4);
  52456. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52457. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52458. this._uniformBuffer.addUniform("vLightFalloff", 4);
  52459. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52460. this._uniformBuffer.addUniform("depthValues", 2);
  52461. this._uniformBuffer.create();
  52462. };
  52463. /**
  52464. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  52465. * @param effect The effect to update
  52466. * @param lightIndex The index of the light in the effect to update
  52467. * @returns The point light
  52468. */
  52469. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  52470. if (this.computeTransformedInformation()) {
  52471. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  52472. }
  52473. else {
  52474. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  52475. }
  52476. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  52477. return this;
  52478. };
  52479. /**
  52480. * Prepares the list of defines specific to the light type.
  52481. * @param defines the list of defines
  52482. * @param lightIndex defines the index of the light for the effect
  52483. */
  52484. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52485. defines["POINTLIGHT" + lightIndex] = true;
  52486. };
  52487. __decorate([
  52488. BABYLON.serialize()
  52489. ], PointLight.prototype, "shadowAngle", null);
  52490. return PointLight;
  52491. }(BABYLON.ShadowLight));
  52492. BABYLON.PointLight = PointLight;
  52493. })(BABYLON || (BABYLON = {}));
  52494. //# sourceMappingURL=babylon.pointLight.js.map
  52495. var BABYLON;
  52496. (function (BABYLON) {
  52497. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  52498. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  52499. });
  52500. /**
  52501. * A directional light is defined by a direction (what a surprise!).
  52502. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  52503. * 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.
  52504. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52505. */
  52506. var DirectionalLight = /** @class */ (function (_super) {
  52507. __extends(DirectionalLight, _super);
  52508. /**
  52509. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  52510. * The directional light is emitted from everywhere in the given direction.
  52511. * It can cast shadows.
  52512. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52513. * @param name The friendly name of the light
  52514. * @param direction The direction of the light
  52515. * @param scene The scene the light belongs to
  52516. */
  52517. function DirectionalLight(name, direction, scene) {
  52518. var _this = _super.call(this, name, scene) || this;
  52519. _this._shadowFrustumSize = 0;
  52520. _this._shadowOrthoScale = 0.1;
  52521. /**
  52522. * Automatically compute the projection matrix to best fit (including all the casters)
  52523. * on each frame.
  52524. */
  52525. _this.autoUpdateExtends = true;
  52526. // Cache
  52527. _this._orthoLeft = Number.MAX_VALUE;
  52528. _this._orthoRight = Number.MIN_VALUE;
  52529. _this._orthoTop = Number.MIN_VALUE;
  52530. _this._orthoBottom = Number.MAX_VALUE;
  52531. _this.position = direction.scale(-1.0);
  52532. _this.direction = direction;
  52533. return _this;
  52534. }
  52535. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  52536. /**
  52537. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  52538. */
  52539. get: function () {
  52540. return this._shadowFrustumSize;
  52541. },
  52542. /**
  52543. * Specifies a fix frustum size for the shadow generation.
  52544. */
  52545. set: function (value) {
  52546. this._shadowFrustumSize = value;
  52547. this.forceProjectionMatrixCompute();
  52548. },
  52549. enumerable: true,
  52550. configurable: true
  52551. });
  52552. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  52553. /**
  52554. * Gets the shadow projection scale against the optimal computed one.
  52555. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  52556. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  52557. */
  52558. get: function () {
  52559. return this._shadowOrthoScale;
  52560. },
  52561. /**
  52562. * Sets the shadow projection scale against the optimal computed one.
  52563. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  52564. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  52565. */
  52566. set: function (value) {
  52567. this._shadowOrthoScale = value;
  52568. this.forceProjectionMatrixCompute();
  52569. },
  52570. enumerable: true,
  52571. configurable: true
  52572. });
  52573. /**
  52574. * Returns the string "DirectionalLight".
  52575. * @return The class name
  52576. */
  52577. DirectionalLight.prototype.getClassName = function () {
  52578. return "DirectionalLight";
  52579. };
  52580. /**
  52581. * Returns the integer 1.
  52582. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52583. */
  52584. DirectionalLight.prototype.getTypeID = function () {
  52585. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  52586. };
  52587. /**
  52588. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  52589. * Returns the DirectionalLight Shadow projection matrix.
  52590. */
  52591. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52592. if (this.shadowFrustumSize > 0) {
  52593. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  52594. }
  52595. else {
  52596. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  52597. }
  52598. };
  52599. /**
  52600. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  52601. * Returns the DirectionalLight Shadow projection matrix.
  52602. */
  52603. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  52604. var activeCamera = this.getScene().activeCamera;
  52605. if (!activeCamera) {
  52606. return;
  52607. }
  52608. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  52609. };
  52610. /**
  52611. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  52612. * Returns the DirectionalLight Shadow projection matrix.
  52613. */
  52614. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52615. var activeCamera = this.getScene().activeCamera;
  52616. if (!activeCamera) {
  52617. return;
  52618. }
  52619. // Check extends
  52620. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  52621. var tempVector3 = BABYLON.Vector3.Zero();
  52622. this._orthoLeft = Number.MAX_VALUE;
  52623. this._orthoRight = Number.MIN_VALUE;
  52624. this._orthoTop = Number.MIN_VALUE;
  52625. this._orthoBottom = Number.MAX_VALUE;
  52626. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  52627. var mesh = renderList[meshIndex];
  52628. if (!mesh) {
  52629. continue;
  52630. }
  52631. var boundingInfo = mesh.getBoundingInfo();
  52632. var boundingBox = boundingInfo.boundingBox;
  52633. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  52634. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  52635. if (tempVector3.x < this._orthoLeft) {
  52636. this._orthoLeft = tempVector3.x;
  52637. }
  52638. if (tempVector3.y < this._orthoBottom) {
  52639. this._orthoBottom = tempVector3.y;
  52640. }
  52641. if (tempVector3.x > this._orthoRight) {
  52642. this._orthoRight = tempVector3.x;
  52643. }
  52644. if (tempVector3.y > this._orthoTop) {
  52645. this._orthoTop = tempVector3.y;
  52646. }
  52647. }
  52648. }
  52649. }
  52650. var xOffset = this._orthoRight - this._orthoLeft;
  52651. var yOffset = this._orthoTop - this._orthoBottom;
  52652. 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);
  52653. };
  52654. DirectionalLight.prototype._buildUniformLayout = function () {
  52655. this._uniformBuffer.addUniform("vLightData", 4);
  52656. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52657. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52658. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52659. this._uniformBuffer.addUniform("depthValues", 2);
  52660. this._uniformBuffer.create();
  52661. };
  52662. /**
  52663. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  52664. * @param effect The effect to update
  52665. * @param lightIndex The index of the light in the effect to update
  52666. * @returns The directional light
  52667. */
  52668. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  52669. if (this.computeTransformedInformation()) {
  52670. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  52671. return this;
  52672. }
  52673. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  52674. return this;
  52675. };
  52676. /**
  52677. * Gets the minZ used for shadow according to both the scene and the light.
  52678. *
  52679. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  52680. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  52681. * @param activeCamera The camera we are returning the min for
  52682. * @returns the depth min z
  52683. */
  52684. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  52685. return 1;
  52686. };
  52687. /**
  52688. * Gets the maxZ used for shadow according to both the scene and the light.
  52689. *
  52690. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  52691. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  52692. * @param activeCamera The camera we are returning the max for
  52693. * @returns the depth max z
  52694. */
  52695. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  52696. return 1;
  52697. };
  52698. /**
  52699. * Prepares the list of defines specific to the light type.
  52700. * @param defines the list of defines
  52701. * @param lightIndex defines the index of the light for the effect
  52702. */
  52703. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52704. defines["DIRLIGHT" + lightIndex] = true;
  52705. };
  52706. __decorate([
  52707. BABYLON.serialize()
  52708. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  52709. __decorate([
  52710. BABYLON.serialize()
  52711. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  52712. __decorate([
  52713. BABYLON.serialize()
  52714. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  52715. return DirectionalLight;
  52716. }(BABYLON.ShadowLight));
  52717. BABYLON.DirectionalLight = DirectionalLight;
  52718. })(BABYLON || (BABYLON = {}));
  52719. //# sourceMappingURL=babylon.directionalLight.js.map
  52720. var BABYLON;
  52721. (function (BABYLON) {
  52722. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  52723. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  52724. });
  52725. /**
  52726. * A spot light is defined by a position, a direction, an angle, and an exponent.
  52727. * These values define a cone of light starting from the position, emitting toward the direction.
  52728. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  52729. * and the exponent defines the speed of the decay of the light with distance (reach).
  52730. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52731. */
  52732. var SpotLight = /** @class */ (function (_super) {
  52733. __extends(SpotLight, _super);
  52734. /**
  52735. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  52736. * It can cast shadows.
  52737. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52738. * @param name The light friendly name
  52739. * @param position The position of the spot light in the scene
  52740. * @param direction The direction of the light in the scene
  52741. * @param angle The cone angle of the light in Radians
  52742. * @param exponent The light decay speed with the distance from the emission spot
  52743. * @param scene The scene the lights belongs to
  52744. */
  52745. function SpotLight(name, position, direction, angle, exponent, scene) {
  52746. var _this = _super.call(this, name, scene) || this;
  52747. _this._innerAngle = 0;
  52748. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  52749. _this._projectionTextureLightNear = 1e-6;
  52750. _this._projectionTextureLightFar = 1000.0;
  52751. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  52752. _this._projectionTextureViewLightDirty = true;
  52753. _this._projectionTextureProjectionLightDirty = true;
  52754. _this._projectionTextureDirty = true;
  52755. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  52756. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  52757. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  52758. _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);
  52759. _this.position = position;
  52760. _this.direction = direction;
  52761. _this.angle = angle;
  52762. _this.exponent = exponent;
  52763. return _this;
  52764. }
  52765. Object.defineProperty(SpotLight.prototype, "angle", {
  52766. /**
  52767. * Gets the cone angle of the spot light in Radians.
  52768. */
  52769. get: function () {
  52770. return this._angle;
  52771. },
  52772. /**
  52773. * Sets the cone angle of the spot light in Radians.
  52774. */
  52775. set: function (value) {
  52776. this._angle = value;
  52777. this._cosHalfAngle = Math.cos(value * 0.5);
  52778. this._projectionTextureProjectionLightDirty = true;
  52779. this.forceProjectionMatrixCompute();
  52780. this._computeAngleValues();
  52781. },
  52782. enumerable: true,
  52783. configurable: true
  52784. });
  52785. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  52786. /**
  52787. * Only used in gltf falloff mode, this defines the angle where
  52788. * the directional falloff will start before cutting at angle which could be seen
  52789. * as outer angle.
  52790. */
  52791. get: function () {
  52792. return this._innerAngle;
  52793. },
  52794. /**
  52795. * Only used in gltf falloff mode, this defines the angle where
  52796. * the directional falloff will start before cutting at angle which could be seen
  52797. * as outer angle.
  52798. */
  52799. set: function (value) {
  52800. this._innerAngle = value;
  52801. this._computeAngleValues();
  52802. },
  52803. enumerable: true,
  52804. configurable: true
  52805. });
  52806. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  52807. /**
  52808. * Allows scaling the angle of the light for shadow generation only.
  52809. */
  52810. get: function () {
  52811. return this._shadowAngleScale;
  52812. },
  52813. /**
  52814. * Allows scaling the angle of the light for shadow generation only.
  52815. */
  52816. set: function (value) {
  52817. this._shadowAngleScale = value;
  52818. this.forceProjectionMatrixCompute();
  52819. },
  52820. enumerable: true,
  52821. configurable: true
  52822. });
  52823. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  52824. /**
  52825. * Allows reading the projecton texture
  52826. */
  52827. get: function () {
  52828. return this._projectionTextureMatrix;
  52829. },
  52830. enumerable: true,
  52831. configurable: true
  52832. });
  52833. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  52834. /**
  52835. * Gets the near clip of the Spotlight for texture projection.
  52836. */
  52837. get: function () {
  52838. return this._projectionTextureLightNear;
  52839. },
  52840. /**
  52841. * Sets the near clip of the Spotlight for texture projection.
  52842. */
  52843. set: function (value) {
  52844. this._projectionTextureLightNear = value;
  52845. this._projectionTextureProjectionLightDirty = true;
  52846. },
  52847. enumerable: true,
  52848. configurable: true
  52849. });
  52850. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  52851. /**
  52852. * Gets the far clip of the Spotlight for texture projection.
  52853. */
  52854. get: function () {
  52855. return this._projectionTextureLightFar;
  52856. },
  52857. /**
  52858. * Sets the far clip of the Spotlight for texture projection.
  52859. */
  52860. set: function (value) {
  52861. this._projectionTextureLightFar = value;
  52862. this._projectionTextureProjectionLightDirty = true;
  52863. },
  52864. enumerable: true,
  52865. configurable: true
  52866. });
  52867. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  52868. /**
  52869. * Gets the Up vector of the Spotlight for texture projection.
  52870. */
  52871. get: function () {
  52872. return this._projectionTextureUpDirection;
  52873. },
  52874. /**
  52875. * Sets the Up vector of the Spotlight for texture projection.
  52876. */
  52877. set: function (value) {
  52878. this._projectionTextureUpDirection = value;
  52879. this._projectionTextureProjectionLightDirty = true;
  52880. },
  52881. enumerable: true,
  52882. configurable: true
  52883. });
  52884. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  52885. /**
  52886. * Gets the projection texture of the light.
  52887. */
  52888. get: function () {
  52889. return this._projectionTexture;
  52890. },
  52891. /**
  52892. * Sets the projection texture of the light.
  52893. */
  52894. set: function (value) {
  52895. this._projectionTexture = value;
  52896. this._projectionTextureDirty = true;
  52897. },
  52898. enumerable: true,
  52899. configurable: true
  52900. });
  52901. /**
  52902. * Returns the string "SpotLight".
  52903. * @returns the class name
  52904. */
  52905. SpotLight.prototype.getClassName = function () {
  52906. return "SpotLight";
  52907. };
  52908. /**
  52909. * Returns the integer 2.
  52910. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52911. */
  52912. SpotLight.prototype.getTypeID = function () {
  52913. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  52914. };
  52915. /**
  52916. * Overrides the direction setter to recompute the projection texture view light Matrix.
  52917. */
  52918. SpotLight.prototype._setDirection = function (value) {
  52919. _super.prototype._setDirection.call(this, value);
  52920. this._projectionTextureViewLightDirty = true;
  52921. };
  52922. /**
  52923. * Overrides the position setter to recompute the projection texture view light Matrix.
  52924. */
  52925. SpotLight.prototype._setPosition = function (value) {
  52926. _super.prototype._setPosition.call(this, value);
  52927. this._projectionTextureViewLightDirty = true;
  52928. };
  52929. /**
  52930. * 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.
  52931. * Returns the SpotLight.
  52932. */
  52933. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52934. var activeCamera = this.getScene().activeCamera;
  52935. if (!activeCamera) {
  52936. return;
  52937. }
  52938. this._shadowAngleScale = this._shadowAngleScale || 1;
  52939. var angle = this._shadowAngleScale * this._angle;
  52940. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  52941. };
  52942. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  52943. this._projectionTextureViewLightDirty = false;
  52944. this._projectionTextureDirty = true;
  52945. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  52946. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  52947. };
  52948. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  52949. this._projectionTextureProjectionLightDirty = false;
  52950. this._projectionTextureDirty = true;
  52951. var light_far = this.projectionTextureLightFar;
  52952. var light_near = this.projectionTextureLightNear;
  52953. var P = light_far / (light_far - light_near);
  52954. var Q = -P * light_near;
  52955. var S = 1.0 / Math.tan(this._angle / 2.0);
  52956. var A = 1.0;
  52957. 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);
  52958. };
  52959. /**
  52960. * Main function for light texture projection matrix computing.
  52961. */
  52962. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  52963. this._projectionTextureDirty = false;
  52964. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  52965. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  52966. };
  52967. SpotLight.prototype._buildUniformLayout = function () {
  52968. this._uniformBuffer.addUniform("vLightData", 4);
  52969. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52970. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52971. this._uniformBuffer.addUniform("vLightDirection", 3);
  52972. this._uniformBuffer.addUniform("vLightFalloff", 4);
  52973. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52974. this._uniformBuffer.addUniform("depthValues", 2);
  52975. this._uniformBuffer.create();
  52976. };
  52977. SpotLight.prototype._computeAngleValues = function () {
  52978. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  52979. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  52980. };
  52981. /**
  52982. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  52983. * @param effect The effect to update
  52984. * @param lightIndex The index of the light in the effect to update
  52985. * @returns The spot light
  52986. */
  52987. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  52988. var normalizeDirection;
  52989. if (this.computeTransformedInformation()) {
  52990. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  52991. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  52992. }
  52993. else {
  52994. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  52995. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  52996. }
  52997. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  52998. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  52999. if (this.projectionTexture && this.projectionTexture.isReady()) {
  53000. if (this._projectionTextureViewLightDirty) {
  53001. this._computeProjectionTextureViewLightMatrix();
  53002. }
  53003. if (this._projectionTextureProjectionLightDirty) {
  53004. this._computeProjectionTextureProjectionLightMatrix();
  53005. }
  53006. if (this._projectionTextureDirty) {
  53007. this._computeProjectionTextureMatrix();
  53008. }
  53009. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  53010. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  53011. }
  53012. return this;
  53013. };
  53014. /**
  53015. * Disposes the light and the associated resources.
  53016. */
  53017. SpotLight.prototype.dispose = function () {
  53018. _super.prototype.dispose.call(this);
  53019. if (this._projectionTexture) {
  53020. this._projectionTexture.dispose();
  53021. }
  53022. };
  53023. /**
  53024. * Prepares the list of defines specific to the light type.
  53025. * @param defines the list of defines
  53026. * @param lightIndex defines the index of the light for the effect
  53027. */
  53028. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  53029. defines["SPOTLIGHT" + lightIndex] = true;
  53030. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  53031. };
  53032. __decorate([
  53033. BABYLON.serialize()
  53034. ], SpotLight.prototype, "angle", null);
  53035. __decorate([
  53036. BABYLON.serialize()
  53037. ], SpotLight.prototype, "innerAngle", null);
  53038. __decorate([
  53039. BABYLON.serialize()
  53040. ], SpotLight.prototype, "shadowAngleScale", null);
  53041. __decorate([
  53042. BABYLON.serialize()
  53043. ], SpotLight.prototype, "exponent", void 0);
  53044. __decorate([
  53045. BABYLON.serialize()
  53046. ], SpotLight.prototype, "projectionTextureLightNear", null);
  53047. __decorate([
  53048. BABYLON.serialize()
  53049. ], SpotLight.prototype, "projectionTextureLightFar", null);
  53050. __decorate([
  53051. BABYLON.serialize()
  53052. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  53053. __decorate([
  53054. BABYLON.serializeAsTexture("projectedLightTexture")
  53055. ], SpotLight.prototype, "_projectionTexture", void 0);
  53056. return SpotLight;
  53057. }(BABYLON.ShadowLight));
  53058. BABYLON.SpotLight = SpotLight;
  53059. })(BABYLON || (BABYLON = {}));
  53060. //# sourceMappingURL=babylon.spotLight.js.map
  53061. var BABYLON;
  53062. (function (BABYLON) {
  53063. /**
  53064. * Class used to override all child animations of a given target
  53065. */
  53066. var AnimationPropertiesOverride = /** @class */ (function () {
  53067. function AnimationPropertiesOverride() {
  53068. /**
  53069. * Gets or sets a value indicating if animation blending must be used
  53070. */
  53071. this.enableBlending = false;
  53072. /**
  53073. * Gets or sets the blending speed to use when enableBlending is true
  53074. */
  53075. this.blendingSpeed = 0.01;
  53076. /**
  53077. * Gets or sets the default loop mode to use
  53078. */
  53079. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  53080. }
  53081. return AnimationPropertiesOverride;
  53082. }());
  53083. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  53084. })(BABYLON || (BABYLON = {}));
  53085. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  53086. var BABYLON;
  53087. (function (BABYLON) {
  53088. /**
  53089. * Represents the range of an animation
  53090. */
  53091. var AnimationRange = /** @class */ (function () {
  53092. /**
  53093. * Initializes the range of an animation
  53094. * @param name The name of the animation range
  53095. * @param from The starting frame of the animation
  53096. * @param to The ending frame of the animation
  53097. */
  53098. function AnimationRange(
  53099. /**The name of the animation range**/
  53100. name,
  53101. /**The starting frame of the animation */
  53102. from,
  53103. /**The ending frame of the animation*/
  53104. to) {
  53105. this.name = name;
  53106. this.from = from;
  53107. this.to = to;
  53108. }
  53109. /**
  53110. * Makes a copy of the animation range
  53111. * @returns A copy of the animation range
  53112. */
  53113. AnimationRange.prototype.clone = function () {
  53114. return new AnimationRange(this.name, this.from, this.to);
  53115. };
  53116. return AnimationRange;
  53117. }());
  53118. BABYLON.AnimationRange = AnimationRange;
  53119. /**
  53120. * Composed of a frame, and an action function
  53121. */
  53122. var AnimationEvent = /** @class */ (function () {
  53123. /**
  53124. * Initializes the animation event
  53125. * @param frame The frame for which the event is triggered
  53126. * @param action The event to perform when triggered
  53127. * @param onlyOnce Specifies if the event should be triggered only once
  53128. */
  53129. function AnimationEvent(
  53130. /** The frame for which the event is triggered **/
  53131. frame,
  53132. /** The event to perform when triggered **/
  53133. action,
  53134. /** Specifies if the event should be triggered only once**/
  53135. onlyOnce) {
  53136. this.frame = frame;
  53137. this.action = action;
  53138. this.onlyOnce = onlyOnce;
  53139. /**
  53140. * Specifies if the animation event is done
  53141. */
  53142. this.isDone = false;
  53143. }
  53144. /** @hidden */
  53145. AnimationEvent.prototype._clone = function () {
  53146. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  53147. };
  53148. return AnimationEvent;
  53149. }());
  53150. BABYLON.AnimationEvent = AnimationEvent;
  53151. /**
  53152. * A cursor which tracks a point on a path
  53153. */
  53154. var PathCursor = /** @class */ (function () {
  53155. /**
  53156. * Initializes the path cursor
  53157. * @param path The path to track
  53158. */
  53159. function PathCursor(path) {
  53160. this.path = path;
  53161. /**
  53162. * Stores path cursor callbacks for when an onchange event is triggered
  53163. */
  53164. this._onchange = new Array();
  53165. /**
  53166. * The value of the path cursor
  53167. */
  53168. this.value = 0;
  53169. /**
  53170. * The animation array of the path cursor
  53171. */
  53172. this.animations = new Array();
  53173. }
  53174. /**
  53175. * Gets the cursor point on the path
  53176. * @returns A point on the path cursor at the cursor location
  53177. */
  53178. PathCursor.prototype.getPoint = function () {
  53179. var point = this.path.getPointAtLengthPosition(this.value);
  53180. return new BABYLON.Vector3(point.x, 0, point.y);
  53181. };
  53182. /**
  53183. * Moves the cursor ahead by the step amount
  53184. * @param step The amount to move the cursor forward
  53185. * @returns This path cursor
  53186. */
  53187. PathCursor.prototype.moveAhead = function (step) {
  53188. if (step === void 0) { step = 0.002; }
  53189. this.move(step);
  53190. return this;
  53191. };
  53192. /**
  53193. * Moves the cursor behind by the step amount
  53194. * @param step The amount to move the cursor back
  53195. * @returns This path cursor
  53196. */
  53197. PathCursor.prototype.moveBack = function (step) {
  53198. if (step === void 0) { step = 0.002; }
  53199. this.move(-step);
  53200. return this;
  53201. };
  53202. /**
  53203. * Moves the cursor by the step amount
  53204. * If the step amount is greater than one, an exception is thrown
  53205. * @param step The amount to move the cursor
  53206. * @returns This path cursor
  53207. */
  53208. PathCursor.prototype.move = function (step) {
  53209. if (Math.abs(step) > 1) {
  53210. throw "step size should be less than 1.";
  53211. }
  53212. this.value += step;
  53213. this.ensureLimits();
  53214. this.raiseOnChange();
  53215. return this;
  53216. };
  53217. /**
  53218. * Ensures that the value is limited between zero and one
  53219. * @returns This path cursor
  53220. */
  53221. PathCursor.prototype.ensureLimits = function () {
  53222. while (this.value > 1) {
  53223. this.value -= 1;
  53224. }
  53225. while (this.value < 0) {
  53226. this.value += 1;
  53227. }
  53228. return this;
  53229. };
  53230. /**
  53231. * Runs onchange callbacks on change (used by the animation engine)
  53232. * @returns This path cursor
  53233. */
  53234. PathCursor.prototype.raiseOnChange = function () {
  53235. var _this = this;
  53236. this._onchange.forEach(function (f) { return f(_this); });
  53237. return this;
  53238. };
  53239. /**
  53240. * Executes a function on change
  53241. * @param f A path cursor onchange callback
  53242. * @returns This path cursor
  53243. */
  53244. PathCursor.prototype.onchange = function (f) {
  53245. this._onchange.push(f);
  53246. return this;
  53247. };
  53248. return PathCursor;
  53249. }());
  53250. BABYLON.PathCursor = PathCursor;
  53251. /**
  53252. * Enum for the animation key frame interpolation type
  53253. */
  53254. var AnimationKeyInterpolation;
  53255. (function (AnimationKeyInterpolation) {
  53256. /**
  53257. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  53258. */
  53259. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  53260. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  53261. /**
  53262. * Class used to store any kind of animation
  53263. */
  53264. var Animation = /** @class */ (function () {
  53265. /**
  53266. * Initializes the animation
  53267. * @param name Name of the animation
  53268. * @param targetProperty Property to animate
  53269. * @param framePerSecond The frames per second of the animation
  53270. * @param dataType The data type of the animation
  53271. * @param loopMode The loop mode of the animation
  53272. * @param enableBlendings Specifies if blending should be enabled
  53273. */
  53274. function Animation(
  53275. /**Name of the animation */
  53276. name,
  53277. /**Property to animate */
  53278. targetProperty,
  53279. /**The frames per second of the animation */
  53280. framePerSecond,
  53281. /**The data type of the animation */
  53282. dataType,
  53283. /**The loop mode of the animation */
  53284. loopMode,
  53285. /**Specifies if blending should be enabled */
  53286. enableBlending) {
  53287. this.name = name;
  53288. this.targetProperty = targetProperty;
  53289. this.framePerSecond = framePerSecond;
  53290. this.dataType = dataType;
  53291. this.loopMode = loopMode;
  53292. this.enableBlending = enableBlending;
  53293. /**
  53294. * @hidden Internal use only
  53295. */
  53296. this._runtimeAnimations = new Array();
  53297. /**
  53298. * The set of event that will be linked to this animation
  53299. */
  53300. this._events = new Array();
  53301. /**
  53302. * Stores the blending speed of the animation
  53303. */
  53304. this.blendingSpeed = 0.01;
  53305. /**
  53306. * Stores the animation ranges for the animation
  53307. */
  53308. this._ranges = {};
  53309. this.targetPropertyPath = targetProperty.split(".");
  53310. this.dataType = dataType;
  53311. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  53312. }
  53313. /**
  53314. * @hidden Internal use
  53315. */
  53316. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  53317. var dataType = undefined;
  53318. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  53319. dataType = Animation.ANIMATIONTYPE_FLOAT;
  53320. }
  53321. else if (from instanceof BABYLON.Quaternion) {
  53322. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  53323. }
  53324. else if (from instanceof BABYLON.Vector3) {
  53325. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  53326. }
  53327. else if (from instanceof BABYLON.Vector2) {
  53328. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  53329. }
  53330. else if (from instanceof BABYLON.Color3) {
  53331. dataType = Animation.ANIMATIONTYPE_COLOR3;
  53332. }
  53333. else if (from instanceof BABYLON.Size) {
  53334. dataType = Animation.ANIMATIONTYPE_SIZE;
  53335. }
  53336. if (dataType == undefined) {
  53337. return null;
  53338. }
  53339. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  53340. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  53341. animation.setKeys(keys);
  53342. if (easingFunction !== undefined) {
  53343. animation.setEasingFunction(easingFunction);
  53344. }
  53345. return animation;
  53346. };
  53347. /**
  53348. * Sets up an animation
  53349. * @param property The property to animate
  53350. * @param animationType The animation type to apply
  53351. * @param framePerSecond The frames per second of the animation
  53352. * @param easingFunction The easing function used in the animation
  53353. * @returns The created animation
  53354. */
  53355. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  53356. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  53357. animation.setEasingFunction(easingFunction);
  53358. return animation;
  53359. };
  53360. /**
  53361. * Create and start an animation on a node
  53362. * @param name defines the name of the global animation that will be run on all nodes
  53363. * @param node defines the root node where the animation will take place
  53364. * @param targetProperty defines property to animate
  53365. * @param framePerSecond defines the number of frame per second yo use
  53366. * @param totalFrame defines the number of frames in total
  53367. * @param from defines the initial value
  53368. * @param to defines the final value
  53369. * @param loopMode defines which loop mode you want to use (off by default)
  53370. * @param easingFunction defines the easing function to use (linear by default)
  53371. * @param onAnimationEnd defines the callback to call when animation end
  53372. * @returns the animatable created for this animation
  53373. */
  53374. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53375. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53376. if (!animation) {
  53377. return null;
  53378. }
  53379. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53380. };
  53381. /**
  53382. * Create and start an animation on a node and its descendants
  53383. * @param name defines the name of the global animation that will be run on all nodes
  53384. * @param node defines the root node where the animation will take place
  53385. * @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
  53386. * @param targetProperty defines property to animate
  53387. * @param framePerSecond defines the number of frame per second to use
  53388. * @param totalFrame defines the number of frames in total
  53389. * @param from defines the initial value
  53390. * @param to defines the final value
  53391. * @param loopMode defines which loop mode you want to use (off by default)
  53392. * @param easingFunction defines the easing function to use (linear by default)
  53393. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  53394. * @returns the list of animatables created for all nodes
  53395. * @example https://www.babylonjs-playground.com/#MH0VLI
  53396. */
  53397. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53398. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53399. if (!animation) {
  53400. return null;
  53401. }
  53402. var scene = node.getScene();
  53403. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53404. };
  53405. /**
  53406. * Creates a new animation, merges it with the existing animations and starts it
  53407. * @param name Name of the animation
  53408. * @param node Node which contains the scene that begins the animations
  53409. * @param targetProperty Specifies which property to animate
  53410. * @param framePerSecond The frames per second of the animation
  53411. * @param totalFrame The total number of frames
  53412. * @param from The frame at the beginning of the animation
  53413. * @param to The frame at the end of the animation
  53414. * @param loopMode Specifies the loop mode of the animation
  53415. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  53416. * @param onAnimationEnd Callback to run once the animation is complete
  53417. * @returns Nullable animation
  53418. */
  53419. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53420. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53421. if (!animation) {
  53422. return null;
  53423. }
  53424. node.animations.push(animation);
  53425. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53426. };
  53427. /**
  53428. * Transition property of an host to the target Value
  53429. * @param property The property to transition
  53430. * @param targetValue The target Value of the property
  53431. * @param host The object where the property to animate belongs
  53432. * @param scene Scene used to run the animation
  53433. * @param frameRate Framerate (in frame/s) to use
  53434. * @param transition The transition type we want to use
  53435. * @param duration The duration of the animation, in milliseconds
  53436. * @param onAnimationEnd Callback trigger at the end of the animation
  53437. * @returns Nullable animation
  53438. */
  53439. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  53440. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  53441. if (duration <= 0) {
  53442. host[property] = targetValue;
  53443. if (onAnimationEnd) {
  53444. onAnimationEnd();
  53445. }
  53446. return null;
  53447. }
  53448. var endFrame = frameRate * (duration / 1000);
  53449. transition.setKeys([{
  53450. frame: 0,
  53451. value: host[property].clone ? host[property].clone() : host[property]
  53452. },
  53453. {
  53454. frame: endFrame,
  53455. value: targetValue
  53456. }]);
  53457. if (!host.animations) {
  53458. host.animations = [];
  53459. }
  53460. host.animations.push(transition);
  53461. var animation = scene.beginAnimation(host, 0, endFrame, false);
  53462. animation.onAnimationEnd = onAnimationEnd;
  53463. return animation;
  53464. };
  53465. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  53466. /**
  53467. * Return the array of runtime animations currently using this animation
  53468. */
  53469. get: function () {
  53470. return this._runtimeAnimations;
  53471. },
  53472. enumerable: true,
  53473. configurable: true
  53474. });
  53475. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  53476. /**
  53477. * Specifies if any of the runtime animations are currently running
  53478. */
  53479. get: function () {
  53480. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  53481. var runtimeAnimation = _a[_i];
  53482. if (!runtimeAnimation.isStopped) {
  53483. return true;
  53484. }
  53485. }
  53486. return false;
  53487. },
  53488. enumerable: true,
  53489. configurable: true
  53490. });
  53491. // Methods
  53492. /**
  53493. * Converts the animation to a string
  53494. * @param fullDetails support for multiple levels of logging within scene loading
  53495. * @returns String form of the animation
  53496. */
  53497. Animation.prototype.toString = function (fullDetails) {
  53498. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  53499. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  53500. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  53501. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  53502. if (fullDetails) {
  53503. ret += ", Ranges: {";
  53504. var first = true;
  53505. for (var name in this._ranges) {
  53506. if (first) {
  53507. ret += ", ";
  53508. first = false;
  53509. }
  53510. ret += name;
  53511. }
  53512. ret += "}";
  53513. }
  53514. return ret;
  53515. };
  53516. /**
  53517. * Add an event to this animation
  53518. * @param event Event to add
  53519. */
  53520. Animation.prototype.addEvent = function (event) {
  53521. this._events.push(event);
  53522. };
  53523. /**
  53524. * Remove all events found at the given frame
  53525. * @param frame The frame to remove events from
  53526. */
  53527. Animation.prototype.removeEvents = function (frame) {
  53528. for (var index = 0; index < this._events.length; index++) {
  53529. if (this._events[index].frame === frame) {
  53530. this._events.splice(index, 1);
  53531. index--;
  53532. }
  53533. }
  53534. };
  53535. /**
  53536. * Retrieves all the events from the animation
  53537. * @returns Events from the animation
  53538. */
  53539. Animation.prototype.getEvents = function () {
  53540. return this._events;
  53541. };
  53542. /**
  53543. * Creates an animation range
  53544. * @param name Name of the animation range
  53545. * @param from Starting frame of the animation range
  53546. * @param to Ending frame of the animation
  53547. */
  53548. Animation.prototype.createRange = function (name, from, to) {
  53549. // check name not already in use; could happen for bones after serialized
  53550. if (!this._ranges[name]) {
  53551. this._ranges[name] = new AnimationRange(name, from, to);
  53552. }
  53553. };
  53554. /**
  53555. * Deletes an animation range by name
  53556. * @param name Name of the animation range to delete
  53557. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  53558. */
  53559. Animation.prototype.deleteRange = function (name, deleteFrames) {
  53560. if (deleteFrames === void 0) { deleteFrames = true; }
  53561. var range = this._ranges[name];
  53562. if (!range) {
  53563. return;
  53564. }
  53565. if (deleteFrames) {
  53566. var from = range.from;
  53567. var to = range.to;
  53568. // this loop MUST go high to low for multiple splices to work
  53569. for (var key = this._keys.length - 1; key >= 0; key--) {
  53570. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  53571. this._keys.splice(key, 1);
  53572. }
  53573. }
  53574. }
  53575. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  53576. };
  53577. /**
  53578. * Gets the animation range by name, or null if not defined
  53579. * @param name Name of the animation range
  53580. * @returns Nullable animation range
  53581. */
  53582. Animation.prototype.getRange = function (name) {
  53583. return this._ranges[name];
  53584. };
  53585. /**
  53586. * Gets the key frames from the animation
  53587. * @returns The key frames of the animation
  53588. */
  53589. Animation.prototype.getKeys = function () {
  53590. return this._keys;
  53591. };
  53592. /**
  53593. * Gets the highest frame rate of the animation
  53594. * @returns Highest frame rate of the animation
  53595. */
  53596. Animation.prototype.getHighestFrame = function () {
  53597. var ret = 0;
  53598. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  53599. if (ret < this._keys[key].frame) {
  53600. ret = this._keys[key].frame;
  53601. }
  53602. }
  53603. return ret;
  53604. };
  53605. /**
  53606. * Gets the easing function of the animation
  53607. * @returns Easing function of the animation
  53608. */
  53609. Animation.prototype.getEasingFunction = function () {
  53610. return this._easingFunction;
  53611. };
  53612. /**
  53613. * Sets the easing function of the animation
  53614. * @param easingFunction A custom mathematical formula for animation
  53615. */
  53616. Animation.prototype.setEasingFunction = function (easingFunction) {
  53617. this._easingFunction = easingFunction;
  53618. };
  53619. /**
  53620. * Interpolates a scalar linearly
  53621. * @param startValue Start value of the animation curve
  53622. * @param endValue End value of the animation curve
  53623. * @param gradient Scalar amount to interpolate
  53624. * @returns Interpolated scalar value
  53625. */
  53626. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  53627. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  53628. };
  53629. /**
  53630. * Interpolates a scalar cubically
  53631. * @param startValue Start value of the animation curve
  53632. * @param outTangent End tangent of the animation
  53633. * @param endValue End value of the animation curve
  53634. * @param inTangent Start tangent of the animation curve
  53635. * @param gradient Scalar amount to interpolate
  53636. * @returns Interpolated scalar value
  53637. */
  53638. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53639. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53640. };
  53641. /**
  53642. * Interpolates a quaternion using a spherical linear interpolation
  53643. * @param startValue Start value of the animation curve
  53644. * @param endValue End value of the animation curve
  53645. * @param gradient Scalar amount to interpolate
  53646. * @returns Interpolated quaternion value
  53647. */
  53648. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  53649. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  53650. };
  53651. /**
  53652. * Interpolates a quaternion cubically
  53653. * @param startValue Start value of the animation curve
  53654. * @param outTangent End tangent of the animation curve
  53655. * @param endValue End value of the animation curve
  53656. * @param inTangent Start tangent of the animation curve
  53657. * @param gradient Scalar amount to interpolate
  53658. * @returns Interpolated quaternion value
  53659. */
  53660. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53661. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  53662. };
  53663. /**
  53664. * Interpolates a Vector3 linearl
  53665. * @param startValue Start value of the animation curve
  53666. * @param endValue End value of the animation curve
  53667. * @param gradient Scalar amount to interpolate
  53668. * @returns Interpolated scalar value
  53669. */
  53670. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  53671. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  53672. };
  53673. /**
  53674. * Interpolates a Vector3 cubically
  53675. * @param startValue Start value of the animation curve
  53676. * @param outTangent End tangent of the animation
  53677. * @param endValue End value of the animation curve
  53678. * @param inTangent Start tangent of the animation curve
  53679. * @param gradient Scalar amount to interpolate
  53680. * @returns InterpolatedVector3 value
  53681. */
  53682. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53683. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53684. };
  53685. /**
  53686. * Interpolates a Vector2 linearly
  53687. * @param startValue Start value of the animation curve
  53688. * @param endValue End value of the animation curve
  53689. * @param gradient Scalar amount to interpolate
  53690. * @returns Interpolated Vector2 value
  53691. */
  53692. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  53693. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  53694. };
  53695. /**
  53696. * Interpolates a Vector2 cubically
  53697. * @param startValue Start value of the animation curve
  53698. * @param outTangent End tangent of the animation
  53699. * @param endValue End value of the animation curve
  53700. * @param inTangent Start tangent of the animation curve
  53701. * @param gradient Scalar amount to interpolate
  53702. * @returns Interpolated Vector2 value
  53703. */
  53704. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53705. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53706. };
  53707. /**
  53708. * Interpolates a size linearly
  53709. * @param startValue Start value of the animation curve
  53710. * @param endValue End value of the animation curve
  53711. * @param gradient Scalar amount to interpolate
  53712. * @returns Interpolated Size value
  53713. */
  53714. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  53715. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  53716. };
  53717. /**
  53718. * Interpolates a Color3 linearly
  53719. * @param startValue Start value of the animation curve
  53720. * @param endValue End value of the animation curve
  53721. * @param gradient Scalar amount to interpolate
  53722. * @returns Interpolated Color3 value
  53723. */
  53724. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  53725. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  53726. };
  53727. /**
  53728. * @hidden Internal use only
  53729. */
  53730. Animation.prototype._getKeyValue = function (value) {
  53731. if (typeof value === "function") {
  53732. return value();
  53733. }
  53734. return value;
  53735. };
  53736. /**
  53737. * @hidden Internal use only
  53738. */
  53739. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  53740. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  53741. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  53742. }
  53743. var keys = this.getKeys();
  53744. // Try to get a hash to find the right key
  53745. 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));
  53746. if (keys[startKeyIndex].frame >= currentFrame) {
  53747. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  53748. startKeyIndex--;
  53749. }
  53750. }
  53751. for (var key = startKeyIndex; key < keys.length; key++) {
  53752. var endKey = keys[key + 1];
  53753. if (endKey.frame >= currentFrame) {
  53754. var startKey = keys[key];
  53755. var startValue = this._getKeyValue(startKey.value);
  53756. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  53757. return startValue;
  53758. }
  53759. var endValue = this._getKeyValue(endKey.value);
  53760. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  53761. var frameDelta = endKey.frame - startKey.frame;
  53762. // gradient : percent of currentFrame between the frame inf and the frame sup
  53763. var gradient = (currentFrame - startKey.frame) / frameDelta;
  53764. // check for easingFunction and correction of gradient
  53765. var easingFunction = this.getEasingFunction();
  53766. if (easingFunction != null) {
  53767. gradient = easingFunction.ease(gradient);
  53768. }
  53769. switch (this.dataType) {
  53770. // Float
  53771. case Animation.ANIMATIONTYPE_FLOAT:
  53772. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  53773. switch (loopMode) {
  53774. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53775. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53776. return floatValue;
  53777. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53778. return offsetValue * repeatCount + floatValue;
  53779. }
  53780. break;
  53781. // Quaternion
  53782. case Animation.ANIMATIONTYPE_QUATERNION:
  53783. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  53784. switch (loopMode) {
  53785. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53786. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53787. return quatValue;
  53788. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53789. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  53790. }
  53791. return quatValue;
  53792. // Vector3
  53793. case Animation.ANIMATIONTYPE_VECTOR3:
  53794. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  53795. switch (loopMode) {
  53796. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53797. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53798. return vec3Value;
  53799. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53800. return vec3Value.add(offsetValue.scale(repeatCount));
  53801. }
  53802. // Vector2
  53803. case Animation.ANIMATIONTYPE_VECTOR2:
  53804. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  53805. switch (loopMode) {
  53806. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53807. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53808. return vec2Value;
  53809. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53810. return vec2Value.add(offsetValue.scale(repeatCount));
  53811. }
  53812. // Size
  53813. case Animation.ANIMATIONTYPE_SIZE:
  53814. switch (loopMode) {
  53815. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53816. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53817. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  53818. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53819. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  53820. }
  53821. // Color3
  53822. case Animation.ANIMATIONTYPE_COLOR3:
  53823. switch (loopMode) {
  53824. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53825. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53826. return this.color3InterpolateFunction(startValue, endValue, gradient);
  53827. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53828. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  53829. }
  53830. // Matrix
  53831. case Animation.ANIMATIONTYPE_MATRIX:
  53832. switch (loopMode) {
  53833. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53834. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53835. if (Animation.AllowMatricesInterpolation) {
  53836. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  53837. }
  53838. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53839. return startValue;
  53840. }
  53841. default:
  53842. break;
  53843. }
  53844. break;
  53845. }
  53846. }
  53847. return this._getKeyValue(keys[keys.length - 1].value);
  53848. };
  53849. /**
  53850. * Defines the function to use to interpolate matrices
  53851. * @param startValue defines the start matrix
  53852. * @param endValue defines the end matrix
  53853. * @param gradient defines the gradient between both matrices
  53854. * @param result defines an optional target matrix where to store the interpolation
  53855. * @returns the interpolated matrix
  53856. */
  53857. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  53858. if (Animation.AllowMatrixDecomposeForInterpolation) {
  53859. if (result) {
  53860. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  53861. return result;
  53862. }
  53863. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  53864. }
  53865. if (result) {
  53866. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  53867. return result;
  53868. }
  53869. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  53870. };
  53871. /**
  53872. * Makes a copy of the animation
  53873. * @returns Cloned animation
  53874. */
  53875. Animation.prototype.clone = function () {
  53876. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  53877. clone.enableBlending = this.enableBlending;
  53878. clone.blendingSpeed = this.blendingSpeed;
  53879. if (this._keys) {
  53880. clone.setKeys(this._keys);
  53881. }
  53882. if (this._ranges) {
  53883. clone._ranges = {};
  53884. for (var name in this._ranges) {
  53885. var range = this._ranges[name];
  53886. if (!range) {
  53887. continue;
  53888. }
  53889. clone._ranges[name] = range.clone();
  53890. }
  53891. }
  53892. return clone;
  53893. };
  53894. /**
  53895. * Sets the key frames of the animation
  53896. * @param values The animation key frames to set
  53897. */
  53898. Animation.prototype.setKeys = function (values) {
  53899. this._keys = values.slice(0);
  53900. };
  53901. /**
  53902. * Serializes the animation to an object
  53903. * @returns Serialized object
  53904. */
  53905. Animation.prototype.serialize = function () {
  53906. var serializationObject = {};
  53907. serializationObject.name = this.name;
  53908. serializationObject.property = this.targetProperty;
  53909. serializationObject.framePerSecond = this.framePerSecond;
  53910. serializationObject.dataType = this.dataType;
  53911. serializationObject.loopBehavior = this.loopMode;
  53912. serializationObject.enableBlending = this.enableBlending;
  53913. serializationObject.blendingSpeed = this.blendingSpeed;
  53914. var dataType = this.dataType;
  53915. serializationObject.keys = [];
  53916. var keys = this.getKeys();
  53917. for (var index = 0; index < keys.length; index++) {
  53918. var animationKey = keys[index];
  53919. var key = {};
  53920. key.frame = animationKey.frame;
  53921. switch (dataType) {
  53922. case Animation.ANIMATIONTYPE_FLOAT:
  53923. key.values = [animationKey.value];
  53924. break;
  53925. case Animation.ANIMATIONTYPE_QUATERNION:
  53926. case Animation.ANIMATIONTYPE_MATRIX:
  53927. case Animation.ANIMATIONTYPE_VECTOR3:
  53928. case Animation.ANIMATIONTYPE_COLOR3:
  53929. key.values = animationKey.value.asArray();
  53930. break;
  53931. }
  53932. serializationObject.keys.push(key);
  53933. }
  53934. serializationObject.ranges = [];
  53935. for (var name in this._ranges) {
  53936. var source = this._ranges[name];
  53937. if (!source) {
  53938. continue;
  53939. }
  53940. var range = {};
  53941. range.name = name;
  53942. range.from = source.from;
  53943. range.to = source.to;
  53944. serializationObject.ranges.push(range);
  53945. }
  53946. return serializationObject;
  53947. };
  53948. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  53949. /**
  53950. * Get the float animation type
  53951. */
  53952. get: function () {
  53953. return Animation._ANIMATIONTYPE_FLOAT;
  53954. },
  53955. enumerable: true,
  53956. configurable: true
  53957. });
  53958. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  53959. /**
  53960. * Get the Vector3 animation type
  53961. */
  53962. get: function () {
  53963. return Animation._ANIMATIONTYPE_VECTOR3;
  53964. },
  53965. enumerable: true,
  53966. configurable: true
  53967. });
  53968. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  53969. /**
  53970. * Get the Vector2 animation type
  53971. */
  53972. get: function () {
  53973. return Animation._ANIMATIONTYPE_VECTOR2;
  53974. },
  53975. enumerable: true,
  53976. configurable: true
  53977. });
  53978. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  53979. /**
  53980. * Get the Size animation type
  53981. */
  53982. get: function () {
  53983. return Animation._ANIMATIONTYPE_SIZE;
  53984. },
  53985. enumerable: true,
  53986. configurable: true
  53987. });
  53988. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  53989. /**
  53990. * Get the Quaternion animation type
  53991. */
  53992. get: function () {
  53993. return Animation._ANIMATIONTYPE_QUATERNION;
  53994. },
  53995. enumerable: true,
  53996. configurable: true
  53997. });
  53998. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  53999. /**
  54000. * Get the Matrix animation type
  54001. */
  54002. get: function () {
  54003. return Animation._ANIMATIONTYPE_MATRIX;
  54004. },
  54005. enumerable: true,
  54006. configurable: true
  54007. });
  54008. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  54009. /**
  54010. * Get the Color3 animation type
  54011. */
  54012. get: function () {
  54013. return Animation._ANIMATIONTYPE_COLOR3;
  54014. },
  54015. enumerable: true,
  54016. configurable: true
  54017. });
  54018. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  54019. /**
  54020. * Get the Relative Loop Mode
  54021. */
  54022. get: function () {
  54023. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  54024. },
  54025. enumerable: true,
  54026. configurable: true
  54027. });
  54028. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  54029. /**
  54030. * Get the Cycle Loop Mode
  54031. */
  54032. get: function () {
  54033. return Animation._ANIMATIONLOOPMODE_CYCLE;
  54034. },
  54035. enumerable: true,
  54036. configurable: true
  54037. });
  54038. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  54039. /**
  54040. * Get the Constant Loop Mode
  54041. */
  54042. get: function () {
  54043. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  54044. },
  54045. enumerable: true,
  54046. configurable: true
  54047. });
  54048. /** @hidden */
  54049. Animation._UniversalLerp = function (left, right, amount) {
  54050. var constructor = left.constructor;
  54051. if (constructor.Lerp) { // Lerp supported
  54052. return constructor.Lerp(left, right, amount);
  54053. }
  54054. else if (constructor.Slerp) { // Slerp supported
  54055. return constructor.Slerp(left, right, amount);
  54056. }
  54057. else if (left.toFixed) { // Number
  54058. return left * (1.0 - amount) + amount * right;
  54059. }
  54060. else { // Blending not supported
  54061. return right;
  54062. }
  54063. };
  54064. /**
  54065. * Parses an animation object and creates an animation
  54066. * @param parsedAnimation Parsed animation object
  54067. * @returns Animation object
  54068. */
  54069. Animation.Parse = function (parsedAnimation) {
  54070. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  54071. var dataType = parsedAnimation.dataType;
  54072. var keys = [];
  54073. var data;
  54074. var index;
  54075. if (parsedAnimation.enableBlending) {
  54076. animation.enableBlending = parsedAnimation.enableBlending;
  54077. }
  54078. if (parsedAnimation.blendingSpeed) {
  54079. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  54080. }
  54081. for (index = 0; index < parsedAnimation.keys.length; index++) {
  54082. var key = parsedAnimation.keys[index];
  54083. var inTangent;
  54084. var outTangent;
  54085. switch (dataType) {
  54086. case Animation.ANIMATIONTYPE_FLOAT:
  54087. data = key.values[0];
  54088. if (key.values.length >= 1) {
  54089. inTangent = key.values[1];
  54090. }
  54091. if (key.values.length >= 2) {
  54092. outTangent = key.values[2];
  54093. }
  54094. break;
  54095. case Animation.ANIMATIONTYPE_QUATERNION:
  54096. data = BABYLON.Quaternion.FromArray(key.values);
  54097. if (key.values.length >= 8) {
  54098. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  54099. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  54100. inTangent = _inTangent;
  54101. }
  54102. }
  54103. if (key.values.length >= 12) {
  54104. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  54105. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  54106. outTangent = _outTangent;
  54107. }
  54108. }
  54109. break;
  54110. case Animation.ANIMATIONTYPE_MATRIX:
  54111. data = BABYLON.Matrix.FromArray(key.values);
  54112. break;
  54113. case Animation.ANIMATIONTYPE_COLOR3:
  54114. data = BABYLON.Color3.FromArray(key.values);
  54115. break;
  54116. case Animation.ANIMATIONTYPE_VECTOR3:
  54117. default:
  54118. data = BABYLON.Vector3.FromArray(key.values);
  54119. break;
  54120. }
  54121. var keyData = {};
  54122. keyData.frame = key.frame;
  54123. keyData.value = data;
  54124. if (inTangent != undefined) {
  54125. keyData.inTangent = inTangent;
  54126. }
  54127. if (outTangent != undefined) {
  54128. keyData.outTangent = outTangent;
  54129. }
  54130. keys.push(keyData);
  54131. }
  54132. animation.setKeys(keys);
  54133. if (parsedAnimation.ranges) {
  54134. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  54135. data = parsedAnimation.ranges[index];
  54136. animation.createRange(data.name, data.from, data.to);
  54137. }
  54138. }
  54139. return animation;
  54140. };
  54141. /**
  54142. * Appends the serialized animations from the source animations
  54143. * @param source Source containing the animations
  54144. * @param destination Target to store the animations
  54145. */
  54146. Animation.AppendSerializedAnimations = function (source, destination) {
  54147. if (source.animations) {
  54148. destination.animations = [];
  54149. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  54150. var animation = source.animations[animationIndex];
  54151. destination.animations.push(animation.serialize());
  54152. }
  54153. }
  54154. };
  54155. /**
  54156. * Use matrix interpolation instead of using direct key value when animating matrices
  54157. */
  54158. Animation.AllowMatricesInterpolation = false;
  54159. /**
  54160. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  54161. */
  54162. Animation.AllowMatrixDecomposeForInterpolation = true;
  54163. // Statics
  54164. /**
  54165. * Float animation type
  54166. */
  54167. Animation._ANIMATIONTYPE_FLOAT = 0;
  54168. /**
  54169. * Vector3 animation type
  54170. */
  54171. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  54172. /**
  54173. * Quaternion animation type
  54174. */
  54175. Animation._ANIMATIONTYPE_QUATERNION = 2;
  54176. /**
  54177. * Matrix animation type
  54178. */
  54179. Animation._ANIMATIONTYPE_MATRIX = 3;
  54180. /**
  54181. * Color3 animation type
  54182. */
  54183. Animation._ANIMATIONTYPE_COLOR3 = 4;
  54184. /**
  54185. * Vector2 animation type
  54186. */
  54187. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  54188. /**
  54189. * Size animation type
  54190. */
  54191. Animation._ANIMATIONTYPE_SIZE = 6;
  54192. /**
  54193. * Relative Loop Mode
  54194. */
  54195. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  54196. /**
  54197. * Cycle Loop Mode
  54198. */
  54199. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  54200. /**
  54201. * Constant Loop Mode
  54202. */
  54203. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  54204. return Animation;
  54205. }());
  54206. BABYLON.Animation = Animation;
  54207. })(BABYLON || (BABYLON = {}));
  54208. //# sourceMappingURL=babylon.animation.js.map
  54209. var BABYLON;
  54210. (function (BABYLON) {
  54211. /**
  54212. * This class defines the direct association between an animation and a target
  54213. */
  54214. var TargetedAnimation = /** @class */ (function () {
  54215. function TargetedAnimation() {
  54216. }
  54217. return TargetedAnimation;
  54218. }());
  54219. BABYLON.TargetedAnimation = TargetedAnimation;
  54220. /**
  54221. * Use this class to create coordinated animations on multiple targets
  54222. */
  54223. var AnimationGroup = /** @class */ (function () {
  54224. /**
  54225. * Instantiates a new Animation Group.
  54226. * This helps managing several animations at once.
  54227. * @see http://doc.babylonjs.com/how_to/group
  54228. * @param name Defines the name of the group
  54229. * @param scene Defines the scene the group belongs to
  54230. */
  54231. function AnimationGroup(
  54232. /** The name of the animation group */
  54233. name, scene) {
  54234. if (scene === void 0) { scene = null; }
  54235. this.name = name;
  54236. this._targetedAnimations = new Array();
  54237. this._animatables = new Array();
  54238. this._from = Number.MAX_VALUE;
  54239. this._to = -Number.MAX_VALUE;
  54240. this._speedRatio = 1;
  54241. /**
  54242. * This observable will notify when one animation have ended.
  54243. */
  54244. this.onAnimationEndObservable = new BABYLON.Observable();
  54245. /**
  54246. * This observable will notify when all animations have ended.
  54247. */
  54248. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  54249. /**
  54250. * This observable will notify when all animations have paused.
  54251. */
  54252. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  54253. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54254. this._scene.animationGroups.push(this);
  54255. }
  54256. Object.defineProperty(AnimationGroup.prototype, "from", {
  54257. /**
  54258. * Gets the first frame
  54259. */
  54260. get: function () {
  54261. return this._from;
  54262. },
  54263. enumerable: true,
  54264. configurable: true
  54265. });
  54266. Object.defineProperty(AnimationGroup.prototype, "to", {
  54267. /**
  54268. * Gets the last frame
  54269. */
  54270. get: function () {
  54271. return this._to;
  54272. },
  54273. enumerable: true,
  54274. configurable: true
  54275. });
  54276. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  54277. /**
  54278. * Define if the animations are started
  54279. */
  54280. get: function () {
  54281. return this._isStarted;
  54282. },
  54283. enumerable: true,
  54284. configurable: true
  54285. });
  54286. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  54287. /**
  54288. * Gets or sets the speed ratio to use for all animations
  54289. */
  54290. get: function () {
  54291. return this._speedRatio;
  54292. },
  54293. /**
  54294. * Gets or sets the speed ratio to use for all animations
  54295. */
  54296. set: function (value) {
  54297. if (this._speedRatio === value) {
  54298. return;
  54299. }
  54300. this._speedRatio = value;
  54301. for (var index = 0; index < this._animatables.length; index++) {
  54302. var animatable = this._animatables[index];
  54303. animatable.speedRatio = this._speedRatio;
  54304. }
  54305. },
  54306. enumerable: true,
  54307. configurable: true
  54308. });
  54309. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  54310. /**
  54311. * Gets the targeted animations for this animation group
  54312. */
  54313. get: function () {
  54314. return this._targetedAnimations;
  54315. },
  54316. enumerable: true,
  54317. configurable: true
  54318. });
  54319. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  54320. /**
  54321. * returning the list of animatables controlled by this animation group.
  54322. */
  54323. get: function () {
  54324. return this._animatables;
  54325. },
  54326. enumerable: true,
  54327. configurable: true
  54328. });
  54329. /**
  54330. * Add an animation (with its target) in the group
  54331. * @param animation defines the animation we want to add
  54332. * @param target defines the target of the animation
  54333. * @returns the TargetedAnimation object
  54334. */
  54335. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  54336. var targetedAnimation = {
  54337. animation: animation,
  54338. target: target
  54339. };
  54340. var keys = animation.getKeys();
  54341. if (this._from > keys[0].frame) {
  54342. this._from = keys[0].frame;
  54343. }
  54344. if (this._to < keys[keys.length - 1].frame) {
  54345. this._to = keys[keys.length - 1].frame;
  54346. }
  54347. this._targetedAnimations.push(targetedAnimation);
  54348. return targetedAnimation;
  54349. };
  54350. /**
  54351. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  54352. * It can add constant keys at begin or end
  54353. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  54354. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  54355. * @returns the animation group
  54356. */
  54357. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  54358. if (beginFrame === void 0) { beginFrame = null; }
  54359. if (endFrame === void 0) { endFrame = null; }
  54360. if (beginFrame == null) {
  54361. beginFrame = this._from;
  54362. }
  54363. if (endFrame == null) {
  54364. endFrame = this._to;
  54365. }
  54366. for (var index = 0; index < this._targetedAnimations.length; index++) {
  54367. var targetedAnimation = this._targetedAnimations[index];
  54368. var keys = targetedAnimation.animation.getKeys();
  54369. var startKey = keys[0];
  54370. var endKey = keys[keys.length - 1];
  54371. if (startKey.frame > beginFrame) {
  54372. var newKey = {
  54373. frame: beginFrame,
  54374. value: startKey.value,
  54375. inTangent: startKey.inTangent,
  54376. outTangent: startKey.outTangent,
  54377. interpolation: startKey.interpolation
  54378. };
  54379. keys.splice(0, 0, newKey);
  54380. }
  54381. if (endKey.frame < endFrame) {
  54382. var newKey = {
  54383. frame: endFrame,
  54384. value: endKey.value,
  54385. inTangent: endKey.outTangent,
  54386. outTangent: endKey.outTangent,
  54387. interpolation: endKey.interpolation
  54388. };
  54389. keys.push(newKey);
  54390. }
  54391. }
  54392. this._from = beginFrame;
  54393. this._to = endFrame;
  54394. return this;
  54395. };
  54396. /**
  54397. * Start all animations on given targets
  54398. * @param loop defines if animations must loop
  54399. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  54400. * @param from defines the from key (optional)
  54401. * @param to defines the to key (optional)
  54402. * @returns the current animation group
  54403. */
  54404. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  54405. var _this = this;
  54406. if (loop === void 0) { loop = false; }
  54407. if (speedRatio === void 0) { speedRatio = 1; }
  54408. if (this._isStarted || this._targetedAnimations.length === 0) {
  54409. return this;
  54410. }
  54411. var _loop_1 = function (targetedAnimation) {
  54412. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  54413. animatable.onAnimationEnd = function () {
  54414. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  54415. _this._checkAnimationGroupEnded(animatable);
  54416. };
  54417. this_1._animatables.push(animatable);
  54418. };
  54419. var this_1 = this;
  54420. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  54421. var targetedAnimation = _a[_i];
  54422. _loop_1(targetedAnimation);
  54423. }
  54424. this._speedRatio = speedRatio;
  54425. this._isStarted = true;
  54426. return this;
  54427. };
  54428. /**
  54429. * Pause all animations
  54430. * @returns the animation group
  54431. */
  54432. AnimationGroup.prototype.pause = function () {
  54433. if (!this._isStarted) {
  54434. return this;
  54435. }
  54436. for (var index = 0; index < this._animatables.length; index++) {
  54437. var animatable = this._animatables[index];
  54438. animatable.pause();
  54439. }
  54440. this.onAnimationGroupPauseObservable.notifyObservers(this);
  54441. return this;
  54442. };
  54443. /**
  54444. * Play all animations to initial state
  54445. * This function will start() the animations if they were not started or will restart() them if they were paused
  54446. * @param loop defines if animations must loop
  54447. * @returns the animation group
  54448. */
  54449. AnimationGroup.prototype.play = function (loop) {
  54450. // only if all animatables are ready and exist
  54451. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  54452. if (loop !== undefined) {
  54453. for (var index = 0; index < this._animatables.length; index++) {
  54454. var animatable = this._animatables[index];
  54455. animatable.loopAnimation = loop;
  54456. }
  54457. }
  54458. this.restart();
  54459. }
  54460. else {
  54461. this.stop();
  54462. this.start(loop, this._speedRatio);
  54463. }
  54464. return this;
  54465. };
  54466. /**
  54467. * Reset all animations to initial state
  54468. * @returns the animation group
  54469. */
  54470. AnimationGroup.prototype.reset = function () {
  54471. if (!this._isStarted) {
  54472. return this;
  54473. }
  54474. for (var index = 0; index < this._animatables.length; index++) {
  54475. var animatable = this._animatables[index];
  54476. animatable.reset();
  54477. }
  54478. return this;
  54479. };
  54480. /**
  54481. * Restart animations from key 0
  54482. * @returns the animation group
  54483. */
  54484. AnimationGroup.prototype.restart = function () {
  54485. if (!this._isStarted) {
  54486. return this;
  54487. }
  54488. for (var index = 0; index < this._animatables.length; index++) {
  54489. var animatable = this._animatables[index];
  54490. animatable.restart();
  54491. }
  54492. return this;
  54493. };
  54494. /**
  54495. * Stop all animations
  54496. * @returns the animation group
  54497. */
  54498. AnimationGroup.prototype.stop = function () {
  54499. if (!this._isStarted) {
  54500. return this;
  54501. }
  54502. var list = this._animatables.slice();
  54503. for (var index = 0; index < list.length; index++) {
  54504. list[index].stop();
  54505. }
  54506. this._isStarted = false;
  54507. return this;
  54508. };
  54509. /**
  54510. * Set animation weight for all animatables
  54511. * @param weight defines the weight to use
  54512. * @return the animationGroup
  54513. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  54514. */
  54515. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  54516. for (var index = 0; index < this._animatables.length; index++) {
  54517. var animatable = this._animatables[index];
  54518. animatable.weight = weight;
  54519. }
  54520. return this;
  54521. };
  54522. /**
  54523. * Synchronize and normalize all animatables with a source animatable
  54524. * @param root defines the root animatable to synchronize with
  54525. * @return the animationGroup
  54526. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  54527. */
  54528. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  54529. for (var index = 0; index < this._animatables.length; index++) {
  54530. var animatable = this._animatables[index];
  54531. animatable.syncWith(root);
  54532. }
  54533. return this;
  54534. };
  54535. /**
  54536. * Goes to a specific frame in this animation group
  54537. * @param frame the frame number to go to
  54538. * @return the animationGroup
  54539. */
  54540. AnimationGroup.prototype.goToFrame = function (frame) {
  54541. if (!this._isStarted) {
  54542. return this;
  54543. }
  54544. for (var index = 0; index < this._animatables.length; index++) {
  54545. var animatable = this._animatables[index];
  54546. animatable.goToFrame(frame);
  54547. }
  54548. return this;
  54549. };
  54550. /**
  54551. * Dispose all associated resources
  54552. */
  54553. AnimationGroup.prototype.dispose = function () {
  54554. this._targetedAnimations = [];
  54555. this._animatables = [];
  54556. var index = this._scene.animationGroups.indexOf(this);
  54557. if (index > -1) {
  54558. this._scene.animationGroups.splice(index, 1);
  54559. }
  54560. };
  54561. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  54562. // animatable should be taken out of the array
  54563. var idx = this._animatables.indexOf(animatable);
  54564. if (idx > -1) {
  54565. this._animatables.splice(idx, 1);
  54566. }
  54567. // all animatables were removed? animation group ended!
  54568. if (this._animatables.length === 0) {
  54569. this._isStarted = false;
  54570. this.onAnimationGroupEndObservable.notifyObservers(this);
  54571. }
  54572. };
  54573. // Statics
  54574. /**
  54575. * Returns a new AnimationGroup object parsed from the source provided.
  54576. * @param parsedAnimationGroup defines the source
  54577. * @param scene defines the scene that will receive the animationGroup
  54578. * @returns a new AnimationGroup
  54579. */
  54580. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  54581. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  54582. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  54583. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  54584. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  54585. var id = targetedAnimation.targetId;
  54586. var targetNode = scene.getNodeByID(id);
  54587. if (targetNode != null) {
  54588. animationGroup.addTargetedAnimation(animation, targetNode);
  54589. }
  54590. }
  54591. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) {
  54592. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  54593. }
  54594. return animationGroup;
  54595. };
  54596. /**
  54597. * Returns the string "AnimationGroup"
  54598. * @returns "AnimationGroup"
  54599. */
  54600. AnimationGroup.prototype.getClassName = function () {
  54601. return "AnimationGroup";
  54602. };
  54603. /**
  54604. * Creates a detailled string about the object
  54605. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  54606. * @returns a string representing the object
  54607. */
  54608. AnimationGroup.prototype.toString = function (fullDetails) {
  54609. var ret = "Name: " + this.name;
  54610. ret += ", type: " + this.getClassName();
  54611. if (fullDetails) {
  54612. ret += ", from: " + this._from;
  54613. ret += ", to: " + this._to;
  54614. ret += ", isStarted: " + this._isStarted;
  54615. ret += ", speedRatio: " + this._speedRatio;
  54616. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  54617. ret += ", animatables length: " + this._animatables;
  54618. }
  54619. return ret;
  54620. };
  54621. return AnimationGroup;
  54622. }());
  54623. BABYLON.AnimationGroup = AnimationGroup;
  54624. })(BABYLON || (BABYLON = {}));
  54625. //# sourceMappingURL=babylon.animationGroup.js.map
  54626. var BABYLON;
  54627. (function (BABYLON) {
  54628. // Static values to help the garbage collector
  54629. // Quaternion
  54630. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  54631. // Vector3
  54632. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  54633. // Vector2
  54634. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  54635. // Size
  54636. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  54637. // Color3
  54638. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  54639. /**
  54640. * Defines a runtime animation
  54641. */
  54642. var RuntimeAnimation = /** @class */ (function () {
  54643. /**
  54644. * Create a new RuntimeAnimation object
  54645. * @param target defines the target of the animation
  54646. * @param animation defines the source animation object
  54647. * @param scene defines the hosting scene
  54648. * @param host defines the initiating Animatable
  54649. */
  54650. function RuntimeAnimation(target, animation, scene, host) {
  54651. var _this = this;
  54652. this._events = new Array();
  54653. /**
  54654. * The current frame of the runtime animation
  54655. */
  54656. this._currentFrame = 0;
  54657. /**
  54658. * The original value of the runtime animation
  54659. */
  54660. this._originalValue = new Array();
  54661. /**
  54662. * The offsets cache of the runtime animation
  54663. */
  54664. this._offsetsCache = {};
  54665. /**
  54666. * The high limits cache of the runtime animation
  54667. */
  54668. this._highLimitsCache = {};
  54669. /**
  54670. * Specifies if the runtime animation has been stopped
  54671. */
  54672. this._stopped = false;
  54673. /**
  54674. * The blending factor of the runtime animation
  54675. */
  54676. this._blendingFactor = 0;
  54677. /**
  54678. * The target path of the runtime animation
  54679. */
  54680. this._targetPath = "";
  54681. /**
  54682. * The weight of the runtime animation
  54683. */
  54684. this._weight = 1.0;
  54685. /**
  54686. * The ratio offset of the runtime animation
  54687. */
  54688. this._ratioOffset = 0;
  54689. /**
  54690. * The previous delay of the runtime animation
  54691. */
  54692. this._previousDelay = 0;
  54693. /**
  54694. * The previous ratio of the runtime animation
  54695. */
  54696. this._previousRatio = 0;
  54697. this._animation = animation;
  54698. this._target = target;
  54699. this._scene = scene;
  54700. this._host = host;
  54701. animation._runtimeAnimations.push(this);
  54702. // Cloning events locally
  54703. var events = animation.getEvents();
  54704. if (events && events.length > 0) {
  54705. events.forEach(function (e) {
  54706. _this._events.push(e._clone());
  54707. });
  54708. }
  54709. }
  54710. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  54711. /**
  54712. * Gets the current frame of the runtime animation
  54713. */
  54714. get: function () {
  54715. return this._currentFrame;
  54716. },
  54717. enumerable: true,
  54718. configurable: true
  54719. });
  54720. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  54721. /**
  54722. * Gets the weight of the runtime animation
  54723. */
  54724. get: function () {
  54725. return this._weight;
  54726. },
  54727. enumerable: true,
  54728. configurable: true
  54729. });
  54730. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  54731. /**
  54732. * Gets the current value of the runtime animation
  54733. */
  54734. get: function () {
  54735. return this._currentValue;
  54736. },
  54737. enumerable: true,
  54738. configurable: true
  54739. });
  54740. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  54741. /**
  54742. * Gets the target path of the runtime animation
  54743. */
  54744. get: function () {
  54745. return this._targetPath;
  54746. },
  54747. enumerable: true,
  54748. configurable: true
  54749. });
  54750. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  54751. /**
  54752. * Gets the actual target of the runtime animation
  54753. */
  54754. get: function () {
  54755. return this._activeTarget;
  54756. },
  54757. enumerable: true,
  54758. configurable: true
  54759. });
  54760. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  54761. /**
  54762. * Gets the animation from the runtime animation
  54763. */
  54764. get: function () {
  54765. return this._animation;
  54766. },
  54767. enumerable: true,
  54768. configurable: true
  54769. });
  54770. /**
  54771. * Resets the runtime animation to the beginning
  54772. * @param restoreOriginal defines whether to restore the target property to the original value
  54773. */
  54774. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  54775. if (restoreOriginal === void 0) { restoreOriginal = false; }
  54776. if (restoreOriginal) {
  54777. if (this._target instanceof Array) {
  54778. var index = 0;
  54779. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  54780. var target = _a[_i];
  54781. if (this._originalValue[index] !== undefined) {
  54782. this._setValue(target, this._originalValue[index], -1);
  54783. }
  54784. index++;
  54785. }
  54786. }
  54787. else {
  54788. if (this._originalValue[0] !== undefined) {
  54789. this._setValue(this._target, this._originalValue[0], -1);
  54790. }
  54791. }
  54792. }
  54793. this._offsetsCache = {};
  54794. this._highLimitsCache = {};
  54795. this._currentFrame = 0;
  54796. this._blendingFactor = 0;
  54797. this._originalValue = new Array();
  54798. // Events
  54799. for (var index = 0; index < this._events.length; index++) {
  54800. this._events[index].isDone = false;
  54801. }
  54802. };
  54803. /**
  54804. * Specifies if the runtime animation is stopped
  54805. * @returns Boolean specifying if the runtime animation is stopped
  54806. */
  54807. RuntimeAnimation.prototype.isStopped = function () {
  54808. return this._stopped;
  54809. };
  54810. /**
  54811. * Disposes of the runtime animation
  54812. */
  54813. RuntimeAnimation.prototype.dispose = function () {
  54814. var index = this._animation.runtimeAnimations.indexOf(this);
  54815. if (index > -1) {
  54816. this._animation.runtimeAnimations.splice(index, 1);
  54817. }
  54818. };
  54819. /**
  54820. * Interpolates the animation from the current frame
  54821. * @param currentFrame The frame to interpolate the animation to
  54822. * @param repeatCount The number of times that the animation should loop
  54823. * @param loopMode The type of looping mode to use
  54824. * @param offsetValue Animation offset value
  54825. * @param highLimitValue The high limit value
  54826. * @returns The interpolated value
  54827. */
  54828. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  54829. this._currentFrame = currentFrame;
  54830. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  54831. this._workValue = BABYLON.Matrix.Zero();
  54832. }
  54833. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  54834. };
  54835. /**
  54836. * Apply the interpolated value to the target
  54837. * @param currentValue defines the value computed by the animation
  54838. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  54839. */
  54840. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  54841. if (weight === void 0) { weight = 1.0; }
  54842. if (this._target instanceof Array) {
  54843. var index = 0;
  54844. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  54845. var target = _a[_i];
  54846. this._setValue(target, currentValue, weight, index);
  54847. index++;
  54848. }
  54849. }
  54850. else {
  54851. this._setValue(this._target, currentValue, weight);
  54852. }
  54853. };
  54854. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  54855. if (targetIndex === void 0) { targetIndex = 0; }
  54856. // Set value
  54857. var path;
  54858. var destination;
  54859. var targetPropertyPath = this._animation.targetPropertyPath;
  54860. if (targetPropertyPath.length > 1) {
  54861. var property = target[targetPropertyPath[0]];
  54862. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  54863. property = property[targetPropertyPath[index]];
  54864. }
  54865. path = targetPropertyPath[targetPropertyPath.length - 1];
  54866. destination = property;
  54867. }
  54868. else {
  54869. path = targetPropertyPath[0];
  54870. destination = target;
  54871. }
  54872. this._targetPath = path;
  54873. this._activeTarget = destination;
  54874. this._weight = weight;
  54875. if (this._originalValue[targetIndex] === undefined) {
  54876. var originalValue = void 0;
  54877. if (destination.getRestPose && path === "_matrix") { // For bones
  54878. originalValue = destination.getRestPose();
  54879. }
  54880. else {
  54881. originalValue = destination[path];
  54882. }
  54883. if (originalValue && originalValue.clone) {
  54884. this._originalValue[targetIndex] = originalValue.clone();
  54885. }
  54886. else {
  54887. this._originalValue[targetIndex] = originalValue;
  54888. }
  54889. }
  54890. // Blending
  54891. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  54892. if (enableBlending && this._blendingFactor <= 1.0) {
  54893. if (!this._originalBlendValue) {
  54894. var originalValue = destination[path];
  54895. if (originalValue.clone) {
  54896. this._originalBlendValue = originalValue.clone();
  54897. }
  54898. else {
  54899. this._originalBlendValue = originalValue;
  54900. }
  54901. }
  54902. if (this._originalBlendValue.m) { // Matrix
  54903. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  54904. if (this._currentValue) {
  54905. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  54906. }
  54907. else {
  54908. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  54909. }
  54910. }
  54911. else {
  54912. if (this._currentValue) {
  54913. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  54914. }
  54915. else {
  54916. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  54917. }
  54918. }
  54919. }
  54920. else {
  54921. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  54922. }
  54923. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  54924. this._blendingFactor += blendingSpeed;
  54925. }
  54926. else {
  54927. this._currentValue = currentValue;
  54928. }
  54929. if (weight !== -1.0) {
  54930. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  54931. }
  54932. else {
  54933. destination[path] = this._currentValue;
  54934. }
  54935. if (target.markAsDirty) {
  54936. target.markAsDirty(this._animation.targetProperty);
  54937. }
  54938. };
  54939. /**
  54940. * Gets the loop pmode of the runtime animation
  54941. * @returns Loop Mode
  54942. */
  54943. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  54944. if (this._target && this._target.animationPropertiesOverride) {
  54945. return this._target.animationPropertiesOverride.loopMode;
  54946. }
  54947. return this._animation.loopMode;
  54948. };
  54949. /**
  54950. * Move the current animation to a given frame
  54951. * @param frame defines the frame to move to
  54952. */
  54953. RuntimeAnimation.prototype.goToFrame = function (frame) {
  54954. var keys = this._animation.getKeys();
  54955. if (frame < keys[0].frame) {
  54956. frame = keys[0].frame;
  54957. }
  54958. else if (frame > keys[keys.length - 1].frame) {
  54959. frame = keys[keys.length - 1].frame;
  54960. }
  54961. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  54962. this.setValue(currentValue, -1);
  54963. };
  54964. /**
  54965. * @hidden Internal use only
  54966. */
  54967. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  54968. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  54969. this._ratioOffset = this._previousRatio - newRatio;
  54970. };
  54971. /**
  54972. * Execute the current animation
  54973. * @param delay defines the delay to add to the current frame
  54974. * @param from defines the lower bound of the animation range
  54975. * @param to defines the upper bound of the animation range
  54976. * @param loop defines if the current animation must loop
  54977. * @param speedRatio defines the current speed ratio
  54978. * @param weight defines the weight of the animation (default is -1 so no weight)
  54979. * @returns a boolean indicating if the animation is running
  54980. */
  54981. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  54982. if (weight === void 0) { weight = -1.0; }
  54983. var targetPropertyPath = this._animation.targetPropertyPath;
  54984. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  54985. this._stopped = true;
  54986. return false;
  54987. }
  54988. var returnValue = true;
  54989. var keys = this._animation.getKeys();
  54990. // Adding a start key at frame 0 if missing
  54991. if (keys[0].frame !== 0) {
  54992. var newKey = { frame: 0, value: keys[0].value };
  54993. keys.splice(0, 0, newKey);
  54994. }
  54995. // Adding a duplicate key when there is only one key at frame zero
  54996. else if (keys.length === 1) {
  54997. var newKey = { frame: 0.001, value: keys[0].value };
  54998. keys.push(newKey);
  54999. }
  55000. // Check limits
  55001. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  55002. from = keys[0].frame;
  55003. }
  55004. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  55005. to = keys[keys.length - 1].frame;
  55006. }
  55007. //to and from cannot be the same key
  55008. if (from === to) {
  55009. if (from > keys[0].frame) {
  55010. from--;
  55011. }
  55012. else if (to < keys[keys.length - 1].frame) {
  55013. to++;
  55014. }
  55015. }
  55016. // Compute ratio
  55017. var range = to - from;
  55018. var offsetValue;
  55019. // ratio represents the frame delta between from and to
  55020. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  55021. var highLimitValue = 0;
  55022. this._previousDelay = delay;
  55023. this._previousRatio = ratio;
  55024. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  55025. returnValue = false;
  55026. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  55027. }
  55028. else {
  55029. // Get max value if required
  55030. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  55031. var keyOffset = to.toString() + from.toString();
  55032. if (!this._offsetsCache[keyOffset]) {
  55033. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  55034. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  55035. switch (this._animation.dataType) {
  55036. // Float
  55037. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  55038. this._offsetsCache[keyOffset] = toValue - fromValue;
  55039. break;
  55040. // Quaternion
  55041. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  55042. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55043. break;
  55044. // Vector3
  55045. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  55046. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55047. // Vector2
  55048. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  55049. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55050. // Size
  55051. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  55052. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55053. // Color3
  55054. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  55055. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55056. default:
  55057. break;
  55058. }
  55059. this._highLimitsCache[keyOffset] = toValue;
  55060. }
  55061. highLimitValue = this._highLimitsCache[keyOffset];
  55062. offsetValue = this._offsetsCache[keyOffset];
  55063. }
  55064. }
  55065. if (offsetValue === undefined) {
  55066. switch (this._animation.dataType) {
  55067. // Float
  55068. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  55069. offsetValue = 0;
  55070. break;
  55071. // Quaternion
  55072. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  55073. offsetValue = _staticOffsetValueQuaternion;
  55074. break;
  55075. // Vector3
  55076. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  55077. offsetValue = _staticOffsetValueVector3;
  55078. break;
  55079. // Vector2
  55080. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  55081. offsetValue = _staticOffsetValueVector2;
  55082. break;
  55083. // Size
  55084. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  55085. offsetValue = _staticOffsetValueSize;
  55086. break;
  55087. // Color3
  55088. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  55089. offsetValue = _staticOffsetValueColor3;
  55090. }
  55091. }
  55092. // Compute value
  55093. var repeatCount = (ratio / range) >> 0;
  55094. var currentFrame = returnValue ? from + ratio % range : to;
  55095. // Need to normalize?
  55096. if (this._host && this._host.syncRoot) {
  55097. var syncRoot = this._host.syncRoot;
  55098. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  55099. currentFrame = from + (to - from) * hostNormalizedFrame;
  55100. }
  55101. // Reset events if looping
  55102. var events = this._events;
  55103. if (range > 0 && this.currentFrame > currentFrame ||
  55104. range < 0 && this.currentFrame < currentFrame) {
  55105. // Need to reset animation events
  55106. for (var index = 0; index < events.length; index++) {
  55107. if (!events[index].onlyOnce) {
  55108. // reset event, the animation is looping
  55109. events[index].isDone = false;
  55110. }
  55111. }
  55112. }
  55113. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  55114. // Set value
  55115. this.setValue(currentValue, weight);
  55116. // Check events
  55117. for (var index = 0; index < events.length; index++) {
  55118. // Make sure current frame has passed event frame and that event frame is within the current range
  55119. // Also, handle both forward and reverse animations
  55120. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  55121. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  55122. var event = events[index];
  55123. if (!event.isDone) {
  55124. // If event should be done only once, remove it.
  55125. if (event.onlyOnce) {
  55126. events.splice(index, 1);
  55127. index--;
  55128. }
  55129. event.isDone = true;
  55130. event.action(currentFrame);
  55131. } // Don't do anything if the event has already be done.
  55132. }
  55133. }
  55134. if (!returnValue) {
  55135. this._stopped = true;
  55136. }
  55137. return returnValue;
  55138. };
  55139. return RuntimeAnimation;
  55140. }());
  55141. BABYLON.RuntimeAnimation = RuntimeAnimation;
  55142. })(BABYLON || (BABYLON = {}));
  55143. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  55144. var BABYLON;
  55145. (function (BABYLON) {
  55146. /**
  55147. * Class used to store an actual running animation
  55148. */
  55149. var Animatable = /** @class */ (function () {
  55150. /**
  55151. * Creates a new Animatable
  55152. * @param scene defines the hosting scene
  55153. * @param target defines the target object
  55154. * @param fromFrame defines the starting frame number (default is 0)
  55155. * @param toFrame defines the ending frame number (default is 100)
  55156. * @param loopAnimation defines if the animation must loop (default is false)
  55157. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  55158. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  55159. * @param animations defines a group of animation to add to the new Animatable
  55160. */
  55161. function Animatable(scene,
  55162. /** defines the target object */
  55163. target,
  55164. /** defines the starting frame number (default is 0) */
  55165. fromFrame,
  55166. /** defines the ending frame number (default is 100) */
  55167. toFrame,
  55168. /** defines if the animation must loop (default is false) */
  55169. loopAnimation, speedRatio,
  55170. /** defines a callback to call when animation ends if it is not looping */
  55171. onAnimationEnd, animations) {
  55172. if (fromFrame === void 0) { fromFrame = 0; }
  55173. if (toFrame === void 0) { toFrame = 100; }
  55174. if (loopAnimation === void 0) { loopAnimation = false; }
  55175. if (speedRatio === void 0) { speedRatio = 1.0; }
  55176. this.target = target;
  55177. this.fromFrame = fromFrame;
  55178. this.toFrame = toFrame;
  55179. this.loopAnimation = loopAnimation;
  55180. this.onAnimationEnd = onAnimationEnd;
  55181. this._localDelayOffset = null;
  55182. this._pausedDelay = null;
  55183. this._runtimeAnimations = new Array();
  55184. this._paused = false;
  55185. this._speedRatio = 1;
  55186. this._weight = -1.0;
  55187. /**
  55188. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  55189. * This will only apply for non looping animation (default is true)
  55190. */
  55191. this.disposeOnEnd = true;
  55192. /**
  55193. * Gets a boolean indicating if the animation has started
  55194. */
  55195. this.animationStarted = false;
  55196. /**
  55197. * Observer raised when the animation ends
  55198. */
  55199. this.onAnimationEndObservable = new BABYLON.Observable();
  55200. this._scene = scene;
  55201. if (animations) {
  55202. this.appendAnimations(target, animations);
  55203. }
  55204. this._speedRatio = speedRatio;
  55205. scene._activeAnimatables.push(this);
  55206. }
  55207. Object.defineProperty(Animatable.prototype, "syncRoot", {
  55208. /**
  55209. * Gets the root Animatable used to synchronize and normalize animations
  55210. */
  55211. get: function () {
  55212. return this._syncRoot;
  55213. },
  55214. enumerable: true,
  55215. configurable: true
  55216. });
  55217. Object.defineProperty(Animatable.prototype, "masterFrame", {
  55218. /**
  55219. * Gets the current frame of the first RuntimeAnimation
  55220. * Used to synchronize Animatables
  55221. */
  55222. get: function () {
  55223. if (this._runtimeAnimations.length === 0) {
  55224. return 0;
  55225. }
  55226. return this._runtimeAnimations[0].currentFrame;
  55227. },
  55228. enumerable: true,
  55229. configurable: true
  55230. });
  55231. Object.defineProperty(Animatable.prototype, "weight", {
  55232. /**
  55233. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  55234. */
  55235. get: function () {
  55236. return this._weight;
  55237. },
  55238. set: function (value) {
  55239. if (value === -1) { // -1 is ok and means no weight
  55240. this._weight = -1;
  55241. return;
  55242. }
  55243. // Else weight must be in [0, 1] range
  55244. this._weight = Math.min(Math.max(value, 0), 1.0);
  55245. },
  55246. enumerable: true,
  55247. configurable: true
  55248. });
  55249. Object.defineProperty(Animatable.prototype, "speedRatio", {
  55250. /**
  55251. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  55252. */
  55253. get: function () {
  55254. return this._speedRatio;
  55255. },
  55256. set: function (value) {
  55257. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  55258. var animation = this._runtimeAnimations[index];
  55259. animation._prepareForSpeedRatioChange(value);
  55260. }
  55261. this._speedRatio = value;
  55262. },
  55263. enumerable: true,
  55264. configurable: true
  55265. });
  55266. // Methods
  55267. /**
  55268. * Synchronize and normalize current Animatable with a source Animatable
  55269. * This is useful when using animation weights and when animations are not of the same length
  55270. * @param root defines the root Animatable to synchronize with
  55271. * @returns the current Animatable
  55272. */
  55273. Animatable.prototype.syncWith = function (root) {
  55274. this._syncRoot = root;
  55275. if (root) {
  55276. // Make sure this animatable will animate after the root
  55277. var index = this._scene._activeAnimatables.indexOf(this);
  55278. if (index > -1) {
  55279. this._scene._activeAnimatables.splice(index, 1);
  55280. this._scene._activeAnimatables.push(this);
  55281. }
  55282. }
  55283. return this;
  55284. };
  55285. /**
  55286. * Gets the list of runtime animations
  55287. * @returns an array of RuntimeAnimation
  55288. */
  55289. Animatable.prototype.getAnimations = function () {
  55290. return this._runtimeAnimations;
  55291. };
  55292. /**
  55293. * Adds more animations to the current animatable
  55294. * @param target defines the target of the animations
  55295. * @param animations defines the new animations to add
  55296. */
  55297. Animatable.prototype.appendAnimations = function (target, animations) {
  55298. for (var index = 0; index < animations.length; index++) {
  55299. var animation = animations[index];
  55300. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  55301. }
  55302. };
  55303. /**
  55304. * Gets the source animation for a specific property
  55305. * @param property defines the propertyu to look for
  55306. * @returns null or the source animation for the given property
  55307. */
  55308. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  55309. var runtimeAnimations = this._runtimeAnimations;
  55310. for (var index = 0; index < runtimeAnimations.length; index++) {
  55311. if (runtimeAnimations[index].animation.targetProperty === property) {
  55312. return runtimeAnimations[index].animation;
  55313. }
  55314. }
  55315. return null;
  55316. };
  55317. /**
  55318. * Gets the runtime animation for a specific property
  55319. * @param property defines the propertyu to look for
  55320. * @returns null or the runtime animation for the given property
  55321. */
  55322. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  55323. var runtimeAnimations = this._runtimeAnimations;
  55324. for (var index = 0; index < runtimeAnimations.length; index++) {
  55325. if (runtimeAnimations[index].animation.targetProperty === property) {
  55326. return runtimeAnimations[index];
  55327. }
  55328. }
  55329. return null;
  55330. };
  55331. /**
  55332. * Resets the animatable to its original state
  55333. */
  55334. Animatable.prototype.reset = function () {
  55335. var runtimeAnimations = this._runtimeAnimations;
  55336. for (var index = 0; index < runtimeAnimations.length; index++) {
  55337. runtimeAnimations[index].reset(true);
  55338. }
  55339. this._localDelayOffset = null;
  55340. this._pausedDelay = null;
  55341. };
  55342. /**
  55343. * Allows the animatable to blend with current running animations
  55344. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  55345. * @param blendingSpeed defines the blending speed to use
  55346. */
  55347. Animatable.prototype.enableBlending = function (blendingSpeed) {
  55348. var runtimeAnimations = this._runtimeAnimations;
  55349. for (var index = 0; index < runtimeAnimations.length; index++) {
  55350. runtimeAnimations[index].animation.enableBlending = true;
  55351. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  55352. }
  55353. };
  55354. /**
  55355. * Disable animation blending
  55356. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  55357. */
  55358. Animatable.prototype.disableBlending = function () {
  55359. var runtimeAnimations = this._runtimeAnimations;
  55360. for (var index = 0; index < runtimeAnimations.length; index++) {
  55361. runtimeAnimations[index].animation.enableBlending = false;
  55362. }
  55363. };
  55364. /**
  55365. * Jump directly to a given frame
  55366. * @param frame defines the frame to jump to
  55367. */
  55368. Animatable.prototype.goToFrame = function (frame) {
  55369. var runtimeAnimations = this._runtimeAnimations;
  55370. if (runtimeAnimations[0]) {
  55371. var fps = runtimeAnimations[0].animation.framePerSecond;
  55372. var currentFrame = runtimeAnimations[0].currentFrame;
  55373. var adjustTime = frame - currentFrame;
  55374. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  55375. if (this._localDelayOffset === null) {
  55376. this._localDelayOffset = 0;
  55377. }
  55378. this._localDelayOffset -= delay;
  55379. }
  55380. for (var index = 0; index < runtimeAnimations.length; index++) {
  55381. runtimeAnimations[index].goToFrame(frame);
  55382. }
  55383. };
  55384. /**
  55385. * Pause the animation
  55386. */
  55387. Animatable.prototype.pause = function () {
  55388. if (this._paused) {
  55389. return;
  55390. }
  55391. this._paused = true;
  55392. };
  55393. /**
  55394. * Restart the animation
  55395. */
  55396. Animatable.prototype.restart = function () {
  55397. this._paused = false;
  55398. };
  55399. Animatable.prototype._raiseOnAnimationEnd = function () {
  55400. if (this.onAnimationEnd) {
  55401. this.onAnimationEnd();
  55402. }
  55403. this.onAnimationEndObservable.notifyObservers(this);
  55404. };
  55405. /**
  55406. * Stop and delete the current animation
  55407. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  55408. * @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)
  55409. */
  55410. Animatable.prototype.stop = function (animationName, targetMask) {
  55411. if (animationName || targetMask) {
  55412. var idx = this._scene._activeAnimatables.indexOf(this);
  55413. if (idx > -1) {
  55414. var runtimeAnimations = this._runtimeAnimations;
  55415. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  55416. var runtimeAnimation = runtimeAnimations[index];
  55417. if (animationName && runtimeAnimation.animation.name != animationName) {
  55418. continue;
  55419. }
  55420. if (targetMask && !targetMask(runtimeAnimation.target)) {
  55421. continue;
  55422. }
  55423. runtimeAnimation.dispose();
  55424. runtimeAnimations.splice(index, 1);
  55425. }
  55426. if (runtimeAnimations.length == 0) {
  55427. this._scene._activeAnimatables.splice(idx, 1);
  55428. this._raiseOnAnimationEnd();
  55429. }
  55430. }
  55431. }
  55432. else {
  55433. var index = this._scene._activeAnimatables.indexOf(this);
  55434. if (index > -1) {
  55435. this._scene._activeAnimatables.splice(index, 1);
  55436. var runtimeAnimations = this._runtimeAnimations;
  55437. for (var index = 0; index < runtimeAnimations.length; index++) {
  55438. runtimeAnimations[index].dispose();
  55439. }
  55440. this._raiseOnAnimationEnd();
  55441. }
  55442. }
  55443. };
  55444. /**
  55445. * Wait asynchronously for the animation to end
  55446. * @returns a promise which will be fullfilled when the animation ends
  55447. */
  55448. Animatable.prototype.waitAsync = function () {
  55449. var _this = this;
  55450. return new Promise(function (resolve, reject) {
  55451. _this.onAnimationEndObservable.add(function () {
  55452. resolve(_this);
  55453. }, undefined, undefined, _this, true);
  55454. });
  55455. };
  55456. /** @hidden */
  55457. Animatable.prototype._animate = function (delay) {
  55458. if (this._paused) {
  55459. this.animationStarted = false;
  55460. if (this._pausedDelay === null) {
  55461. this._pausedDelay = delay;
  55462. }
  55463. return true;
  55464. }
  55465. if (this._localDelayOffset === null) {
  55466. this._localDelayOffset = delay;
  55467. this._pausedDelay = null;
  55468. }
  55469. else if (this._pausedDelay !== null) {
  55470. this._localDelayOffset += delay - this._pausedDelay;
  55471. this._pausedDelay = null;
  55472. }
  55473. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  55474. return true;
  55475. }
  55476. // Animating
  55477. var running = false;
  55478. var runtimeAnimations = this._runtimeAnimations;
  55479. var index;
  55480. for (index = 0; index < runtimeAnimations.length; index++) {
  55481. var animation = runtimeAnimations[index];
  55482. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  55483. running = running || isRunning;
  55484. }
  55485. this.animationStarted = running;
  55486. if (!running) {
  55487. if (this.disposeOnEnd) {
  55488. // Remove from active animatables
  55489. index = this._scene._activeAnimatables.indexOf(this);
  55490. this._scene._activeAnimatables.splice(index, 1);
  55491. // Dispose all runtime animations
  55492. for (index = 0; index < runtimeAnimations.length; index++) {
  55493. runtimeAnimations[index].dispose();
  55494. }
  55495. }
  55496. this._raiseOnAnimationEnd();
  55497. if (this.disposeOnEnd) {
  55498. this.onAnimationEnd = null;
  55499. this.onAnimationEndObservable.clear();
  55500. }
  55501. }
  55502. return running;
  55503. };
  55504. return Animatable;
  55505. }());
  55506. BABYLON.Animatable = Animatable;
  55507. })(BABYLON || (BABYLON = {}));
  55508. //# sourceMappingURL=babylon.animatable.js.map
  55509. var BABYLON;
  55510. (function (BABYLON) {
  55511. /**
  55512. * Base class used for every default easing function.
  55513. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55514. */
  55515. var EasingFunction = /** @class */ (function () {
  55516. function EasingFunction() {
  55517. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  55518. }
  55519. /**
  55520. * Sets the easing mode of the current function.
  55521. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  55522. */
  55523. EasingFunction.prototype.setEasingMode = function (easingMode) {
  55524. var n = Math.min(Math.max(easingMode, 0), 2);
  55525. this._easingMode = n;
  55526. };
  55527. /**
  55528. * Gets the current easing mode.
  55529. * @returns the easing mode
  55530. */
  55531. EasingFunction.prototype.getEasingMode = function () {
  55532. return this._easingMode;
  55533. };
  55534. /**
  55535. * @hidden
  55536. */
  55537. EasingFunction.prototype.easeInCore = function (gradient) {
  55538. throw new Error('You must implement this method');
  55539. };
  55540. /**
  55541. * Given an input gradient between 0 and 1, this returns the corrseponding value
  55542. * of the easing function.
  55543. * @param gradient Defines the value between 0 and 1 we want the easing value for
  55544. * @returns the corresponding value on the curve defined by the easing function
  55545. */
  55546. EasingFunction.prototype.ease = function (gradient) {
  55547. switch (this._easingMode) {
  55548. case EasingFunction.EASINGMODE_EASEIN:
  55549. return this.easeInCore(gradient);
  55550. case EasingFunction.EASINGMODE_EASEOUT:
  55551. return (1 - this.easeInCore(1 - gradient));
  55552. }
  55553. if (gradient >= 0.5) {
  55554. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  55555. }
  55556. return (this.easeInCore(gradient * 2) * 0.5);
  55557. };
  55558. /**
  55559. * Interpolation follows the mathematical formula associated with the easing function.
  55560. */
  55561. EasingFunction.EASINGMODE_EASEIN = 0;
  55562. /**
  55563. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  55564. */
  55565. EasingFunction.EASINGMODE_EASEOUT = 1;
  55566. /**
  55567. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  55568. */
  55569. EasingFunction.EASINGMODE_EASEINOUT = 2;
  55570. return EasingFunction;
  55571. }());
  55572. BABYLON.EasingFunction = EasingFunction;
  55573. /**
  55574. * Easing function with a circle shape (see link below).
  55575. * @see https://easings.net/#easeInCirc
  55576. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55577. */
  55578. var CircleEase = /** @class */ (function (_super) {
  55579. __extends(CircleEase, _super);
  55580. function CircleEase() {
  55581. return _super !== null && _super.apply(this, arguments) || this;
  55582. }
  55583. /** @hidden */
  55584. CircleEase.prototype.easeInCore = function (gradient) {
  55585. gradient = Math.max(0, Math.min(1, gradient));
  55586. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  55587. };
  55588. return CircleEase;
  55589. }(EasingFunction));
  55590. BABYLON.CircleEase = CircleEase;
  55591. /**
  55592. * Easing function with a ease back shape (see link below).
  55593. * @see https://easings.net/#easeInBack
  55594. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55595. */
  55596. var BackEase = /** @class */ (function (_super) {
  55597. __extends(BackEase, _super);
  55598. /**
  55599. * Instantiates a back ease easing
  55600. * @see https://easings.net/#easeInBack
  55601. * @param amplitude Defines the amplitude of the function
  55602. */
  55603. function BackEase(
  55604. /** Defines the amplitude of the function */
  55605. amplitude) {
  55606. if (amplitude === void 0) { amplitude = 1; }
  55607. var _this = _super.call(this) || this;
  55608. _this.amplitude = amplitude;
  55609. return _this;
  55610. }
  55611. /** @hidden */
  55612. BackEase.prototype.easeInCore = function (gradient) {
  55613. var num = Math.max(0, this.amplitude);
  55614. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  55615. };
  55616. return BackEase;
  55617. }(EasingFunction));
  55618. BABYLON.BackEase = BackEase;
  55619. /**
  55620. * Easing function with a bouncing shape (see link below).
  55621. * @see https://easings.net/#easeInBounce
  55622. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55623. */
  55624. var BounceEase = /** @class */ (function (_super) {
  55625. __extends(BounceEase, _super);
  55626. /**
  55627. * Instantiates a bounce easing
  55628. * @see https://easings.net/#easeInBounce
  55629. * @param bounces Defines the number of bounces
  55630. * @param bounciness Defines the amplitude of the bounce
  55631. */
  55632. function BounceEase(
  55633. /** Defines the number of bounces */
  55634. bounces,
  55635. /** Defines the amplitude of the bounce */
  55636. bounciness) {
  55637. if (bounces === void 0) { bounces = 3; }
  55638. if (bounciness === void 0) { bounciness = 2; }
  55639. var _this = _super.call(this) || this;
  55640. _this.bounces = bounces;
  55641. _this.bounciness = bounciness;
  55642. return _this;
  55643. }
  55644. /** @hidden */
  55645. BounceEase.prototype.easeInCore = function (gradient) {
  55646. var y = Math.max(0.0, this.bounces);
  55647. var bounciness = this.bounciness;
  55648. if (bounciness <= 1.0) {
  55649. bounciness = 1.001;
  55650. }
  55651. var num9 = Math.pow(bounciness, y);
  55652. var num5 = 1.0 - bounciness;
  55653. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  55654. var num15 = gradient * num4;
  55655. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  55656. var num3 = Math.floor(num65);
  55657. var num13 = num3 + 1.0;
  55658. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  55659. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  55660. var num7 = (num8 + num12) * 0.5;
  55661. var num6 = gradient - num7;
  55662. var num2 = num7 - num8;
  55663. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  55664. };
  55665. return BounceEase;
  55666. }(EasingFunction));
  55667. BABYLON.BounceEase = BounceEase;
  55668. /**
  55669. * Easing function with a power of 3 shape (see link below).
  55670. * @see https://easings.net/#easeInCubic
  55671. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55672. */
  55673. var CubicEase = /** @class */ (function (_super) {
  55674. __extends(CubicEase, _super);
  55675. function CubicEase() {
  55676. return _super !== null && _super.apply(this, arguments) || this;
  55677. }
  55678. /** @hidden */
  55679. CubicEase.prototype.easeInCore = function (gradient) {
  55680. return (gradient * gradient * gradient);
  55681. };
  55682. return CubicEase;
  55683. }(EasingFunction));
  55684. BABYLON.CubicEase = CubicEase;
  55685. /**
  55686. * Easing function with an elastic shape (see link below).
  55687. * @see https://easings.net/#easeInElastic
  55688. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55689. */
  55690. var ElasticEase = /** @class */ (function (_super) {
  55691. __extends(ElasticEase, _super);
  55692. /**
  55693. * Instantiates an elastic easing function
  55694. * @see https://easings.net/#easeInElastic
  55695. * @param oscillations Defines the number of oscillations
  55696. * @param springiness Defines the amplitude of the oscillations
  55697. */
  55698. function ElasticEase(
  55699. /** Defines the number of oscillations*/
  55700. oscillations,
  55701. /** Defines the amplitude of the oscillations*/
  55702. springiness) {
  55703. if (oscillations === void 0) { oscillations = 3; }
  55704. if (springiness === void 0) { springiness = 3; }
  55705. var _this = _super.call(this) || this;
  55706. _this.oscillations = oscillations;
  55707. _this.springiness = springiness;
  55708. return _this;
  55709. }
  55710. /** @hidden */
  55711. ElasticEase.prototype.easeInCore = function (gradient) {
  55712. var num2;
  55713. var num3 = Math.max(0.0, this.oscillations);
  55714. var num = Math.max(0.0, this.springiness);
  55715. if (num == 0) {
  55716. num2 = gradient;
  55717. }
  55718. else {
  55719. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  55720. }
  55721. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  55722. };
  55723. return ElasticEase;
  55724. }(EasingFunction));
  55725. BABYLON.ElasticEase = ElasticEase;
  55726. /**
  55727. * Easing function with an exponential shape (see link below).
  55728. * @see https://easings.net/#easeInExpo
  55729. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55730. */
  55731. var ExponentialEase = /** @class */ (function (_super) {
  55732. __extends(ExponentialEase, _super);
  55733. /**
  55734. * Instantiates an exponential easing function
  55735. * @see https://easings.net/#easeInExpo
  55736. * @param exponent Defines the exponent of the function
  55737. */
  55738. function ExponentialEase(
  55739. /** Defines the exponent of the function */
  55740. exponent) {
  55741. if (exponent === void 0) { exponent = 2; }
  55742. var _this = _super.call(this) || this;
  55743. _this.exponent = exponent;
  55744. return _this;
  55745. }
  55746. /** @hidden */
  55747. ExponentialEase.prototype.easeInCore = function (gradient) {
  55748. if (this.exponent <= 0) {
  55749. return gradient;
  55750. }
  55751. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  55752. };
  55753. return ExponentialEase;
  55754. }(EasingFunction));
  55755. BABYLON.ExponentialEase = ExponentialEase;
  55756. /**
  55757. * Easing function with a power shape (see link below).
  55758. * @see https://easings.net/#easeInQuad
  55759. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55760. */
  55761. var PowerEase = /** @class */ (function (_super) {
  55762. __extends(PowerEase, _super);
  55763. /**
  55764. * Instantiates an power base easing function
  55765. * @see https://easings.net/#easeInQuad
  55766. * @param power Defines the power of the function
  55767. */
  55768. function PowerEase(
  55769. /** Defines the power of the function */
  55770. power) {
  55771. if (power === void 0) { power = 2; }
  55772. var _this = _super.call(this) || this;
  55773. _this.power = power;
  55774. return _this;
  55775. }
  55776. /** @hidden */
  55777. PowerEase.prototype.easeInCore = function (gradient) {
  55778. var y = Math.max(0.0, this.power);
  55779. return Math.pow(gradient, y);
  55780. };
  55781. return PowerEase;
  55782. }(EasingFunction));
  55783. BABYLON.PowerEase = PowerEase;
  55784. /**
  55785. * Easing function with a power of 2 shape (see link below).
  55786. * @see https://easings.net/#easeInQuad
  55787. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55788. */
  55789. var QuadraticEase = /** @class */ (function (_super) {
  55790. __extends(QuadraticEase, _super);
  55791. function QuadraticEase() {
  55792. return _super !== null && _super.apply(this, arguments) || this;
  55793. }
  55794. /** @hidden */
  55795. QuadraticEase.prototype.easeInCore = function (gradient) {
  55796. return (gradient * gradient);
  55797. };
  55798. return QuadraticEase;
  55799. }(EasingFunction));
  55800. BABYLON.QuadraticEase = QuadraticEase;
  55801. /**
  55802. * Easing function with a power of 4 shape (see link below).
  55803. * @see https://easings.net/#easeInQuart
  55804. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55805. */
  55806. var QuarticEase = /** @class */ (function (_super) {
  55807. __extends(QuarticEase, _super);
  55808. function QuarticEase() {
  55809. return _super !== null && _super.apply(this, arguments) || this;
  55810. }
  55811. /** @hidden */
  55812. QuarticEase.prototype.easeInCore = function (gradient) {
  55813. return (gradient * gradient * gradient * gradient);
  55814. };
  55815. return QuarticEase;
  55816. }(EasingFunction));
  55817. BABYLON.QuarticEase = QuarticEase;
  55818. /**
  55819. * Easing function with a power of 5 shape (see link below).
  55820. * @see https://easings.net/#easeInQuint
  55821. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55822. */
  55823. var QuinticEase = /** @class */ (function (_super) {
  55824. __extends(QuinticEase, _super);
  55825. function QuinticEase() {
  55826. return _super !== null && _super.apply(this, arguments) || this;
  55827. }
  55828. /** @hidden */
  55829. QuinticEase.prototype.easeInCore = function (gradient) {
  55830. return (gradient * gradient * gradient * gradient * gradient);
  55831. };
  55832. return QuinticEase;
  55833. }(EasingFunction));
  55834. BABYLON.QuinticEase = QuinticEase;
  55835. /**
  55836. * Easing function with a sin shape (see link below).
  55837. * @see https://easings.net/#easeInSine
  55838. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55839. */
  55840. var SineEase = /** @class */ (function (_super) {
  55841. __extends(SineEase, _super);
  55842. function SineEase() {
  55843. return _super !== null && _super.apply(this, arguments) || this;
  55844. }
  55845. /** @hidden */
  55846. SineEase.prototype.easeInCore = function (gradient) {
  55847. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  55848. };
  55849. return SineEase;
  55850. }(EasingFunction));
  55851. BABYLON.SineEase = SineEase;
  55852. /**
  55853. * Easing function with a bezier shape (see link below).
  55854. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  55855. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55856. */
  55857. var BezierCurveEase = /** @class */ (function (_super) {
  55858. __extends(BezierCurveEase, _super);
  55859. /**
  55860. * Instantiates a bezier function
  55861. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  55862. * @param x1 Defines the x component of the start tangent in the bezier curve
  55863. * @param y1 Defines the y component of the start tangent in the bezier curve
  55864. * @param x2 Defines the x component of the end tangent in the bezier curve
  55865. * @param y2 Defines the y component of the end tangent in the bezier curve
  55866. */
  55867. function BezierCurveEase(
  55868. /** Defines the x component of the start tangent in the bezier curve */
  55869. x1,
  55870. /** Defines the y component of the start tangent in the bezier curve */
  55871. y1,
  55872. /** Defines the x component of the end tangent in the bezier curve */
  55873. x2,
  55874. /** Defines the y component of the end tangent in the bezier curve */
  55875. y2) {
  55876. if (x1 === void 0) { x1 = 0; }
  55877. if (y1 === void 0) { y1 = 0; }
  55878. if (x2 === void 0) { x2 = 1; }
  55879. if (y2 === void 0) { y2 = 1; }
  55880. var _this = _super.call(this) || this;
  55881. _this.x1 = x1;
  55882. _this.y1 = y1;
  55883. _this.x2 = x2;
  55884. _this.y2 = y2;
  55885. return _this;
  55886. }
  55887. /** @hidden */
  55888. BezierCurveEase.prototype.easeInCore = function (gradient) {
  55889. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  55890. };
  55891. return BezierCurveEase;
  55892. }(EasingFunction));
  55893. BABYLON.BezierCurveEase = BezierCurveEase;
  55894. })(BABYLON || (BABYLON = {}));
  55895. //# sourceMappingURL=babylon.easing.js.map
  55896. var BABYLON;
  55897. (function (BABYLON) {
  55898. /**
  55899. * A Condition applied to an Action
  55900. */
  55901. var Condition = /** @class */ (function () {
  55902. /**
  55903. * Creates a new Condition
  55904. * @param actionManager the manager of the action the condition is applied to
  55905. */
  55906. function Condition(actionManager) {
  55907. this._actionManager = actionManager;
  55908. }
  55909. /**
  55910. * Check if the current condition is valid
  55911. * @returns a boolean
  55912. */
  55913. Condition.prototype.isValid = function () {
  55914. return true;
  55915. };
  55916. /**
  55917. * Internal only
  55918. * @hidden
  55919. */
  55920. Condition.prototype._getProperty = function (propertyPath) {
  55921. return this._actionManager._getProperty(propertyPath);
  55922. };
  55923. /**
  55924. * Internal only
  55925. * @hidden
  55926. */
  55927. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  55928. return this._actionManager._getEffectiveTarget(target, propertyPath);
  55929. };
  55930. /**
  55931. * Serialize placeholder for child classes
  55932. * @returns the serialized object
  55933. */
  55934. Condition.prototype.serialize = function () {
  55935. };
  55936. /**
  55937. * Internal only
  55938. * @hidden
  55939. */
  55940. Condition.prototype._serialize = function (serializedCondition) {
  55941. return {
  55942. type: 2,
  55943. children: [],
  55944. name: serializedCondition.name,
  55945. properties: serializedCondition.properties
  55946. };
  55947. };
  55948. return Condition;
  55949. }());
  55950. BABYLON.Condition = Condition;
  55951. /**
  55952. * Defines specific conditional operators as extensions of Condition
  55953. */
  55954. var ValueCondition = /** @class */ (function (_super) {
  55955. __extends(ValueCondition, _super);
  55956. /**
  55957. * Creates a new ValueCondition
  55958. * @param actionManager manager for the action the condition applies to
  55959. * @param target for the action
  55960. * @param propertyPath path to specify the property of the target the conditional operator uses
  55961. * @param value the value compared by the conditional operator against the current value of the property
  55962. * @param operator the conditional operator, default ValueCondition.IsEqual
  55963. */
  55964. function ValueCondition(actionManager, target,
  55965. /** path to specify the property of the target the conditional operator uses */
  55966. propertyPath,
  55967. /** the value compared by the conditional operator against the current value of the property */
  55968. value,
  55969. /** the conditional operator, default ValueCondition.IsEqual */
  55970. operator) {
  55971. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  55972. var _this = _super.call(this, actionManager) || this;
  55973. _this.propertyPath = propertyPath;
  55974. _this.value = value;
  55975. _this.operator = operator;
  55976. _this._target = target;
  55977. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  55978. _this._property = _this._getProperty(_this.propertyPath);
  55979. return _this;
  55980. }
  55981. Object.defineProperty(ValueCondition, "IsEqual", {
  55982. /**
  55983. * returns the number for IsEqual
  55984. */
  55985. get: function () {
  55986. return ValueCondition._IsEqual;
  55987. },
  55988. enumerable: true,
  55989. configurable: true
  55990. });
  55991. Object.defineProperty(ValueCondition, "IsDifferent", {
  55992. /**
  55993. * Returns the number for IsDifferent
  55994. */
  55995. get: function () {
  55996. return ValueCondition._IsDifferent;
  55997. },
  55998. enumerable: true,
  55999. configurable: true
  56000. });
  56001. Object.defineProperty(ValueCondition, "IsGreater", {
  56002. /**
  56003. * Returns the number for IsGreater
  56004. */
  56005. get: function () {
  56006. return ValueCondition._IsGreater;
  56007. },
  56008. enumerable: true,
  56009. configurable: true
  56010. });
  56011. Object.defineProperty(ValueCondition, "IsLesser", {
  56012. /**
  56013. * Returns the number for IsLesser
  56014. */
  56015. get: function () {
  56016. return ValueCondition._IsLesser;
  56017. },
  56018. enumerable: true,
  56019. configurable: true
  56020. });
  56021. /**
  56022. * Compares the given value with the property value for the specified conditional operator
  56023. * @returns the result of the comparison
  56024. */
  56025. ValueCondition.prototype.isValid = function () {
  56026. switch (this.operator) {
  56027. case ValueCondition.IsGreater:
  56028. return this._effectiveTarget[this._property] > this.value;
  56029. case ValueCondition.IsLesser:
  56030. return this._effectiveTarget[this._property] < this.value;
  56031. case ValueCondition.IsEqual:
  56032. case ValueCondition.IsDifferent:
  56033. var check;
  56034. if (this.value.equals) {
  56035. check = this.value.equals(this._effectiveTarget[this._property]);
  56036. }
  56037. else {
  56038. check = this.value === this._effectiveTarget[this._property];
  56039. }
  56040. return this.operator === ValueCondition.IsEqual ? check : !check;
  56041. }
  56042. return false;
  56043. };
  56044. /**
  56045. * Serialize the ValueCondition into a JSON compatible object
  56046. * @returns serialization object
  56047. */
  56048. ValueCondition.prototype.serialize = function () {
  56049. return this._serialize({
  56050. name: "ValueCondition",
  56051. properties: [
  56052. BABYLON.Action._GetTargetProperty(this._target),
  56053. { name: "propertyPath", value: this.propertyPath },
  56054. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  56055. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  56056. ]
  56057. });
  56058. };
  56059. /**
  56060. * Gets the name of the conditional operator for the ValueCondition
  56061. * @param operator the conditional operator
  56062. * @returns the name
  56063. */
  56064. ValueCondition.GetOperatorName = function (operator) {
  56065. switch (operator) {
  56066. case ValueCondition._IsEqual: return "IsEqual";
  56067. case ValueCondition._IsDifferent: return "IsDifferent";
  56068. case ValueCondition._IsGreater: return "IsGreater";
  56069. case ValueCondition._IsLesser: return "IsLesser";
  56070. default: return "";
  56071. }
  56072. };
  56073. /**
  56074. * Internal only
  56075. * @hidden
  56076. */
  56077. ValueCondition._IsEqual = 0;
  56078. /**
  56079. * Internal only
  56080. * @hidden
  56081. */
  56082. ValueCondition._IsDifferent = 1;
  56083. /**
  56084. * Internal only
  56085. * @hidden
  56086. */
  56087. ValueCondition._IsGreater = 2;
  56088. /**
  56089. * Internal only
  56090. * @hidden
  56091. */
  56092. ValueCondition._IsLesser = 3;
  56093. return ValueCondition;
  56094. }(Condition));
  56095. BABYLON.ValueCondition = ValueCondition;
  56096. /**
  56097. * Defines a predicate condition as an extension of Condition
  56098. */
  56099. var PredicateCondition = /** @class */ (function (_super) {
  56100. __extends(PredicateCondition, _super);
  56101. /**
  56102. * Creates a new PredicateCondition
  56103. * @param actionManager manager for the action the condition applies to
  56104. * @param predicate defines the predicate function used to validate the condition
  56105. */
  56106. function PredicateCondition(actionManager,
  56107. /** defines the predicate function used to validate the condition */
  56108. predicate) {
  56109. var _this = _super.call(this, actionManager) || this;
  56110. _this.predicate = predicate;
  56111. return _this;
  56112. }
  56113. /**
  56114. * @returns the validity of the predicate condition
  56115. */
  56116. PredicateCondition.prototype.isValid = function () {
  56117. return this.predicate();
  56118. };
  56119. return PredicateCondition;
  56120. }(Condition));
  56121. BABYLON.PredicateCondition = PredicateCondition;
  56122. /**
  56123. * Defines a state condition as an extension of Condition
  56124. */
  56125. var StateCondition = /** @class */ (function (_super) {
  56126. __extends(StateCondition, _super);
  56127. /**
  56128. * Creates a new StateCondition
  56129. * @param actionManager manager for the action the condition applies to
  56130. * @param target of the condition
  56131. * @param value to compare with target state
  56132. */
  56133. function StateCondition(actionManager, target,
  56134. /** Value to compare with target state */
  56135. value) {
  56136. var _this = _super.call(this, actionManager) || this;
  56137. _this.value = value;
  56138. _this._target = target;
  56139. return _this;
  56140. }
  56141. /**
  56142. * Gets a boolean indicating if the current condition is met
  56143. * @returns the validity of the state
  56144. */
  56145. StateCondition.prototype.isValid = function () {
  56146. return this._target.state === this.value;
  56147. };
  56148. /**
  56149. * Serialize the StateCondition into a JSON compatible object
  56150. * @returns serialization object
  56151. */
  56152. StateCondition.prototype.serialize = function () {
  56153. return this._serialize({
  56154. name: "StateCondition",
  56155. properties: [
  56156. BABYLON.Action._GetTargetProperty(this._target),
  56157. { name: "value", value: this.value }
  56158. ]
  56159. });
  56160. };
  56161. return StateCondition;
  56162. }(Condition));
  56163. BABYLON.StateCondition = StateCondition;
  56164. })(BABYLON || (BABYLON = {}));
  56165. //# sourceMappingURL=babylon.condition.js.map
  56166. var BABYLON;
  56167. (function (BABYLON) {
  56168. /**
  56169. * The action to be carried out following a trigger
  56170. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  56171. */
  56172. var Action = /** @class */ (function () {
  56173. /**
  56174. * Creates a new Action
  56175. * @param triggerOptions the trigger, with or without parameters, for the action
  56176. * @param condition an optional determinant of action
  56177. */
  56178. function Action(
  56179. /** the trigger, with or without parameters, for the action */
  56180. triggerOptions, condition) {
  56181. this.triggerOptions = triggerOptions;
  56182. /**
  56183. * An event triggered prior to action being executed.
  56184. */
  56185. this.onBeforeExecuteObservable = new BABYLON.Observable();
  56186. if (triggerOptions.parameter) {
  56187. this.trigger = triggerOptions.trigger;
  56188. this._triggerParameter = triggerOptions.parameter;
  56189. }
  56190. else if (triggerOptions.trigger) {
  56191. this.trigger = triggerOptions.trigger;
  56192. }
  56193. else {
  56194. this.trigger = triggerOptions;
  56195. }
  56196. this._nextActiveAction = this;
  56197. this._condition = condition;
  56198. }
  56199. /**
  56200. * Internal only
  56201. * @hidden
  56202. */
  56203. Action.prototype._prepare = function () {
  56204. };
  56205. /**
  56206. * Gets the trigger parameters
  56207. * @returns the trigger parameters
  56208. */
  56209. Action.prototype.getTriggerParameter = function () {
  56210. return this._triggerParameter;
  56211. };
  56212. /**
  56213. * Internal only - executes current action event
  56214. * @hidden
  56215. */
  56216. Action.prototype._executeCurrent = function (evt) {
  56217. if (this._nextActiveAction._condition) {
  56218. var condition = this._nextActiveAction._condition;
  56219. var currentRenderId = this._actionManager.getScene().getRenderId();
  56220. // We cache the current evaluation for the current frame
  56221. if (condition._evaluationId === currentRenderId) {
  56222. if (!condition._currentResult) {
  56223. return;
  56224. }
  56225. }
  56226. else {
  56227. condition._evaluationId = currentRenderId;
  56228. if (!condition.isValid()) {
  56229. condition._currentResult = false;
  56230. return;
  56231. }
  56232. condition._currentResult = true;
  56233. }
  56234. }
  56235. this.onBeforeExecuteObservable.notifyObservers(this);
  56236. this._nextActiveAction.execute(evt);
  56237. this.skipToNextActiveAction();
  56238. };
  56239. /**
  56240. * Execute placeholder for child classes
  56241. * @param evt optional action event
  56242. */
  56243. Action.prototype.execute = function (evt) {
  56244. };
  56245. /**
  56246. * Skips to next active action
  56247. */
  56248. Action.prototype.skipToNextActiveAction = function () {
  56249. if (this._nextActiveAction._child) {
  56250. if (!this._nextActiveAction._child._actionManager) {
  56251. this._nextActiveAction._child._actionManager = this._actionManager;
  56252. }
  56253. this._nextActiveAction = this._nextActiveAction._child;
  56254. }
  56255. else {
  56256. this._nextActiveAction = this;
  56257. }
  56258. };
  56259. /**
  56260. * Adds action to chain of actions, may be a DoNothingAction
  56261. * @param action defines the next action to execute
  56262. * @returns The action passed in
  56263. * @see https://www.babylonjs-playground.com/#1T30HR#0
  56264. */
  56265. Action.prototype.then = function (action) {
  56266. this._child = action;
  56267. action._actionManager = this._actionManager;
  56268. action._prepare();
  56269. return action;
  56270. };
  56271. /**
  56272. * Internal only
  56273. * @hidden
  56274. */
  56275. Action.prototype._getProperty = function (propertyPath) {
  56276. return this._actionManager._getProperty(propertyPath);
  56277. };
  56278. /**
  56279. * Internal only
  56280. * @hidden
  56281. */
  56282. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  56283. return this._actionManager._getEffectiveTarget(target, propertyPath);
  56284. };
  56285. /**
  56286. * Serialize placeholder for child classes
  56287. * @param parent of child
  56288. * @returns the serialized object
  56289. */
  56290. Action.prototype.serialize = function (parent) {
  56291. };
  56292. /**
  56293. * Internal only called by serialize
  56294. * @hidden
  56295. */
  56296. Action.prototype._serialize = function (serializedAction, parent) {
  56297. var serializationObject = {
  56298. type: 1,
  56299. children: [],
  56300. name: serializedAction.name,
  56301. properties: serializedAction.properties || []
  56302. };
  56303. // Serialize child
  56304. if (this._child) {
  56305. this._child.serialize(serializationObject);
  56306. }
  56307. // Check if "this" has a condition
  56308. if (this._condition) {
  56309. var serializedCondition = this._condition.serialize();
  56310. serializedCondition.children.push(serializationObject);
  56311. if (parent) {
  56312. parent.children.push(serializedCondition);
  56313. }
  56314. return serializedCondition;
  56315. }
  56316. if (parent) {
  56317. parent.children.push(serializationObject);
  56318. }
  56319. return serializationObject;
  56320. };
  56321. /**
  56322. * Internal only
  56323. * @hidden
  56324. */
  56325. Action._SerializeValueAsString = function (value) {
  56326. if (typeof value === "number") {
  56327. return value.toString();
  56328. }
  56329. if (typeof value === "boolean") {
  56330. return value ? "true" : "false";
  56331. }
  56332. if (value instanceof BABYLON.Vector2) {
  56333. return value.x + ", " + value.y;
  56334. }
  56335. if (value instanceof BABYLON.Vector3) {
  56336. return value.x + ", " + value.y + ", " + value.z;
  56337. }
  56338. if (value instanceof BABYLON.Color3) {
  56339. return value.r + ", " + value.g + ", " + value.b;
  56340. }
  56341. if (value instanceof BABYLON.Color4) {
  56342. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  56343. }
  56344. return value; // string
  56345. };
  56346. /**
  56347. * Internal only
  56348. * @hidden
  56349. */
  56350. Action._GetTargetProperty = function (target) {
  56351. return {
  56352. name: "target",
  56353. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  56354. : target instanceof BABYLON.Light ? "LightProperties"
  56355. : target instanceof BABYLON.Camera ? "CameraProperties"
  56356. : "SceneProperties",
  56357. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  56358. };
  56359. };
  56360. return Action;
  56361. }());
  56362. BABYLON.Action = Action;
  56363. })(BABYLON || (BABYLON = {}));
  56364. //# sourceMappingURL=babylon.action.js.map
  56365. var BABYLON;
  56366. (function (BABYLON) {
  56367. /**
  56368. * ActionEvent is the event being sent when an action is triggered.
  56369. */
  56370. var ActionEvent = /** @class */ (function () {
  56371. /**
  56372. * Creates a new ActionEvent
  56373. * @param source The mesh or sprite that triggered the action
  56374. * @param pointerX The X mouse cursor position at the time of the event
  56375. * @param pointerY The Y mouse cursor position at the time of the event
  56376. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  56377. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  56378. * @param additionalData additional data for the event
  56379. */
  56380. function ActionEvent(
  56381. /** The mesh or sprite that triggered the action */
  56382. source,
  56383. /** The X mouse cursor position at the time of the event */
  56384. pointerX,
  56385. /** The Y mouse cursor position at the time of the event */
  56386. pointerY,
  56387. /** The mesh that is currently pointed at (can be null) */
  56388. meshUnderPointer,
  56389. /** the original (browser) event that triggered the ActionEvent */
  56390. sourceEvent,
  56391. /** additional data for the event */
  56392. additionalData) {
  56393. this.source = source;
  56394. this.pointerX = pointerX;
  56395. this.pointerY = pointerY;
  56396. this.meshUnderPointer = meshUnderPointer;
  56397. this.sourceEvent = sourceEvent;
  56398. this.additionalData = additionalData;
  56399. }
  56400. /**
  56401. * Helper function to auto-create an ActionEvent from a source mesh.
  56402. * @param source The source mesh that triggered the event
  56403. * @param evt The original (browser) event
  56404. * @param additionalData additional data for the event
  56405. * @returns the new ActionEvent
  56406. */
  56407. ActionEvent.CreateNew = function (source, evt, additionalData) {
  56408. var scene = source.getScene();
  56409. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  56410. };
  56411. /**
  56412. * Helper function to auto-create an ActionEvent from a source sprite
  56413. * @param source The source sprite that triggered the event
  56414. * @param scene Scene associated with the sprite
  56415. * @param evt The original (browser) event
  56416. * @param additionalData additional data for the event
  56417. * @returns the new ActionEvent
  56418. */
  56419. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  56420. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  56421. };
  56422. /**
  56423. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  56424. * @param scene the scene where the event occurred
  56425. * @param evt The original (browser) event
  56426. * @returns the new ActionEvent
  56427. */
  56428. ActionEvent.CreateNewFromScene = function (scene, evt) {
  56429. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  56430. };
  56431. /**
  56432. * Helper function to auto-create an ActionEvent from a primitive
  56433. * @param prim defines the target primitive
  56434. * @param pointerPos defines the pointer position
  56435. * @param evt The original (browser) event
  56436. * @param additionalData additional data for the event
  56437. * @returns the new ActionEvent
  56438. */
  56439. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  56440. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  56441. };
  56442. return ActionEvent;
  56443. }());
  56444. BABYLON.ActionEvent = ActionEvent;
  56445. /**
  56446. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  56447. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  56448. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56449. */
  56450. var ActionManager = /** @class */ (function () {
  56451. /**
  56452. * Creates a new action manager
  56453. * @param scene defines the hosting scene
  56454. */
  56455. function ActionManager(scene) {
  56456. // Members
  56457. /** Gets the list of actions */
  56458. this.actions = new Array();
  56459. /** Gets the cursor to use when hovering items */
  56460. this.hoverCursor = '';
  56461. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56462. scene.actionManagers.push(this);
  56463. }
  56464. // Methods
  56465. /**
  56466. * Releases all associated resources
  56467. */
  56468. ActionManager.prototype.dispose = function () {
  56469. var index = this._scene.actionManagers.indexOf(this);
  56470. for (var i = 0; i < this.actions.length; i++) {
  56471. var action = this.actions[i];
  56472. ActionManager.Triggers[action.trigger]--;
  56473. if (ActionManager.Triggers[action.trigger] === 0) {
  56474. delete ActionManager.Triggers[action.trigger];
  56475. }
  56476. }
  56477. if (index > -1) {
  56478. this._scene.actionManagers.splice(index, 1);
  56479. }
  56480. };
  56481. /**
  56482. * Gets hosting scene
  56483. * @returns the hosting scene
  56484. */
  56485. ActionManager.prototype.getScene = function () {
  56486. return this._scene;
  56487. };
  56488. /**
  56489. * Does this action manager handles actions of any of the given triggers
  56490. * @param triggers defines the triggers to be tested
  56491. * @return a boolean indicating whether one (or more) of the triggers is handled
  56492. */
  56493. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  56494. for (var index = 0; index < this.actions.length; index++) {
  56495. var action = this.actions[index];
  56496. if (triggers.indexOf(action.trigger) > -1) {
  56497. return true;
  56498. }
  56499. }
  56500. return false;
  56501. };
  56502. /**
  56503. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  56504. * speed.
  56505. * @param triggerA defines the trigger to be tested
  56506. * @param triggerB defines the trigger to be tested
  56507. * @return a boolean indicating whether one (or more) of the triggers is handled
  56508. */
  56509. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  56510. for (var index = 0; index < this.actions.length; index++) {
  56511. var action = this.actions[index];
  56512. if (triggerA == action.trigger || triggerB == action.trigger) {
  56513. return true;
  56514. }
  56515. }
  56516. return false;
  56517. };
  56518. /**
  56519. * Does this action manager handles actions of a given trigger
  56520. * @param trigger defines the trigger to be tested
  56521. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  56522. * @return whether the trigger is handled
  56523. */
  56524. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  56525. for (var index = 0; index < this.actions.length; index++) {
  56526. var action = this.actions[index];
  56527. if (action.trigger === trigger) {
  56528. if (parameterPredicate) {
  56529. if (parameterPredicate(action.getTriggerParameter())) {
  56530. return true;
  56531. }
  56532. }
  56533. else {
  56534. return true;
  56535. }
  56536. }
  56537. }
  56538. return false;
  56539. };
  56540. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  56541. /**
  56542. * Does this action manager has pointer triggers
  56543. */
  56544. get: function () {
  56545. for (var index = 0; index < this.actions.length; index++) {
  56546. var action = this.actions[index];
  56547. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  56548. return true;
  56549. }
  56550. }
  56551. return false;
  56552. },
  56553. enumerable: true,
  56554. configurable: true
  56555. });
  56556. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  56557. /**
  56558. * Does this action manager has pick triggers
  56559. */
  56560. get: function () {
  56561. for (var index = 0; index < this.actions.length; index++) {
  56562. var action = this.actions[index];
  56563. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  56564. return true;
  56565. }
  56566. }
  56567. return false;
  56568. },
  56569. enumerable: true,
  56570. configurable: true
  56571. });
  56572. Object.defineProperty(ActionManager, "HasTriggers", {
  56573. /**
  56574. * Does exist one action manager with at least one trigger
  56575. **/
  56576. get: function () {
  56577. for (var t in ActionManager.Triggers) {
  56578. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56579. return true;
  56580. }
  56581. }
  56582. return false;
  56583. },
  56584. enumerable: true,
  56585. configurable: true
  56586. });
  56587. Object.defineProperty(ActionManager, "HasPickTriggers", {
  56588. /**
  56589. * Does exist one action manager with at least one pick trigger
  56590. **/
  56591. get: function () {
  56592. for (var t in ActionManager.Triggers) {
  56593. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56594. var t_int = parseInt(t);
  56595. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  56596. return true;
  56597. }
  56598. }
  56599. }
  56600. return false;
  56601. },
  56602. enumerable: true,
  56603. configurable: true
  56604. });
  56605. /**
  56606. * Does exist one action manager that handles actions of a given trigger
  56607. * @param trigger defines the trigger to be tested
  56608. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  56609. **/
  56610. ActionManager.HasSpecificTrigger = function (trigger) {
  56611. for (var t in ActionManager.Triggers) {
  56612. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56613. var t_int = parseInt(t);
  56614. if (t_int === trigger) {
  56615. return true;
  56616. }
  56617. }
  56618. }
  56619. return false;
  56620. };
  56621. /**
  56622. * Registers an action to this action manager
  56623. * @param action defines the action to be registered
  56624. * @return the action amended (prepared) after registration
  56625. */
  56626. ActionManager.prototype.registerAction = function (action) {
  56627. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  56628. if (this.getScene().actionManager !== this) {
  56629. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  56630. return null;
  56631. }
  56632. }
  56633. this.actions.push(action);
  56634. if (ActionManager.Triggers[action.trigger]) {
  56635. ActionManager.Triggers[action.trigger]++;
  56636. }
  56637. else {
  56638. ActionManager.Triggers[action.trigger] = 1;
  56639. }
  56640. action._actionManager = this;
  56641. action._prepare();
  56642. return action;
  56643. };
  56644. /**
  56645. * Unregisters an action to this action manager
  56646. * @param action defines the action to be unregistered
  56647. * @return a boolean indicating whether the action has been unregistered
  56648. */
  56649. ActionManager.prototype.unregisterAction = function (action) {
  56650. var index = this.actions.indexOf(action);
  56651. if (index !== -1) {
  56652. this.actions.splice(index, 1);
  56653. ActionManager.Triggers[action.trigger] -= 1;
  56654. if (ActionManager.Triggers[action.trigger] === 0) {
  56655. delete ActionManager.Triggers[action.trigger];
  56656. }
  56657. delete action._actionManager;
  56658. return true;
  56659. }
  56660. return false;
  56661. };
  56662. /**
  56663. * Process a specific trigger
  56664. * @param trigger defines the trigger to process
  56665. * @param evt defines the event details to be processed
  56666. */
  56667. ActionManager.prototype.processTrigger = function (trigger, evt) {
  56668. for (var index = 0; index < this.actions.length; index++) {
  56669. var action = this.actions[index];
  56670. if (action.trigger === trigger) {
  56671. if (evt) {
  56672. if (trigger === ActionManager.OnKeyUpTrigger
  56673. || trigger === ActionManager.OnKeyDownTrigger) {
  56674. var parameter = action.getTriggerParameter();
  56675. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  56676. if (!parameter.toLowerCase) {
  56677. continue;
  56678. }
  56679. var lowerCase = parameter.toLowerCase();
  56680. if (lowerCase !== evt.sourceEvent.key) {
  56681. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  56682. var actualkey = String.fromCharCode(unicode).toLowerCase();
  56683. if (actualkey !== lowerCase) {
  56684. continue;
  56685. }
  56686. }
  56687. }
  56688. }
  56689. }
  56690. action._executeCurrent(evt);
  56691. }
  56692. }
  56693. };
  56694. /** @hidden */
  56695. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  56696. var properties = propertyPath.split(".");
  56697. for (var index = 0; index < properties.length - 1; index++) {
  56698. target = target[properties[index]];
  56699. }
  56700. return target;
  56701. };
  56702. /** @hidden */
  56703. ActionManager.prototype._getProperty = function (propertyPath) {
  56704. var properties = propertyPath.split(".");
  56705. return properties[properties.length - 1];
  56706. };
  56707. /**
  56708. * Serialize this manager to a JSON object
  56709. * @param name defines the property name to store this manager
  56710. * @returns a JSON representation of this manager
  56711. */
  56712. ActionManager.prototype.serialize = function (name) {
  56713. var root = {
  56714. children: new Array(),
  56715. name: name,
  56716. type: 3,
  56717. properties: new Array() // Empty for root but required
  56718. };
  56719. for (var i = 0; i < this.actions.length; i++) {
  56720. var triggerObject = {
  56721. type: 0,
  56722. children: new Array(),
  56723. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  56724. properties: new Array()
  56725. };
  56726. var triggerOptions = this.actions[i].triggerOptions;
  56727. if (triggerOptions && typeof triggerOptions !== "number") {
  56728. if (triggerOptions.parameter instanceof BABYLON.Node) {
  56729. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  56730. }
  56731. else {
  56732. var parameter = {};
  56733. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  56734. if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
  56735. parameter._meshId = triggerOptions.parameter.mesh.id;
  56736. }
  56737. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  56738. }
  56739. }
  56740. // Serialize child action, recursively
  56741. this.actions[i].serialize(triggerObject);
  56742. // Add serialized trigger
  56743. root.children.push(triggerObject);
  56744. }
  56745. return root;
  56746. };
  56747. /**
  56748. * Creates a new ActionManager from a JSON data
  56749. * @param parsedActions defines the JSON data to read from
  56750. * @param object defines the hosting mesh
  56751. * @param scene defines the hosting scene
  56752. */
  56753. ActionManager.Parse = function (parsedActions, object, scene) {
  56754. var actionManager = new ActionManager(scene);
  56755. if (object === null) {
  56756. scene.actionManager = actionManager;
  56757. }
  56758. else {
  56759. object.actionManager = actionManager;
  56760. }
  56761. // instanciate a new object
  56762. var instanciate = function (name, params) {
  56763. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  56764. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  56765. newInstance.constructor.apply(newInstance, params);
  56766. return newInstance;
  56767. };
  56768. var parseParameter = function (name, value, target, propertyPath) {
  56769. if (propertyPath === null) {
  56770. // String, boolean or float
  56771. var floatValue = parseFloat(value);
  56772. if (value === "true" || value === "false") {
  56773. return value === "true";
  56774. }
  56775. else {
  56776. return isNaN(floatValue) ? value : floatValue;
  56777. }
  56778. }
  56779. var effectiveTarget = propertyPath.split(".");
  56780. var values = value.split(",");
  56781. // Get effective Target
  56782. for (var i = 0; i < effectiveTarget.length; i++) {
  56783. target = target[effectiveTarget[i]];
  56784. }
  56785. // Return appropriate value with its type
  56786. if (typeof (target) === "boolean") {
  56787. return values[0] === "true";
  56788. }
  56789. if (typeof (target) === "string") {
  56790. return values[0];
  56791. }
  56792. // Parameters with multiple values such as Vector3 etc.
  56793. var split = new Array();
  56794. for (var i = 0; i < values.length; i++) {
  56795. split.push(parseFloat(values[i]));
  56796. }
  56797. if (target instanceof BABYLON.Vector3) {
  56798. return BABYLON.Vector3.FromArray(split);
  56799. }
  56800. if (target instanceof BABYLON.Vector4) {
  56801. return BABYLON.Vector4.FromArray(split);
  56802. }
  56803. if (target instanceof BABYLON.Color3) {
  56804. return BABYLON.Color3.FromArray(split);
  56805. }
  56806. if (target instanceof BABYLON.Color4) {
  56807. return BABYLON.Color4.FromArray(split);
  56808. }
  56809. return parseFloat(values[0]);
  56810. };
  56811. // traverse graph per trigger
  56812. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  56813. if (combineArray === void 0) { combineArray = null; }
  56814. if (parsedAction.detached) {
  56815. return;
  56816. }
  56817. var parameters = new Array();
  56818. var target = null;
  56819. var propertyPath = null;
  56820. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  56821. // Parameters
  56822. if (parsedAction.type === 2) {
  56823. parameters.push(actionManager);
  56824. }
  56825. else {
  56826. parameters.push(trigger);
  56827. }
  56828. if (combine) {
  56829. var actions = new Array();
  56830. for (var j = 0; j < parsedAction.combine.length; j++) {
  56831. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  56832. }
  56833. parameters.push(actions);
  56834. }
  56835. else {
  56836. for (var i = 0; i < parsedAction.properties.length; i++) {
  56837. var value = parsedAction.properties[i].value;
  56838. var name = parsedAction.properties[i].name;
  56839. var targetType = parsedAction.properties[i].targetType;
  56840. if (name === "target") {
  56841. if (targetType !== null && targetType === "SceneProperties") {
  56842. value = target = scene;
  56843. }
  56844. else {
  56845. value = target = scene.getNodeByName(value);
  56846. }
  56847. }
  56848. else if (name === "parent") {
  56849. value = scene.getNodeByName(value);
  56850. }
  56851. else if (name === "sound") {
  56852. // Can not externalize to component, so only checks for the presence off the API.
  56853. if (scene.getSoundByName) {
  56854. value = scene.getSoundByName(value);
  56855. }
  56856. }
  56857. else if (name !== "propertyPath") {
  56858. if (parsedAction.type === 2 && name === "operator") {
  56859. value = BABYLON.ValueCondition[value];
  56860. }
  56861. else {
  56862. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  56863. }
  56864. }
  56865. else {
  56866. propertyPath = value;
  56867. }
  56868. parameters.push(value);
  56869. }
  56870. }
  56871. if (combineArray === null) {
  56872. parameters.push(condition);
  56873. }
  56874. else {
  56875. parameters.push(null);
  56876. }
  56877. // If interpolate value action
  56878. if (parsedAction.name === "InterpolateValueAction") {
  56879. var param = parameters[parameters.length - 2];
  56880. parameters[parameters.length - 1] = param;
  56881. parameters[parameters.length - 2] = condition;
  56882. }
  56883. // Action or condition(s) and not CombineAction
  56884. var newAction = instanciate(parsedAction.name, parameters);
  56885. if (newAction instanceof BABYLON.Condition && condition !== null) {
  56886. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  56887. if (action) {
  56888. action.then(nothing);
  56889. }
  56890. else {
  56891. actionManager.registerAction(nothing);
  56892. }
  56893. action = nothing;
  56894. }
  56895. if (combineArray === null) {
  56896. if (newAction instanceof BABYLON.Condition) {
  56897. condition = newAction;
  56898. newAction = action;
  56899. }
  56900. else {
  56901. condition = null;
  56902. if (action) {
  56903. action.then(newAction);
  56904. }
  56905. else {
  56906. actionManager.registerAction(newAction);
  56907. }
  56908. }
  56909. }
  56910. else {
  56911. combineArray.push(newAction);
  56912. }
  56913. for (var i = 0; i < parsedAction.children.length; i++) {
  56914. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  56915. }
  56916. };
  56917. // triggers
  56918. for (var i = 0; i < parsedActions.children.length; i++) {
  56919. var triggerParams;
  56920. var trigger = parsedActions.children[i];
  56921. if (trigger.properties.length > 0) {
  56922. var param = trigger.properties[0].value;
  56923. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  56924. if (value._meshId) {
  56925. value.mesh = scene.getMeshByID(value._meshId);
  56926. }
  56927. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  56928. }
  56929. else {
  56930. triggerParams = ActionManager[trigger.name];
  56931. }
  56932. for (var j = 0; j < trigger.children.length; j++) {
  56933. if (!trigger.detached) {
  56934. traverse(trigger.children[j], triggerParams, null, null);
  56935. }
  56936. }
  56937. }
  56938. };
  56939. /**
  56940. * Get a trigger name by index
  56941. * @param trigger defines the trigger index
  56942. * @returns a trigger name
  56943. */
  56944. ActionManager.GetTriggerName = function (trigger) {
  56945. switch (trigger) {
  56946. case 0: return "NothingTrigger";
  56947. case 1: return "OnPickTrigger";
  56948. case 2: return "OnLeftPickTrigger";
  56949. case 3: return "OnRightPickTrigger";
  56950. case 4: return "OnCenterPickTrigger";
  56951. case 5: return "OnPickDownTrigger";
  56952. case 6: return "OnPickUpTrigger";
  56953. case 7: return "OnLongPressTrigger";
  56954. case 8: return "OnPointerOverTrigger";
  56955. case 9: return "OnPointerOutTrigger";
  56956. case 10: return "OnEveryFrameTrigger";
  56957. case 11: return "OnIntersectionEnterTrigger";
  56958. case 12: return "OnIntersectionExitTrigger";
  56959. case 13: return "OnKeyDownTrigger";
  56960. case 14: return "OnKeyUpTrigger";
  56961. case 15: return "OnPickOutTrigger";
  56962. default: return "";
  56963. }
  56964. };
  56965. /**
  56966. * Nothing
  56967. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  56968. */
  56969. ActionManager.NothingTrigger = 0;
  56970. /**
  56971. * On pick
  56972. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  56973. */
  56974. ActionManager.OnPickTrigger = 1;
  56975. /**
  56976. * On left pick
  56977. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  56978. */
  56979. ActionManager.OnLeftPickTrigger = 2;
  56980. /**
  56981. * On right pick
  56982. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  56983. */
  56984. ActionManager.OnRightPickTrigger = 3;
  56985. /**
  56986. * On center pick
  56987. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  56988. */
  56989. ActionManager.OnCenterPickTrigger = 4;
  56990. /**
  56991. * On pick down
  56992. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  56993. */
  56994. ActionManager.OnPickDownTrigger = 5;
  56995. /**
  56996. * On double pick
  56997. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  56998. */
  56999. ActionManager.OnDoublePickTrigger = 6;
  57000. /**
  57001. * On pick up
  57002. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57003. */
  57004. ActionManager.OnPickUpTrigger = 7;
  57005. /**
  57006. * On pick out.
  57007. * This trigger will only be raised if you also declared a OnPickDown
  57008. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57009. */
  57010. ActionManager.OnPickOutTrigger = 16;
  57011. /**
  57012. * On long press
  57013. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57014. */
  57015. ActionManager.OnLongPressTrigger = 8;
  57016. /**
  57017. * On pointer over
  57018. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57019. */
  57020. ActionManager.OnPointerOverTrigger = 9;
  57021. /**
  57022. * On pointer out
  57023. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57024. */
  57025. ActionManager.OnPointerOutTrigger = 10;
  57026. /**
  57027. * On every frame
  57028. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57029. */
  57030. ActionManager.OnEveryFrameTrigger = 11;
  57031. /**
  57032. * On intersection enter
  57033. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57034. */
  57035. ActionManager.OnIntersectionEnterTrigger = 12;
  57036. /**
  57037. * On intersection exit
  57038. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57039. */
  57040. ActionManager.OnIntersectionExitTrigger = 13;
  57041. /**
  57042. * On key down
  57043. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57044. */
  57045. ActionManager.OnKeyDownTrigger = 14;
  57046. /**
  57047. * On key up
  57048. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57049. */
  57050. ActionManager.OnKeyUpTrigger = 15;
  57051. /** Gets the list of active triggers */
  57052. ActionManager.Triggers = {};
  57053. return ActionManager;
  57054. }());
  57055. BABYLON.ActionManager = ActionManager;
  57056. })(BABYLON || (BABYLON = {}));
  57057. //# sourceMappingURL=babylon.actionManager.js.map
  57058. var BABYLON;
  57059. (function (BABYLON) {
  57060. /**
  57061. * This defines an action responsible to change the value of a property
  57062. * by interpolating between its current value and the newly set one once triggered.
  57063. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57064. */
  57065. var InterpolateValueAction = /** @class */ (function (_super) {
  57066. __extends(InterpolateValueAction, _super);
  57067. /**
  57068. * Instantiate the action
  57069. * @param triggerOptions defines the trigger options
  57070. * @param target defines the object containing the value to interpolate
  57071. * @param propertyPath defines the path to the property in the target object
  57072. * @param value defines the target value at the end of the interpolation
  57073. * @param duration deines the time it will take for the property to interpolate to the value.
  57074. * @param condition defines the trigger related conditions
  57075. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  57076. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  57077. */
  57078. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  57079. if (duration === void 0) { duration = 1000; }
  57080. var _this = _super.call(this, triggerOptions, condition) || this;
  57081. /**
  57082. * Defines the time it will take for the property to interpolate to the value.
  57083. */
  57084. _this.duration = 1000;
  57085. /**
  57086. * Observable triggered once the interpolation animation has been done.
  57087. */
  57088. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  57089. _this.propertyPath = propertyPath;
  57090. _this.value = value;
  57091. _this.duration = duration;
  57092. _this.stopOtherAnimations = stopOtherAnimations;
  57093. _this.onInterpolationDone = onInterpolationDone;
  57094. _this._target = _this._effectiveTarget = target;
  57095. return _this;
  57096. }
  57097. /** @hidden */
  57098. InterpolateValueAction.prototype._prepare = function () {
  57099. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57100. this._property = this._getProperty(this.propertyPath);
  57101. };
  57102. /**
  57103. * Execute the action starts the value interpolation.
  57104. */
  57105. InterpolateValueAction.prototype.execute = function () {
  57106. var _this = this;
  57107. var scene = this._actionManager.getScene();
  57108. var keys = [
  57109. {
  57110. frame: 0,
  57111. value: this._effectiveTarget[this._property]
  57112. }, {
  57113. frame: 100,
  57114. value: this.value
  57115. }
  57116. ];
  57117. var dataType;
  57118. if (typeof this.value === "number") {
  57119. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  57120. }
  57121. else if (this.value instanceof BABYLON.Color3) {
  57122. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  57123. }
  57124. else if (this.value instanceof BABYLON.Vector3) {
  57125. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  57126. }
  57127. else if (this.value instanceof BABYLON.Matrix) {
  57128. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  57129. }
  57130. else if (this.value instanceof BABYLON.Quaternion) {
  57131. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  57132. }
  57133. else {
  57134. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  57135. return;
  57136. }
  57137. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  57138. animation.setKeys(keys);
  57139. if (this.stopOtherAnimations) {
  57140. scene.stopAnimation(this._effectiveTarget);
  57141. }
  57142. var wrapper = function () {
  57143. _this.onInterpolationDoneObservable.notifyObservers(_this);
  57144. if (_this.onInterpolationDone) {
  57145. _this.onInterpolationDone();
  57146. }
  57147. };
  57148. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  57149. };
  57150. /**
  57151. * Serializes the actions and its related information.
  57152. * @param parent defines the object to serialize in
  57153. * @returns the serialized object
  57154. */
  57155. InterpolateValueAction.prototype.serialize = function (parent) {
  57156. return _super.prototype._serialize.call(this, {
  57157. name: "InterpolateValueAction",
  57158. properties: [
  57159. BABYLON.Action._GetTargetProperty(this._target),
  57160. { name: "propertyPath", value: this.propertyPath },
  57161. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  57162. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  57163. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  57164. ]
  57165. }, parent);
  57166. };
  57167. return InterpolateValueAction;
  57168. }(BABYLON.Action));
  57169. BABYLON.InterpolateValueAction = InterpolateValueAction;
  57170. })(BABYLON || (BABYLON = {}));
  57171. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  57172. var BABYLON;
  57173. (function (BABYLON) {
  57174. /**
  57175. * This defines an action responsible to toggle a boolean once triggered.
  57176. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57177. */
  57178. var SwitchBooleanAction = /** @class */ (function (_super) {
  57179. __extends(SwitchBooleanAction, _super);
  57180. /**
  57181. * Instantiate the action
  57182. * @param triggerOptions defines the trigger options
  57183. * @param target defines the object containing the boolean
  57184. * @param propertyPath defines the path to the boolean property in the target object
  57185. * @param condition defines the trigger related conditions
  57186. */
  57187. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  57188. var _this = _super.call(this, triggerOptions, condition) || this;
  57189. _this.propertyPath = propertyPath;
  57190. _this._target = _this._effectiveTarget = target;
  57191. return _this;
  57192. }
  57193. /** @hidden */
  57194. SwitchBooleanAction.prototype._prepare = function () {
  57195. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57196. this._property = this._getProperty(this.propertyPath);
  57197. };
  57198. /**
  57199. * Execute the action toggle the boolean value.
  57200. */
  57201. SwitchBooleanAction.prototype.execute = function () {
  57202. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  57203. };
  57204. /**
  57205. * Serializes the actions and its related information.
  57206. * @param parent defines the object to serialize in
  57207. * @returns the serialized object
  57208. */
  57209. SwitchBooleanAction.prototype.serialize = function (parent) {
  57210. return _super.prototype._serialize.call(this, {
  57211. name: "SwitchBooleanAction",
  57212. properties: [
  57213. BABYLON.Action._GetTargetProperty(this._target),
  57214. { name: "propertyPath", value: this.propertyPath }
  57215. ]
  57216. }, parent);
  57217. };
  57218. return SwitchBooleanAction;
  57219. }(BABYLON.Action));
  57220. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  57221. /**
  57222. * This defines an action responsible to set a the state field of the target
  57223. * to a desired value once triggered.
  57224. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57225. */
  57226. var SetStateAction = /** @class */ (function (_super) {
  57227. __extends(SetStateAction, _super);
  57228. /**
  57229. * Instantiate the action
  57230. * @param triggerOptions defines the trigger options
  57231. * @param target defines the object containing the state property
  57232. * @param value defines the value to store in the state field
  57233. * @param condition defines the trigger related conditions
  57234. */
  57235. function SetStateAction(triggerOptions, target, value, condition) {
  57236. var _this = _super.call(this, triggerOptions, condition) || this;
  57237. _this.value = value;
  57238. _this._target = target;
  57239. return _this;
  57240. }
  57241. /**
  57242. * Execute the action and store the value on the target state property.
  57243. */
  57244. SetStateAction.prototype.execute = function () {
  57245. this._target.state = this.value;
  57246. };
  57247. /**
  57248. * Serializes the actions and its related information.
  57249. * @param parent defines the object to serialize in
  57250. * @returns the serialized object
  57251. */
  57252. SetStateAction.prototype.serialize = function (parent) {
  57253. return _super.prototype._serialize.call(this, {
  57254. name: "SetStateAction",
  57255. properties: [
  57256. BABYLON.Action._GetTargetProperty(this._target),
  57257. { name: "value", value: this.value }
  57258. ]
  57259. }, parent);
  57260. };
  57261. return SetStateAction;
  57262. }(BABYLON.Action));
  57263. BABYLON.SetStateAction = SetStateAction;
  57264. /**
  57265. * This defines an action responsible to set a property of the target
  57266. * to a desired value once triggered.
  57267. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57268. */
  57269. var SetValueAction = /** @class */ (function (_super) {
  57270. __extends(SetValueAction, _super);
  57271. /**
  57272. * Instantiate the action
  57273. * @param triggerOptions defines the trigger options
  57274. * @param target defines the object containing the property
  57275. * @param propertyPath defines the path of the property to set in the target
  57276. * @param value defines the value to set in the property
  57277. * @param condition defines the trigger related conditions
  57278. */
  57279. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  57280. var _this = _super.call(this, triggerOptions, condition) || this;
  57281. _this.propertyPath = propertyPath;
  57282. _this.value = value;
  57283. _this._target = _this._effectiveTarget = target;
  57284. return _this;
  57285. }
  57286. /** @hidden */
  57287. SetValueAction.prototype._prepare = function () {
  57288. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57289. this._property = this._getProperty(this.propertyPath);
  57290. };
  57291. /**
  57292. * Execute the action and set the targetted property to the desired value.
  57293. */
  57294. SetValueAction.prototype.execute = function () {
  57295. this._effectiveTarget[this._property] = this.value;
  57296. if (this._target.markAsDirty) {
  57297. this._target.markAsDirty(this._property);
  57298. }
  57299. };
  57300. /**
  57301. * Serializes the actions and its related information.
  57302. * @param parent defines the object to serialize in
  57303. * @returns the serialized object
  57304. */
  57305. SetValueAction.prototype.serialize = function (parent) {
  57306. return _super.prototype._serialize.call(this, {
  57307. name: "SetValueAction",
  57308. properties: [
  57309. BABYLON.Action._GetTargetProperty(this._target),
  57310. { name: "propertyPath", value: this.propertyPath },
  57311. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  57312. ]
  57313. }, parent);
  57314. };
  57315. return SetValueAction;
  57316. }(BABYLON.Action));
  57317. BABYLON.SetValueAction = SetValueAction;
  57318. /**
  57319. * This defines an action responsible to increment the target value
  57320. * to a desired value once triggered.
  57321. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57322. */
  57323. var IncrementValueAction = /** @class */ (function (_super) {
  57324. __extends(IncrementValueAction, _super);
  57325. /**
  57326. * Instantiate the action
  57327. * @param triggerOptions defines the trigger options
  57328. * @param target defines the object containing the property
  57329. * @param propertyPath defines the path of the property to increment in the target
  57330. * @param value defines the value value we should increment the property by
  57331. * @param condition defines the trigger related conditions
  57332. */
  57333. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  57334. var _this = _super.call(this, triggerOptions, condition) || this;
  57335. _this.propertyPath = propertyPath;
  57336. _this.value = value;
  57337. _this._target = _this._effectiveTarget = target;
  57338. return _this;
  57339. }
  57340. /** @hidden */
  57341. IncrementValueAction.prototype._prepare = function () {
  57342. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57343. this._property = this._getProperty(this.propertyPath);
  57344. if (typeof this._effectiveTarget[this._property] !== "number") {
  57345. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  57346. }
  57347. };
  57348. /**
  57349. * Execute the action and increment the target of the value amount.
  57350. */
  57351. IncrementValueAction.prototype.execute = function () {
  57352. this._effectiveTarget[this._property] += this.value;
  57353. if (this._target.markAsDirty) {
  57354. this._target.markAsDirty(this._property);
  57355. }
  57356. };
  57357. /**
  57358. * Serializes the actions and its related information.
  57359. * @param parent defines the object to serialize in
  57360. * @returns the serialized object
  57361. */
  57362. IncrementValueAction.prototype.serialize = function (parent) {
  57363. return _super.prototype._serialize.call(this, {
  57364. name: "IncrementValueAction",
  57365. properties: [
  57366. BABYLON.Action._GetTargetProperty(this._target),
  57367. { name: "propertyPath", value: this.propertyPath },
  57368. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  57369. ]
  57370. }, parent);
  57371. };
  57372. return IncrementValueAction;
  57373. }(BABYLON.Action));
  57374. BABYLON.IncrementValueAction = IncrementValueAction;
  57375. /**
  57376. * This defines an action responsible to start an animation once triggered.
  57377. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57378. */
  57379. var PlayAnimationAction = /** @class */ (function (_super) {
  57380. __extends(PlayAnimationAction, _super);
  57381. /**
  57382. * Instantiate the action
  57383. * @param triggerOptions defines the trigger options
  57384. * @param target defines the target animation or animation name
  57385. * @param from defines from where the animation should start (animation frame)
  57386. * @param end defines where the animation should stop (animation frame)
  57387. * @param loop defines if the animation should loop or stop after the first play
  57388. * @param condition defines the trigger related conditions
  57389. */
  57390. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  57391. var _this = _super.call(this, triggerOptions, condition) || this;
  57392. _this.from = from;
  57393. _this.to = to;
  57394. _this.loop = loop;
  57395. _this._target = target;
  57396. return _this;
  57397. }
  57398. /** @hidden */
  57399. PlayAnimationAction.prototype._prepare = function () {
  57400. };
  57401. /**
  57402. * Execute the action and play the animation.
  57403. */
  57404. PlayAnimationAction.prototype.execute = function () {
  57405. var scene = this._actionManager.getScene();
  57406. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  57407. };
  57408. /**
  57409. * Serializes the actions and its related information.
  57410. * @param parent defines the object to serialize in
  57411. * @returns the serialized object
  57412. */
  57413. PlayAnimationAction.prototype.serialize = function (parent) {
  57414. return _super.prototype._serialize.call(this, {
  57415. name: "PlayAnimationAction",
  57416. properties: [
  57417. BABYLON.Action._GetTargetProperty(this._target),
  57418. { name: "from", value: String(this.from) },
  57419. { name: "to", value: String(this.to) },
  57420. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  57421. ]
  57422. }, parent);
  57423. };
  57424. return PlayAnimationAction;
  57425. }(BABYLON.Action));
  57426. BABYLON.PlayAnimationAction = PlayAnimationAction;
  57427. /**
  57428. * This defines an action responsible to stop an animation once triggered.
  57429. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57430. */
  57431. var StopAnimationAction = /** @class */ (function (_super) {
  57432. __extends(StopAnimationAction, _super);
  57433. /**
  57434. * Instantiate the action
  57435. * @param triggerOptions defines the trigger options
  57436. * @param target defines the target animation or animation name
  57437. * @param condition defines the trigger related conditions
  57438. */
  57439. function StopAnimationAction(triggerOptions, target, condition) {
  57440. var _this = _super.call(this, triggerOptions, condition) || this;
  57441. _this._target = target;
  57442. return _this;
  57443. }
  57444. /** @hidden */
  57445. StopAnimationAction.prototype._prepare = function () {
  57446. };
  57447. /**
  57448. * Execute the action and stop the animation.
  57449. */
  57450. StopAnimationAction.prototype.execute = function () {
  57451. var scene = this._actionManager.getScene();
  57452. scene.stopAnimation(this._target);
  57453. };
  57454. /**
  57455. * Serializes the actions and its related information.
  57456. * @param parent defines the object to serialize in
  57457. * @returns the serialized object
  57458. */
  57459. StopAnimationAction.prototype.serialize = function (parent) {
  57460. return _super.prototype._serialize.call(this, {
  57461. name: "StopAnimationAction",
  57462. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  57463. }, parent);
  57464. };
  57465. return StopAnimationAction;
  57466. }(BABYLON.Action));
  57467. BABYLON.StopAnimationAction = StopAnimationAction;
  57468. /**
  57469. * This defines an action responsible that does nothing once triggered.
  57470. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57471. */
  57472. var DoNothingAction = /** @class */ (function (_super) {
  57473. __extends(DoNothingAction, _super);
  57474. /**
  57475. * Instantiate the action
  57476. * @param triggerOptions defines the trigger options
  57477. * @param condition defines the trigger related conditions
  57478. */
  57479. function DoNothingAction(triggerOptions, condition) {
  57480. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  57481. return _super.call(this, triggerOptions, condition) || this;
  57482. }
  57483. /**
  57484. * Execute the action and do nothing.
  57485. */
  57486. DoNothingAction.prototype.execute = function () {
  57487. };
  57488. /**
  57489. * Serializes the actions and its related information.
  57490. * @param parent defines the object to serialize in
  57491. * @returns the serialized object
  57492. */
  57493. DoNothingAction.prototype.serialize = function (parent) {
  57494. return _super.prototype._serialize.call(this, {
  57495. name: "DoNothingAction",
  57496. properties: []
  57497. }, parent);
  57498. };
  57499. return DoNothingAction;
  57500. }(BABYLON.Action));
  57501. BABYLON.DoNothingAction = DoNothingAction;
  57502. /**
  57503. * This defines an action responsible to trigger several actions once triggered.
  57504. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57505. */
  57506. var CombineAction = /** @class */ (function (_super) {
  57507. __extends(CombineAction, _super);
  57508. /**
  57509. * Instantiate the action
  57510. * @param triggerOptions defines the trigger options
  57511. * @param children defines the list of aggregated animations to run
  57512. * @param condition defines the trigger related conditions
  57513. */
  57514. function CombineAction(triggerOptions, children, condition) {
  57515. var _this = _super.call(this, triggerOptions, condition) || this;
  57516. _this.children = children;
  57517. return _this;
  57518. }
  57519. /** @hidden */
  57520. CombineAction.prototype._prepare = function () {
  57521. for (var index = 0; index < this.children.length; index++) {
  57522. this.children[index]._actionManager = this._actionManager;
  57523. this.children[index]._prepare();
  57524. }
  57525. };
  57526. /**
  57527. * Execute the action and executes all the aggregated actions.
  57528. */
  57529. CombineAction.prototype.execute = function (evt) {
  57530. for (var index = 0; index < this.children.length; index++) {
  57531. this.children[index].execute(evt);
  57532. }
  57533. };
  57534. /**
  57535. * Serializes the actions and its related information.
  57536. * @param parent defines the object to serialize in
  57537. * @returns the serialized object
  57538. */
  57539. CombineAction.prototype.serialize = function (parent) {
  57540. var serializationObject = _super.prototype._serialize.call(this, {
  57541. name: "CombineAction",
  57542. properties: [],
  57543. combine: []
  57544. }, parent);
  57545. for (var i = 0; i < this.children.length; i++) {
  57546. serializationObject.combine.push(this.children[i].serialize(null));
  57547. }
  57548. return serializationObject;
  57549. };
  57550. return CombineAction;
  57551. }(BABYLON.Action));
  57552. BABYLON.CombineAction = CombineAction;
  57553. /**
  57554. * This defines an action responsible to run code (external event) once triggered.
  57555. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57556. */
  57557. var ExecuteCodeAction = /** @class */ (function (_super) {
  57558. __extends(ExecuteCodeAction, _super);
  57559. /**
  57560. * Instantiate the action
  57561. * @param triggerOptions defines the trigger options
  57562. * @param func defines the callback function to run
  57563. * @param condition defines the trigger related conditions
  57564. */
  57565. function ExecuteCodeAction(triggerOptions, func, condition) {
  57566. var _this = _super.call(this, triggerOptions, condition) || this;
  57567. _this.func = func;
  57568. return _this;
  57569. }
  57570. /**
  57571. * Execute the action and run the attached code.
  57572. */
  57573. ExecuteCodeAction.prototype.execute = function (evt) {
  57574. this.func(evt);
  57575. };
  57576. return ExecuteCodeAction;
  57577. }(BABYLON.Action));
  57578. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  57579. /**
  57580. * This defines an action responsible to set the parent property of the target once triggered.
  57581. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57582. */
  57583. var SetParentAction = /** @class */ (function (_super) {
  57584. __extends(SetParentAction, _super);
  57585. /**
  57586. * Instantiate the action
  57587. * @param triggerOptions defines the trigger options
  57588. * @param target defines the target containing the parent property
  57589. * @param parent defines from where the animation should start (animation frame)
  57590. * @param condition defines the trigger related conditions
  57591. */
  57592. function SetParentAction(triggerOptions, target, parent, condition) {
  57593. var _this = _super.call(this, triggerOptions, condition) || this;
  57594. _this._target = target;
  57595. _this._parent = parent;
  57596. return _this;
  57597. }
  57598. /** @hidden */
  57599. SetParentAction.prototype._prepare = function () {
  57600. };
  57601. /**
  57602. * Execute the action and set the parent property.
  57603. */
  57604. SetParentAction.prototype.execute = function () {
  57605. if (this._target.parent === this._parent) {
  57606. return;
  57607. }
  57608. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  57609. invertParentWorldMatrix.invert();
  57610. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  57611. this._target.parent = this._parent;
  57612. };
  57613. /**
  57614. * Serializes the actions and its related information.
  57615. * @param parent defines the object to serialize in
  57616. * @returns the serialized object
  57617. */
  57618. SetParentAction.prototype.serialize = function (parent) {
  57619. return _super.prototype._serialize.call(this, {
  57620. name: "SetParentAction",
  57621. properties: [
  57622. BABYLON.Action._GetTargetProperty(this._target),
  57623. BABYLON.Action._GetTargetProperty(this._parent),
  57624. ]
  57625. }, parent);
  57626. };
  57627. return SetParentAction;
  57628. }(BABYLON.Action));
  57629. BABYLON.SetParentAction = SetParentAction;
  57630. })(BABYLON || (BABYLON = {}));
  57631. //# sourceMappingURL=babylon.directActions.js.map
  57632. var BABYLON;
  57633. (function (BABYLON) {
  57634. /**
  57635. * Class used to manage multiple sprites on the same spritesheet
  57636. * @see http://doc.babylonjs.com/babylon101/sprites
  57637. */
  57638. var SpriteManager = /** @class */ (function () {
  57639. /**
  57640. * Creates a new sprite manager
  57641. * @param name defines the manager's name
  57642. * @param imgUrl defines the sprite sheet url
  57643. * @param capacity defines the maximum allowed number of sprites
  57644. * @param cellSize defines the size of a sprite cell
  57645. * @param scene defines the hosting scene
  57646. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  57647. * @param samplingMode defines the smapling mode to use with spritesheet
  57648. */
  57649. function SpriteManager(
  57650. /** defines the manager's name */
  57651. name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  57652. if (epsilon === void 0) { epsilon = 0.01; }
  57653. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57654. this.name = name;
  57655. /** Gets the list of sprites */
  57656. this.sprites = new Array();
  57657. /** Gets or sets the rendering group id (0 by default) */
  57658. this.renderingGroupId = 0;
  57659. /** Gets or sets camera layer mask */
  57660. this.layerMask = 0x0FFFFFFF;
  57661. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  57662. this.fogEnabled = true;
  57663. /** Gets or sets a boolean indicating if the sprites are pickable */
  57664. this.isPickable = false;
  57665. /**
  57666. * An event triggered when the manager is disposed.
  57667. */
  57668. this.onDisposeObservable = new BABYLON.Observable();
  57669. this._vertexBuffers = {};
  57670. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  57671. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  57672. }
  57673. this._capacity = capacity;
  57674. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  57675. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57676. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57677. if (cellSize.width && cellSize.height) {
  57678. this.cellWidth = cellSize.width;
  57679. this.cellHeight = cellSize.height;
  57680. }
  57681. else if (cellSize !== undefined) {
  57682. this.cellWidth = cellSize;
  57683. this.cellHeight = cellSize;
  57684. }
  57685. else {
  57686. return;
  57687. }
  57688. this._epsilon = epsilon;
  57689. this._scene = scene;
  57690. this._scene.spriteManagers.push(this);
  57691. var indices = [];
  57692. var index = 0;
  57693. for (var count = 0; count < capacity; count++) {
  57694. indices.push(index);
  57695. indices.push(index + 1);
  57696. indices.push(index + 2);
  57697. indices.push(index);
  57698. indices.push(index + 2);
  57699. indices.push(index + 3);
  57700. index += 4;
  57701. }
  57702. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  57703. // VBO
  57704. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  57705. this._vertexData = new Float32Array(capacity * 16 * 4);
  57706. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  57707. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  57708. var options = this._buffer.createVertexBuffer("options", 4, 4);
  57709. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  57710. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  57711. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  57712. this._vertexBuffers["options"] = options;
  57713. this._vertexBuffers["cellInfo"] = cellInfo;
  57714. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  57715. // Effects
  57716. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  57717. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  57718. }
  57719. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  57720. /**
  57721. * Callback called when the manager is disposed
  57722. */
  57723. set: function (callback) {
  57724. if (this._onDisposeObserver) {
  57725. this.onDisposeObservable.remove(this._onDisposeObserver);
  57726. }
  57727. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57728. },
  57729. enumerable: true,
  57730. configurable: true
  57731. });
  57732. Object.defineProperty(SpriteManager.prototype, "texture", {
  57733. /**
  57734. * Gets or sets the spritesheet texture
  57735. */
  57736. get: function () {
  57737. return this._spriteTexture;
  57738. },
  57739. set: function (value) {
  57740. this._spriteTexture = value;
  57741. },
  57742. enumerable: true,
  57743. configurable: true
  57744. });
  57745. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  57746. var arrayOffset = index * 16;
  57747. if (offsetX === 0) {
  57748. offsetX = this._epsilon;
  57749. }
  57750. else if (offsetX === 1) {
  57751. offsetX = 1 - this._epsilon;
  57752. }
  57753. if (offsetY === 0) {
  57754. offsetY = this._epsilon;
  57755. }
  57756. else if (offsetY === 1) {
  57757. offsetY = 1 - this._epsilon;
  57758. }
  57759. this._vertexData[arrayOffset] = sprite.position.x;
  57760. this._vertexData[arrayOffset + 1] = sprite.position.y;
  57761. this._vertexData[arrayOffset + 2] = sprite.position.z;
  57762. this._vertexData[arrayOffset + 3] = sprite.angle;
  57763. this._vertexData[arrayOffset + 4] = sprite.width;
  57764. this._vertexData[arrayOffset + 5] = sprite.height;
  57765. this._vertexData[arrayOffset + 6] = offsetX;
  57766. this._vertexData[arrayOffset + 7] = offsetY;
  57767. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  57768. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  57769. var offset = (sprite.cellIndex / rowSize) >> 0;
  57770. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  57771. this._vertexData[arrayOffset + 11] = offset;
  57772. // Color
  57773. this._vertexData[arrayOffset + 12] = sprite.color.r;
  57774. this._vertexData[arrayOffset + 13] = sprite.color.g;
  57775. this._vertexData[arrayOffset + 14] = sprite.color.b;
  57776. this._vertexData[arrayOffset + 15] = sprite.color.a;
  57777. };
  57778. /**
  57779. * Intersects the sprites with a ray
  57780. * @param ray defines the ray to intersect with
  57781. * @param camera defines the current active camera
  57782. * @param predicate defines a predicate used to select candidate sprites
  57783. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  57784. * @returns null if no hit or a PickingInfo
  57785. */
  57786. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  57787. var count = Math.min(this._capacity, this.sprites.length);
  57788. var min = BABYLON.Vector3.Zero();
  57789. var max = BABYLON.Vector3.Zero();
  57790. var distance = Number.MAX_VALUE;
  57791. var currentSprite = null;
  57792. var cameraSpacePosition = BABYLON.Vector3.Zero();
  57793. var cameraView = camera.getViewMatrix();
  57794. for (var index = 0; index < count; index++) {
  57795. var sprite = this.sprites[index];
  57796. if (!sprite) {
  57797. continue;
  57798. }
  57799. if (predicate) {
  57800. if (!predicate(sprite)) {
  57801. continue;
  57802. }
  57803. }
  57804. else if (!sprite.isPickable) {
  57805. continue;
  57806. }
  57807. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  57808. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  57809. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  57810. if (ray.intersectsBoxMinMax(min, max)) {
  57811. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  57812. if (distance > currentDistance) {
  57813. distance = currentDistance;
  57814. currentSprite = sprite;
  57815. if (fastCheck) {
  57816. break;
  57817. }
  57818. }
  57819. }
  57820. }
  57821. if (currentSprite) {
  57822. var result = new BABYLON.PickingInfo();
  57823. result.hit = true;
  57824. result.pickedSprite = currentSprite;
  57825. result.distance = distance;
  57826. return result;
  57827. }
  57828. return null;
  57829. };
  57830. /**
  57831. * Render all child sprites
  57832. */
  57833. SpriteManager.prototype.render = function () {
  57834. // Check
  57835. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady()) {
  57836. return;
  57837. }
  57838. var engine = this._scene.getEngine();
  57839. var baseSize = this._spriteTexture.getBaseSize();
  57840. // Sprites
  57841. var deltaTime = engine.getDeltaTime();
  57842. var max = Math.min(this._capacity, this.sprites.length);
  57843. var rowSize = baseSize.width / this.cellWidth;
  57844. var offset = 0;
  57845. for (var index = 0; index < max; index++) {
  57846. var sprite = this.sprites[index];
  57847. if (!sprite || !sprite.isVisible) {
  57848. continue;
  57849. }
  57850. sprite._animate(deltaTime);
  57851. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  57852. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  57853. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  57854. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  57855. }
  57856. this._buffer.update(this._vertexData);
  57857. // Render
  57858. var effect = this._effectBase;
  57859. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  57860. effect = this._effectFog;
  57861. }
  57862. engine.enableEffect(effect);
  57863. var viewMatrix = this._scene.getViewMatrix();
  57864. effect.setTexture("diffuseSampler", this._spriteTexture);
  57865. effect.setMatrix("view", viewMatrix);
  57866. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57867. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  57868. // Fog
  57869. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  57870. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  57871. effect.setColor3("vFogColor", this._scene.fogColor);
  57872. }
  57873. // VBOs
  57874. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57875. // Draw order
  57876. engine.setDepthFunctionToLessOrEqual();
  57877. effect.setBool("alphaTest", true);
  57878. engine.setColorWrite(false);
  57879. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  57880. engine.setColorWrite(true);
  57881. effect.setBool("alphaTest", false);
  57882. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57883. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  57884. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57885. };
  57886. /**
  57887. * Release associated resources
  57888. */
  57889. SpriteManager.prototype.dispose = function () {
  57890. if (this._buffer) {
  57891. this._buffer.dispose();
  57892. this._buffer = null;
  57893. }
  57894. if (this._indexBuffer) {
  57895. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57896. this._indexBuffer = null;
  57897. }
  57898. if (this._spriteTexture) {
  57899. this._spriteTexture.dispose();
  57900. this._spriteTexture = null;
  57901. }
  57902. // Remove from scene
  57903. var index = this._scene.spriteManagers.indexOf(this);
  57904. this._scene.spriteManagers.splice(index, 1);
  57905. // Callback
  57906. this.onDisposeObservable.notifyObservers(this);
  57907. this.onDisposeObservable.clear();
  57908. };
  57909. return SpriteManager;
  57910. }());
  57911. BABYLON.SpriteManager = SpriteManager;
  57912. })(BABYLON || (BABYLON = {}));
  57913. //# sourceMappingURL=babylon.spriteManager.js.map
  57914. var BABYLON;
  57915. (function (BABYLON) {
  57916. /**
  57917. * Class used to represent a sprite
  57918. * @see http://doc.babylonjs.com/babylon101/sprites
  57919. */
  57920. var Sprite = /** @class */ (function () {
  57921. /**
  57922. * Creates a new Sprite
  57923. * @param name defines the name
  57924. * @param manager defines the manager
  57925. */
  57926. function Sprite(
  57927. /** defines the name */
  57928. name, manager) {
  57929. this.name = name;
  57930. /** Gets or sets the main color */
  57931. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57932. /** Gets or sets the width */
  57933. this.width = 1.0;
  57934. /** Gets or sets the height */
  57935. this.height = 1.0;
  57936. /** Gets or sets rotation angle */
  57937. this.angle = 0;
  57938. /** Gets or sets the cell index in the sprite sheet */
  57939. this.cellIndex = 0;
  57940. /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
  57941. this.invertU = 0;
  57942. /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
  57943. this.invertV = 0;
  57944. /** Gets the list of attached animations */
  57945. this.animations = new Array();
  57946. /** Gets or sets a boolean indicating if the sprite can be picked */
  57947. this.isPickable = false;
  57948. this._animationStarted = false;
  57949. this._loopAnimation = false;
  57950. this._fromIndex = 0;
  57951. this._toIndex = 0;
  57952. this._delay = 0;
  57953. this._direction = 1;
  57954. this._time = 0;
  57955. /**
  57956. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  57957. */
  57958. this.isVisible = true;
  57959. this._manager = manager;
  57960. this._manager.sprites.push(this);
  57961. this.position = BABYLON.Vector3.Zero();
  57962. }
  57963. Object.defineProperty(Sprite.prototype, "size", {
  57964. /**
  57965. * Gets or sets the sprite size
  57966. */
  57967. get: function () {
  57968. return this.width;
  57969. },
  57970. set: function (value) {
  57971. this.width = value;
  57972. this.height = value;
  57973. },
  57974. enumerable: true,
  57975. configurable: true
  57976. });
  57977. /**
  57978. * Starts an animation
  57979. * @param from defines the initial key
  57980. * @param to defines the end key
  57981. * @param loop defines if the animation must loop
  57982. * @param delay defines the start delay (in ms)
  57983. * @param onAnimationEnd defines a callback to call when animation ends
  57984. */
  57985. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  57986. this._fromIndex = from;
  57987. this._toIndex = to;
  57988. this._loopAnimation = loop;
  57989. this._delay = delay;
  57990. this._animationStarted = true;
  57991. this._direction = from < to ? 1 : -1;
  57992. this.cellIndex = from;
  57993. this._time = 0;
  57994. this._onAnimationEnd = onAnimationEnd;
  57995. };
  57996. /** Stops current animation (if any) */
  57997. Sprite.prototype.stopAnimation = function () {
  57998. this._animationStarted = false;
  57999. };
  58000. /** @hidden */
  58001. Sprite.prototype._animate = function (deltaTime) {
  58002. if (!this._animationStarted) {
  58003. return;
  58004. }
  58005. this._time += deltaTime;
  58006. if (this._time > this._delay) {
  58007. this._time = this._time % this._delay;
  58008. this.cellIndex += this._direction;
  58009. if (this.cellIndex > this._toIndex) {
  58010. if (this._loopAnimation) {
  58011. this.cellIndex = this._fromIndex;
  58012. }
  58013. else {
  58014. this.cellIndex = this._toIndex;
  58015. this._animationStarted = false;
  58016. if (this._onAnimationEnd) {
  58017. this._onAnimationEnd();
  58018. }
  58019. if (this.disposeWhenFinishedAnimating) {
  58020. this.dispose();
  58021. }
  58022. }
  58023. }
  58024. }
  58025. };
  58026. /** Release associated resources */
  58027. Sprite.prototype.dispose = function () {
  58028. for (var i = 0; i < this._manager.sprites.length; i++) {
  58029. if (this._manager.sprites[i] == this) {
  58030. this._manager.sprites.splice(i, 1);
  58031. }
  58032. }
  58033. };
  58034. return Sprite;
  58035. }());
  58036. BABYLON.Sprite = Sprite;
  58037. })(BABYLON || (BABYLON = {}));
  58038. //# sourceMappingURL=babylon.sprite.js.map
  58039. var BABYLON;
  58040. (function (BABYLON) {
  58041. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  58042. if (!BABYLON.PickingInfo) {
  58043. return null;
  58044. }
  58045. var pickingInfo = null;
  58046. if (!camera) {
  58047. if (!this.activeCamera) {
  58048. return null;
  58049. }
  58050. camera = this.activeCamera;
  58051. }
  58052. if (this.spriteManagers.length > 0) {
  58053. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  58054. var spriteManager = this.spriteManagers[spriteIndex];
  58055. if (!spriteManager.isPickable) {
  58056. continue;
  58057. }
  58058. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  58059. if (!result || !result.hit) {
  58060. continue;
  58061. }
  58062. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  58063. continue;
  58064. }
  58065. pickingInfo = result;
  58066. if (fastCheck) {
  58067. break;
  58068. }
  58069. }
  58070. }
  58071. return pickingInfo || new BABYLON.PickingInfo();
  58072. };
  58073. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  58074. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  58075. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  58076. };
  58077. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  58078. if (!this._tempSpritePickingRay) {
  58079. return null;
  58080. }
  58081. if (!camera) {
  58082. if (!this.activeCamera) {
  58083. return null;
  58084. }
  58085. camera = this.activeCamera;
  58086. }
  58087. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  58088. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  58089. };
  58090. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  58091. if (this._pointerOverSprite === sprite) {
  58092. return;
  58093. }
  58094. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  58095. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  58096. }
  58097. this._pointerOverSprite = sprite;
  58098. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  58099. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  58100. }
  58101. };
  58102. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  58103. return this._pointerOverSprite;
  58104. };
  58105. /**
  58106. * Defines the sprite scene component responsible to manage sprites
  58107. * in a given scene.
  58108. */
  58109. var SpriteSceneComponent = /** @class */ (function () {
  58110. /**
  58111. * Creates a new instance of the component for the given scene
  58112. * @param scene Defines the scene to register the component in
  58113. */
  58114. function SpriteSceneComponent(scene) {
  58115. /**
  58116. * The component name helpfull to identify the component in the list of scene components.
  58117. */
  58118. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  58119. this.scene = scene;
  58120. this.scene.spriteManagers = new Array();
  58121. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  58122. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  58123. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  58124. this._spritePredicate = function (sprite) {
  58125. if (!sprite.actionManager) {
  58126. return false;
  58127. }
  58128. return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
  58129. };
  58130. }
  58131. /**
  58132. * Registers the component in a given scene
  58133. */
  58134. SpriteSceneComponent.prototype.register = function () {
  58135. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  58136. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  58137. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  58138. };
  58139. /**
  58140. * Rebuilds the elements related to this component in case of
  58141. * context lost for instance.
  58142. */
  58143. SpriteSceneComponent.prototype.rebuild = function () {
  58144. /** Nothing to do for sprites */
  58145. };
  58146. /**
  58147. * Disposes the component and the associated ressources.
  58148. */
  58149. SpriteSceneComponent.prototype.dispose = function () {
  58150. this.scene.onBeforeSpritesRenderingObservable.clear();
  58151. this.scene.onAfterSpritesRenderingObservable.clear();
  58152. var spriteManagers = this.scene.spriteManagers;
  58153. while (spriteManagers.length) {
  58154. spriteManagers[0].dispose();
  58155. }
  58156. };
  58157. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  58158. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  58159. if (result) {
  58160. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  58161. }
  58162. return result;
  58163. };
  58164. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  58165. var scene = this.scene;
  58166. if (isMeshPicked) {
  58167. scene.setPointerOverSprite(null);
  58168. }
  58169. else {
  58170. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  58171. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  58172. scene.setPointerOverSprite(pickResult.pickedSprite);
  58173. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  58174. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  58175. }
  58176. else {
  58177. canvas.style.cursor = scene.hoverCursor;
  58178. }
  58179. }
  58180. else {
  58181. scene.setPointerOverSprite(null);
  58182. }
  58183. }
  58184. return pickResult;
  58185. };
  58186. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  58187. var scene = this.scene;
  58188. scene._pickedDownSprite = null;
  58189. if (scene.spriteManagers.length > 0) {
  58190. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  58191. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  58192. if (pickResult.pickedSprite.actionManager) {
  58193. scene._pickedDownSprite = pickResult.pickedSprite;
  58194. switch (evt.button) {
  58195. case 0:
  58196. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58197. break;
  58198. case 1:
  58199. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58200. break;
  58201. case 2:
  58202. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58203. break;
  58204. }
  58205. if (pickResult.pickedSprite.actionManager) {
  58206. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58207. }
  58208. }
  58209. }
  58210. }
  58211. return pickResult;
  58212. };
  58213. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  58214. var scene = this.scene;
  58215. if (scene.spriteManagers.length > 0) {
  58216. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  58217. if (spritePickResult) {
  58218. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  58219. if (spritePickResult.pickedSprite.actionManager) {
  58220. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  58221. if (spritePickResult.pickedSprite.actionManager) {
  58222. if (!this.scene._isPointerSwiping()) {
  58223. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  58224. }
  58225. }
  58226. }
  58227. }
  58228. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  58229. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  58230. }
  58231. }
  58232. }
  58233. return pickResult;
  58234. };
  58235. return SpriteSceneComponent;
  58236. }());
  58237. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  58238. })(BABYLON || (BABYLON = {}));
  58239. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  58240. var BABYLON;
  58241. (function (BABYLON) {
  58242. /**
  58243. * @hidden
  58244. */
  58245. var IntersectionInfo = /** @class */ (function () {
  58246. function IntersectionInfo(bu, bv, distance) {
  58247. this.bu = bu;
  58248. this.bv = bv;
  58249. this.distance = distance;
  58250. this.faceId = 0;
  58251. this.subMeshId = 0;
  58252. }
  58253. return IntersectionInfo;
  58254. }());
  58255. BABYLON.IntersectionInfo = IntersectionInfo;
  58256. /**
  58257. * Information about the result of picking within a scene
  58258. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  58259. */
  58260. var PickingInfo = /** @class */ (function () {
  58261. function PickingInfo() {
  58262. /**
  58263. * If the pick collided with an object
  58264. */
  58265. this.hit = false;
  58266. /**
  58267. * Distance away where the pick collided
  58268. */
  58269. this.distance = 0;
  58270. /**
  58271. * The location of pick collision
  58272. */
  58273. this.pickedPoint = null;
  58274. /**
  58275. * The mesh corresponding the the pick collision
  58276. */
  58277. this.pickedMesh = null;
  58278. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  58279. this.bu = 0;
  58280. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  58281. this.bv = 0;
  58282. /** The id of the face on the mesh that was picked */
  58283. this.faceId = -1;
  58284. /** Id of the the submesh that was picked */
  58285. this.subMeshId = 0;
  58286. /** If a sprite was picked, this will be the sprite the pick collided with */
  58287. this.pickedSprite = null;
  58288. /**
  58289. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  58290. */
  58291. this.originMesh = null;
  58292. /**
  58293. * The ray that was used to perform the picking.
  58294. */
  58295. this.ray = null;
  58296. }
  58297. /**
  58298. * Gets the normal correspodning to the face the pick collided with
  58299. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  58300. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  58301. * @returns The normal correspodning to the face the pick collided with
  58302. */
  58303. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  58304. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  58305. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  58306. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  58307. return null;
  58308. }
  58309. var indices = this.pickedMesh.getIndices();
  58310. if (!indices) {
  58311. return null;
  58312. }
  58313. var result;
  58314. if (useVerticesNormals) {
  58315. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58316. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  58317. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  58318. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  58319. normal0 = normal0.scale(this.bu);
  58320. normal1 = normal1.scale(this.bv);
  58321. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  58322. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  58323. }
  58324. else {
  58325. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58326. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  58327. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  58328. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  58329. var p1p2 = vertex1.subtract(vertex2);
  58330. var p3p2 = vertex3.subtract(vertex2);
  58331. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  58332. }
  58333. if (useWorldCoordinates) {
  58334. var wm = this.pickedMesh.getWorldMatrix();
  58335. if (this.pickedMesh.nonUniformScaling) {
  58336. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  58337. wm = BABYLON.Tmp.Matrix[0];
  58338. wm.setTranslationFromFloats(0, 0, 0);
  58339. wm.invert();
  58340. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  58341. wm = BABYLON.Tmp.Matrix[1];
  58342. }
  58343. result = BABYLON.Vector3.TransformNormal(result, wm);
  58344. }
  58345. result.normalize();
  58346. return result;
  58347. };
  58348. /**
  58349. * Gets the texture coordinates of where the pick occured
  58350. * @returns the vector containing the coordnates of the texture
  58351. */
  58352. PickingInfo.prototype.getTextureCoordinates = function () {
  58353. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58354. return null;
  58355. }
  58356. var indices = this.pickedMesh.getIndices();
  58357. if (!indices) {
  58358. return null;
  58359. }
  58360. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58361. if (!uvs) {
  58362. return null;
  58363. }
  58364. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  58365. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  58366. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  58367. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  58368. uv1 = uv1.scale(this.bu);
  58369. uv2 = uv2.scale(this.bv);
  58370. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  58371. };
  58372. return PickingInfo;
  58373. }());
  58374. BABYLON.PickingInfo = PickingInfo;
  58375. })(BABYLON || (BABYLON = {}));
  58376. //# sourceMappingURL=babylon.pickingInfo.js.map
  58377. var BABYLON;
  58378. (function (BABYLON) {
  58379. /**
  58380. * Class representing a ray with position and direction
  58381. */
  58382. var Ray = /** @class */ (function () {
  58383. /**
  58384. * Creates a new ray
  58385. * @param origin origin point
  58386. * @param direction direction
  58387. * @param length length of the ray
  58388. */
  58389. function Ray(
  58390. /** origin point */
  58391. origin,
  58392. /** direction */
  58393. direction,
  58394. /** length of the ray */
  58395. length) {
  58396. if (length === void 0) { length = Number.MAX_VALUE; }
  58397. this.origin = origin;
  58398. this.direction = direction;
  58399. this.length = length;
  58400. }
  58401. // Methods
  58402. /**
  58403. * Checks if the ray intersects a box
  58404. * @param minimum bound of the box
  58405. * @param maximum bound of the box
  58406. * @param intersectionTreshold extra extend to be added to the box in all direction
  58407. * @returns if the box was hit
  58408. */
  58409. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum, intersectionTreshold) {
  58410. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  58411. var newMinimum = Ray._min.copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold);
  58412. var newMaximum = Ray._max.copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold);
  58413. var d = 0.0;
  58414. var maxValue = Number.MAX_VALUE;
  58415. var inv;
  58416. var min;
  58417. var max;
  58418. var temp;
  58419. if (Math.abs(this.direction.x) < 0.0000001) {
  58420. if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) {
  58421. return false;
  58422. }
  58423. }
  58424. else {
  58425. inv = 1.0 / this.direction.x;
  58426. min = (newMinimum.x - this.origin.x) * inv;
  58427. max = (newMaximum.x - this.origin.x) * inv;
  58428. if (max === -Infinity) {
  58429. max = Infinity;
  58430. }
  58431. if (min > max) {
  58432. temp = min;
  58433. min = max;
  58434. max = temp;
  58435. }
  58436. d = Math.max(min, d);
  58437. maxValue = Math.min(max, maxValue);
  58438. if (d > maxValue) {
  58439. return false;
  58440. }
  58441. }
  58442. if (Math.abs(this.direction.y) < 0.0000001) {
  58443. if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) {
  58444. return false;
  58445. }
  58446. }
  58447. else {
  58448. inv = 1.0 / this.direction.y;
  58449. min = (newMinimum.y - this.origin.y) * inv;
  58450. max = (newMaximum.y - this.origin.y) * inv;
  58451. if (max === -Infinity) {
  58452. max = Infinity;
  58453. }
  58454. if (min > max) {
  58455. temp = min;
  58456. min = max;
  58457. max = temp;
  58458. }
  58459. d = Math.max(min, d);
  58460. maxValue = Math.min(max, maxValue);
  58461. if (d > maxValue) {
  58462. return false;
  58463. }
  58464. }
  58465. if (Math.abs(this.direction.z) < 0.0000001) {
  58466. if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) {
  58467. return false;
  58468. }
  58469. }
  58470. else {
  58471. inv = 1.0 / this.direction.z;
  58472. min = (newMinimum.z - this.origin.z) * inv;
  58473. max = (newMaximum.z - this.origin.z) * inv;
  58474. if (max === -Infinity) {
  58475. max = Infinity;
  58476. }
  58477. if (min > max) {
  58478. temp = min;
  58479. min = max;
  58480. max = temp;
  58481. }
  58482. d = Math.max(min, d);
  58483. maxValue = Math.min(max, maxValue);
  58484. if (d > maxValue) {
  58485. return false;
  58486. }
  58487. }
  58488. return true;
  58489. };
  58490. /**
  58491. * Checks if the ray intersects a box
  58492. * @param box the bounding box to check
  58493. * @param intersectionTreshold extra extend to be added to the BoundingBox in all direction
  58494. * @returns if the box was hit
  58495. */
  58496. Ray.prototype.intersectsBox = function (box, intersectionTreshold) {
  58497. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  58498. return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold);
  58499. };
  58500. /**
  58501. * If the ray hits a sphere
  58502. * @param sphere the bounding sphere to check
  58503. * @param intersectionTreshold extra extend to be added to the BoundingSphere in all direction
  58504. * @returns true if it hits the sphere
  58505. */
  58506. Ray.prototype.intersectsSphere = function (sphere, intersectionTreshold) {
  58507. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  58508. var x = sphere.center.x - this.origin.x;
  58509. var y = sphere.center.y - this.origin.y;
  58510. var z = sphere.center.z - this.origin.z;
  58511. var pyth = (x * x) + (y * y) + (z * z);
  58512. var radius = sphere.radius + intersectionTreshold;
  58513. var rr = radius * radius;
  58514. if (pyth <= rr) {
  58515. return true;
  58516. }
  58517. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  58518. if (dot < 0.0) {
  58519. return false;
  58520. }
  58521. var temp = pyth - (dot * dot);
  58522. return temp <= rr;
  58523. };
  58524. /**
  58525. * If the ray hits a triange
  58526. * @param vertex0 triangle vertex
  58527. * @param vertex1 triangle vertex
  58528. * @param vertex2 triangle vertex
  58529. * @returns intersection information if hit
  58530. */
  58531. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  58532. vertex1.subtractToRef(vertex0, Ray._edge1);
  58533. vertex2.subtractToRef(vertex0, Ray._edge2);
  58534. BABYLON.Vector3.CrossToRef(this.direction, Ray._edge2, Ray._pvec);
  58535. var det = BABYLON.Vector3.Dot(Ray._edge1, Ray._pvec);
  58536. if (det === 0) {
  58537. return null;
  58538. }
  58539. var invdet = 1 / det;
  58540. this.origin.subtractToRef(vertex0, Ray._tvec);
  58541. var bu = BABYLON.Vector3.Dot(Ray._tvec, Ray._pvec) * invdet;
  58542. if (bu < 0 || bu > 1.0) {
  58543. return null;
  58544. }
  58545. BABYLON.Vector3.CrossToRef(Ray._tvec, Ray._edge1, Ray._qvec);
  58546. var bv = BABYLON.Vector3.Dot(this.direction, Ray._qvec) * invdet;
  58547. if (bv < 0 || bu + bv > 1.0) {
  58548. return null;
  58549. }
  58550. //check if the distance is longer than the predefined length.
  58551. var distance = BABYLON.Vector3.Dot(Ray._edge2, Ray._qvec) * invdet;
  58552. if (distance > this.length) {
  58553. return null;
  58554. }
  58555. return new BABYLON.IntersectionInfo(bu, bv, distance);
  58556. };
  58557. /**
  58558. * Checks if ray intersects a plane
  58559. * @param plane the plane to check
  58560. * @returns the distance away it was hit
  58561. */
  58562. Ray.prototype.intersectsPlane = function (plane) {
  58563. var distance;
  58564. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  58565. if (Math.abs(result1) < 9.99999997475243E-07) {
  58566. return null;
  58567. }
  58568. else {
  58569. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  58570. distance = (-plane.d - result2) / result1;
  58571. if (distance < 0.0) {
  58572. if (distance < -9.99999997475243E-07) {
  58573. return null;
  58574. }
  58575. else {
  58576. return 0;
  58577. }
  58578. }
  58579. return distance;
  58580. }
  58581. };
  58582. /**
  58583. * Checks if ray intersects a mesh
  58584. * @param mesh the mesh to check
  58585. * @param fastCheck if only the bounding box should checked
  58586. * @returns picking info of the intersecton
  58587. */
  58588. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  58589. var tm = BABYLON.Tmp.Matrix[0];
  58590. mesh.getWorldMatrix().invertToRef(tm);
  58591. if (this._tmpRay) {
  58592. Ray.TransformToRef(this, tm, this._tmpRay);
  58593. }
  58594. else {
  58595. this._tmpRay = Ray.Transform(this, tm);
  58596. }
  58597. return mesh.intersects(this._tmpRay, fastCheck);
  58598. };
  58599. /**
  58600. * Checks if ray intersects a mesh
  58601. * @param meshes the meshes to check
  58602. * @param fastCheck if only the bounding box should checked
  58603. * @param results array to store result in
  58604. * @returns Array of picking infos
  58605. */
  58606. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  58607. if (results) {
  58608. results.length = 0;
  58609. }
  58610. else {
  58611. results = [];
  58612. }
  58613. for (var i = 0; i < meshes.length; i++) {
  58614. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  58615. if (pickInfo.hit) {
  58616. results.push(pickInfo);
  58617. }
  58618. }
  58619. results.sort(this._comparePickingInfo);
  58620. return results;
  58621. };
  58622. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  58623. if (pickingInfoA.distance < pickingInfoB.distance) {
  58624. return -1;
  58625. }
  58626. else if (pickingInfoA.distance > pickingInfoB.distance) {
  58627. return 1;
  58628. }
  58629. else {
  58630. return 0;
  58631. }
  58632. };
  58633. /**
  58634. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  58635. * @param sega the first point of the segment to test the intersection against
  58636. * @param segb the second point of the segment to test the intersection against
  58637. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  58638. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  58639. */
  58640. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  58641. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  58642. var u = segb.subtract(sega);
  58643. var v = rsegb.subtract(this.origin);
  58644. var w = sega.subtract(this.origin);
  58645. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  58646. var b = BABYLON.Vector3.Dot(u, v);
  58647. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  58648. var d = BABYLON.Vector3.Dot(u, w);
  58649. var e = BABYLON.Vector3.Dot(v, w);
  58650. var D = a * c - b * b; // always >= 0
  58651. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  58652. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  58653. // compute the line parameters of the two closest points
  58654. if (D < Ray.smallnum) { // the lines are almost parallel
  58655. sN = 0.0; // force using point P0 on segment S1
  58656. sD = 1.0; // to prevent possible division by 0.0 later
  58657. tN = e;
  58658. tD = c;
  58659. }
  58660. else { // get the closest points on the infinite lines
  58661. sN = (b * e - c * d);
  58662. tN = (a * e - b * d);
  58663. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  58664. sN = 0.0;
  58665. tN = e;
  58666. tD = c;
  58667. }
  58668. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  58669. sN = sD;
  58670. tN = e + b;
  58671. tD = c;
  58672. }
  58673. }
  58674. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  58675. tN = 0.0;
  58676. // recompute sc for this edge
  58677. if (-d < 0.0) {
  58678. sN = 0.0;
  58679. }
  58680. else if (-d > a) {
  58681. sN = sD;
  58682. }
  58683. else {
  58684. sN = -d;
  58685. sD = a;
  58686. }
  58687. }
  58688. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  58689. tN = tD;
  58690. // recompute sc for this edge
  58691. if ((-d + b) < 0.0) {
  58692. sN = 0;
  58693. }
  58694. else if ((-d + b) > a) {
  58695. sN = sD;
  58696. }
  58697. else {
  58698. sN = (-d + b);
  58699. sD = a;
  58700. }
  58701. }
  58702. // finally do the division to get sc and tc
  58703. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  58704. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  58705. // get the difference of the two closest points
  58706. var qtc = v.multiplyByFloats(tc, tc, tc);
  58707. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  58708. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  58709. if (isIntersected) {
  58710. return qtc.length();
  58711. }
  58712. return -1;
  58713. };
  58714. /**
  58715. * Update the ray from viewport position
  58716. * @param x position
  58717. * @param y y position
  58718. * @param viewportWidth viewport width
  58719. * @param viewportHeight viewport height
  58720. * @param world world matrix
  58721. * @param view view matrix
  58722. * @param projection projection matrix
  58723. * @returns this ray updated
  58724. */
  58725. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  58726. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  58727. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  58728. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  58729. this.direction.normalize();
  58730. return this;
  58731. };
  58732. // Statics
  58733. /**
  58734. * Creates a ray with origin and direction of 0,0,0
  58735. * @returns the new ray
  58736. */
  58737. Ray.Zero = function () {
  58738. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  58739. };
  58740. /**
  58741. * Creates a new ray from screen space and viewport
  58742. * @param x position
  58743. * @param y y position
  58744. * @param viewportWidth viewport width
  58745. * @param viewportHeight viewport height
  58746. * @param world world matrix
  58747. * @param view view matrix
  58748. * @param projection projection matrix
  58749. * @returns new ray
  58750. */
  58751. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  58752. var result = Ray.Zero();
  58753. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  58754. };
  58755. /**
  58756. * 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
  58757. * transformed to the given world matrix.
  58758. * @param origin The origin point
  58759. * @param end The end point
  58760. * @param world a matrix to transform the ray to. Default is the identity matrix.
  58761. * @returns the new ray
  58762. */
  58763. Ray.CreateNewFromTo = function (origin, end, world) {
  58764. if (world === void 0) { world = BABYLON.Matrix.IdentityReadOnly; }
  58765. var direction = end.subtract(origin);
  58766. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  58767. direction.normalize();
  58768. return Ray.Transform(new Ray(origin, direction, length), world);
  58769. };
  58770. /**
  58771. * Transforms a ray by a matrix
  58772. * @param ray ray to transform
  58773. * @param matrix matrix to apply
  58774. * @returns the resulting new ray
  58775. */
  58776. Ray.Transform = function (ray, matrix) {
  58777. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  58778. Ray.TransformToRef(ray, matrix, result);
  58779. return result;
  58780. };
  58781. /**
  58782. * Transforms a ray by a matrix
  58783. * @param ray ray to transform
  58784. * @param matrix matrix to apply
  58785. * @param result ray to store result in
  58786. */
  58787. Ray.TransformToRef = function (ray, matrix, result) {
  58788. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  58789. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  58790. result.length = ray.length;
  58791. var dir = result.direction;
  58792. var len = dir.length();
  58793. if (!(len === 0 || len === 1)) {
  58794. var num = 1.0 / len;
  58795. dir.x *= num;
  58796. dir.y *= num;
  58797. dir.z *= num;
  58798. result.length *= len;
  58799. }
  58800. };
  58801. Ray._edge1 = BABYLON.Vector3.Zero();
  58802. Ray._edge2 = BABYLON.Vector3.Zero();
  58803. Ray._pvec = BABYLON.Vector3.Zero();
  58804. Ray._tvec = BABYLON.Vector3.Zero();
  58805. Ray._qvec = BABYLON.Vector3.Zero();
  58806. Ray._min = BABYLON.Vector3.Zero();
  58807. Ray._max = BABYLON.Vector3.Zero();
  58808. Ray.smallnum = 0.00000001;
  58809. Ray.rayl = 10e8;
  58810. return Ray;
  58811. }());
  58812. BABYLON.Ray = Ray;
  58813. })(BABYLON || (BABYLON = {}));
  58814. //# sourceMappingURL=babylon.ray.js.map
  58815. var BABYLON;
  58816. (function (BABYLON) {
  58817. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  58818. if (boxMin.x > sphereCenter.x + sphereRadius) {
  58819. return false;
  58820. }
  58821. if (sphereCenter.x - sphereRadius > boxMax.x) {
  58822. return false;
  58823. }
  58824. if (boxMin.y > sphereCenter.y + sphereRadius) {
  58825. return false;
  58826. }
  58827. if (sphereCenter.y - sphereRadius > boxMax.y) {
  58828. return false;
  58829. }
  58830. if (boxMin.z > sphereCenter.z + sphereRadius) {
  58831. return false;
  58832. }
  58833. if (sphereCenter.z - sphereRadius > boxMax.z) {
  58834. return false;
  58835. }
  58836. return true;
  58837. };
  58838. var getLowestRoot = (function () {
  58839. var result = { root: 0, found: false };
  58840. return function (a, b, c, maxR) {
  58841. result.root = 0;
  58842. result.found = false;
  58843. var determinant = b * b - 4.0 * a * c;
  58844. if (determinant < 0) {
  58845. return result;
  58846. }
  58847. var sqrtD = Math.sqrt(determinant);
  58848. var r1 = (-b - sqrtD) / (2.0 * a);
  58849. var r2 = (-b + sqrtD) / (2.0 * a);
  58850. if (r1 > r2) {
  58851. var temp = r2;
  58852. r2 = r1;
  58853. r1 = temp;
  58854. }
  58855. if (r1 > 0 && r1 < maxR) {
  58856. result.root = r1;
  58857. result.found = true;
  58858. return result;
  58859. }
  58860. if (r2 > 0 && r2 < maxR) {
  58861. result.root = r2;
  58862. result.found = true;
  58863. return result;
  58864. }
  58865. return result;
  58866. };
  58867. })();
  58868. /** @hidden */
  58869. var Collider = /** @class */ (function () {
  58870. function Collider() {
  58871. this._collisionPoint = BABYLON.Vector3.Zero();
  58872. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  58873. this._tempVector = BABYLON.Vector3.Zero();
  58874. this._tempVector2 = BABYLON.Vector3.Zero();
  58875. this._tempVector3 = BABYLON.Vector3.Zero();
  58876. this._tempVector4 = BABYLON.Vector3.Zero();
  58877. this._edge = BABYLON.Vector3.Zero();
  58878. this._baseToVertex = BABYLON.Vector3.Zero();
  58879. this._destinationPoint = BABYLON.Vector3.Zero();
  58880. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  58881. this._displacementVector = BABYLON.Vector3.Zero();
  58882. /** @hidden */
  58883. this._radius = BABYLON.Vector3.One();
  58884. /** @hidden */
  58885. this._retry = 0;
  58886. /** @hidden */
  58887. this._basePointWorld = BABYLON.Vector3.Zero();
  58888. this._velocityWorld = BABYLON.Vector3.Zero();
  58889. this._normalizedVelocity = BABYLON.Vector3.Zero();
  58890. this._collisionMask = -1;
  58891. }
  58892. Object.defineProperty(Collider.prototype, "collisionMask", {
  58893. get: function () {
  58894. return this._collisionMask;
  58895. },
  58896. set: function (mask) {
  58897. this._collisionMask = !isNaN(mask) ? mask : -1;
  58898. },
  58899. enumerable: true,
  58900. configurable: true
  58901. });
  58902. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  58903. /**
  58904. * Gets the plane normal used to compute the sliding response (in local space)
  58905. */
  58906. get: function () {
  58907. return this._slidePlaneNormal;
  58908. },
  58909. enumerable: true,
  58910. configurable: true
  58911. });
  58912. // Methods
  58913. /** @hidden */
  58914. Collider.prototype._initialize = function (source, dir, e) {
  58915. this._velocity = dir;
  58916. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  58917. this._basePoint = source;
  58918. source.multiplyToRef(this._radius, this._basePointWorld);
  58919. dir.multiplyToRef(this._radius, this._velocityWorld);
  58920. this._velocityWorldLength = this._velocityWorld.length();
  58921. this._epsilon = e;
  58922. this.collisionFound = false;
  58923. };
  58924. /** @hidden */
  58925. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  58926. pa.subtractToRef(point, this._tempVector);
  58927. pb.subtractToRef(point, this._tempVector2);
  58928. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  58929. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  58930. if (d < 0) {
  58931. return false;
  58932. }
  58933. pc.subtractToRef(point, this._tempVector3);
  58934. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  58935. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  58936. if (d < 0) {
  58937. return false;
  58938. }
  58939. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  58940. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  58941. return d >= 0;
  58942. };
  58943. /** @hidden */
  58944. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  58945. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  58946. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  58947. if (distance > this._velocityWorldLength + max + sphereRadius) {
  58948. return false;
  58949. }
  58950. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
  58951. return false;
  58952. }
  58953. return true;
  58954. };
  58955. /** @hidden */
  58956. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  58957. var t0;
  58958. var embeddedInPlane = false;
  58959. //defensive programming, actually not needed.
  58960. if (!trianglePlaneArray) {
  58961. trianglePlaneArray = [];
  58962. }
  58963. if (!trianglePlaneArray[faceIndex]) {
  58964. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  58965. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  58966. }
  58967. var trianglePlane = trianglePlaneArray[faceIndex];
  58968. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
  58969. return;
  58970. }
  58971. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  58972. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  58973. if (normalDotVelocity == 0) {
  58974. if (Math.abs(signedDistToTrianglePlane) >= 1.0) {
  58975. return;
  58976. }
  58977. embeddedInPlane = true;
  58978. t0 = 0;
  58979. }
  58980. else {
  58981. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  58982. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  58983. if (t0 > t1) {
  58984. var temp = t1;
  58985. t1 = t0;
  58986. t0 = temp;
  58987. }
  58988. if (t0 > 1.0 || t1 < 0.0) {
  58989. return;
  58990. }
  58991. if (t0 < 0) {
  58992. t0 = 0;
  58993. }
  58994. if (t0 > 1.0) {
  58995. t0 = 1.0;
  58996. }
  58997. }
  58998. this._collisionPoint.copyFromFloats(0, 0, 0);
  58999. var found = false;
  59000. var t = 1.0;
  59001. if (!embeddedInPlane) {
  59002. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  59003. this._velocity.scaleToRef(t0, this._tempVector);
  59004. this._planeIntersectionPoint.addInPlace(this._tempVector);
  59005. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  59006. found = true;
  59007. t = t0;
  59008. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  59009. }
  59010. }
  59011. if (!found) {
  59012. var velocitySquaredLength = this._velocity.lengthSquared();
  59013. var a = velocitySquaredLength;
  59014. this._basePoint.subtractToRef(p1, this._tempVector);
  59015. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59016. var c = this._tempVector.lengthSquared() - 1.0;
  59017. var lowestRoot = getLowestRoot(a, b, c, t);
  59018. if (lowestRoot.found) {
  59019. t = lowestRoot.root;
  59020. found = true;
  59021. this._collisionPoint.copyFrom(p1);
  59022. }
  59023. this._basePoint.subtractToRef(p2, this._tempVector);
  59024. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59025. c = this._tempVector.lengthSquared() - 1.0;
  59026. lowestRoot = getLowestRoot(a, b, c, t);
  59027. if (lowestRoot.found) {
  59028. t = lowestRoot.root;
  59029. found = true;
  59030. this._collisionPoint.copyFrom(p2);
  59031. }
  59032. this._basePoint.subtractToRef(p3, this._tempVector);
  59033. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59034. c = this._tempVector.lengthSquared() - 1.0;
  59035. lowestRoot = getLowestRoot(a, b, c, t);
  59036. if (lowestRoot.found) {
  59037. t = lowestRoot.root;
  59038. found = true;
  59039. this._collisionPoint.copyFrom(p3);
  59040. }
  59041. p2.subtractToRef(p1, this._edge);
  59042. p1.subtractToRef(this._basePoint, this._baseToVertex);
  59043. var edgeSquaredLength = this._edge.lengthSquared();
  59044. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59045. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59046. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59047. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59048. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59049. lowestRoot = getLowestRoot(a, b, c, t);
  59050. if (lowestRoot.found) {
  59051. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59052. if (f >= 0.0 && f <= 1.0) {
  59053. t = lowestRoot.root;
  59054. found = true;
  59055. this._edge.scaleInPlace(f);
  59056. p1.addToRef(this._edge, this._collisionPoint);
  59057. }
  59058. }
  59059. p3.subtractToRef(p2, this._edge);
  59060. p2.subtractToRef(this._basePoint, this._baseToVertex);
  59061. edgeSquaredLength = this._edge.lengthSquared();
  59062. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59063. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59064. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59065. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59066. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59067. lowestRoot = getLowestRoot(a, b, c, t);
  59068. if (lowestRoot.found) {
  59069. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59070. if (f >= 0.0 && f <= 1.0) {
  59071. t = lowestRoot.root;
  59072. found = true;
  59073. this._edge.scaleInPlace(f);
  59074. p2.addToRef(this._edge, this._collisionPoint);
  59075. }
  59076. }
  59077. p1.subtractToRef(p3, this._edge);
  59078. p3.subtractToRef(this._basePoint, this._baseToVertex);
  59079. edgeSquaredLength = this._edge.lengthSquared();
  59080. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59081. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59082. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59083. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59084. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59085. lowestRoot = getLowestRoot(a, b, c, t);
  59086. if (lowestRoot.found) {
  59087. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59088. if (f >= 0.0 && f <= 1.0) {
  59089. t = lowestRoot.root;
  59090. found = true;
  59091. this._edge.scaleInPlace(f);
  59092. p3.addToRef(this._edge, this._collisionPoint);
  59093. }
  59094. }
  59095. }
  59096. if (found) {
  59097. var distToCollision = t * this._velocity.length();
  59098. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  59099. if (!this.intersectionPoint) {
  59100. this.intersectionPoint = this._collisionPoint.clone();
  59101. }
  59102. else {
  59103. this.intersectionPoint.copyFrom(this._collisionPoint);
  59104. }
  59105. this._nearestDistance = distToCollision;
  59106. this.collisionFound = true;
  59107. }
  59108. }
  59109. };
  59110. /** @hidden */
  59111. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  59112. for (var i = indexStart; i < indexEnd; i += 3) {
  59113. var p1 = pts[indices[i] - decal];
  59114. var p2 = pts[indices[i + 1] - decal];
  59115. var p3 = pts[indices[i + 2] - decal];
  59116. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  59117. }
  59118. };
  59119. /** @hidden */
  59120. Collider.prototype._getResponse = function (pos, vel) {
  59121. pos.addToRef(vel, this._destinationPoint);
  59122. vel.scaleInPlace((this._nearestDistance / vel.length()));
  59123. this._basePoint.addToRef(vel, pos);
  59124. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  59125. this._slidePlaneNormal.normalize();
  59126. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  59127. pos.addInPlace(this._displacementVector);
  59128. this.intersectionPoint.addInPlace(this._displacementVector);
  59129. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  59130. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  59131. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  59132. };
  59133. return Collider;
  59134. }());
  59135. BABYLON.Collider = Collider;
  59136. })(BABYLON || (BABYLON = {}));
  59137. //# sourceMappingURL=babylon.collider.js.map
  59138. var BABYLON;
  59139. (function (BABYLON) {
  59140. //WebWorker code will be inserted to this variable.
  59141. /** @hidden */
  59142. BABYLON.CollisionWorker = "";
  59143. /** Defines supported task for worker process */
  59144. var WorkerTaskType;
  59145. (function (WorkerTaskType) {
  59146. /** Initialization */
  59147. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  59148. /** Update of geometry */
  59149. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  59150. /** Evaluate collision */
  59151. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  59152. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  59153. /** Defines kind of replies returned by worker */
  59154. var WorkerReplyType;
  59155. (function (WorkerReplyType) {
  59156. /** Success */
  59157. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  59158. /** Unkown error */
  59159. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  59160. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  59161. /** @hidden */
  59162. var CollisionCoordinatorWorker = /** @class */ (function () {
  59163. function CollisionCoordinatorWorker() {
  59164. var _this = this;
  59165. this._scaledPosition = BABYLON.Vector3.Zero();
  59166. this._scaledVelocity = BABYLON.Vector3.Zero();
  59167. this.onMeshUpdated = function (transformNode) {
  59168. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  59169. };
  59170. this.onGeometryUpdated = function (geometry) {
  59171. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  59172. };
  59173. this._afterRender = function () {
  59174. if (!_this._init) {
  59175. return;
  59176. }
  59177. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  59178. return;
  59179. }
  59180. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  59181. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  59182. if (_this._runningUpdated > 4) {
  59183. return;
  59184. }
  59185. ++_this._runningUpdated;
  59186. var payload = {
  59187. updatedMeshes: _this._addUpdateMeshesList,
  59188. updatedGeometries: _this._addUpdateGeometriesList,
  59189. removedGeometries: _this._toRemoveGeometryArray,
  59190. removedMeshes: _this._toRemoveMeshesArray
  59191. };
  59192. var message = {
  59193. payload: payload,
  59194. taskType: WorkerTaskType.UPDATE
  59195. };
  59196. var serializable = [];
  59197. for (var id in payload.updatedGeometries) {
  59198. if (payload.updatedGeometries.hasOwnProperty(id)) {
  59199. //prepare transferables
  59200. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  59201. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  59202. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  59203. }
  59204. }
  59205. _this._worker.postMessage(message, serializable);
  59206. _this._addUpdateMeshesList = {};
  59207. _this._addUpdateGeometriesList = {};
  59208. _this._toRemoveGeometryArray = [];
  59209. _this._toRemoveMeshesArray = [];
  59210. };
  59211. this._onMessageFromWorker = function (e) {
  59212. var returnData = e.data;
  59213. if (returnData.error != WorkerReplyType.SUCCESS) {
  59214. //TODO what errors can be returned from the worker?
  59215. BABYLON.Tools.Warn("error returned from worker!");
  59216. return;
  59217. }
  59218. switch (returnData.taskType) {
  59219. case WorkerTaskType.INIT:
  59220. _this._init = true;
  59221. //Update the worked with ALL of the scene's current state
  59222. _this._scene.meshes.forEach(function (mesh) {
  59223. _this.onMeshAdded(mesh);
  59224. });
  59225. _this._scene.getGeometries().forEach(function (geometry) {
  59226. _this.onGeometryAdded(geometry);
  59227. });
  59228. break;
  59229. case WorkerTaskType.UPDATE:
  59230. _this._runningUpdated--;
  59231. break;
  59232. case WorkerTaskType.COLLIDE:
  59233. var returnPayload = returnData.payload;
  59234. if (!_this._collisionsCallbackArray[returnPayload.collisionId]) {
  59235. return;
  59236. }
  59237. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  59238. if (callback) {
  59239. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  59240. if (mesh) {
  59241. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  59242. }
  59243. }
  59244. //cleanup
  59245. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  59246. break;
  59247. }
  59248. };
  59249. this._collisionsCallbackArray = [];
  59250. this._init = false;
  59251. this._runningUpdated = 0;
  59252. this._addUpdateMeshesList = {};
  59253. this._addUpdateGeometriesList = {};
  59254. this._toRemoveGeometryArray = [];
  59255. this._toRemoveMeshesArray = [];
  59256. }
  59257. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  59258. if (!this._init) {
  59259. return;
  59260. }
  59261. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000]) {
  59262. return;
  59263. }
  59264. position.divideToRef(collider._radius, this._scaledPosition);
  59265. displacement.divideToRef(collider._radius, this._scaledVelocity);
  59266. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  59267. var payload = {
  59268. collider: {
  59269. position: this._scaledPosition.asArray(),
  59270. velocity: this._scaledVelocity.asArray(),
  59271. radius: collider._radius.asArray()
  59272. },
  59273. collisionId: collisionIndex,
  59274. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  59275. maximumRetry: maximumRetry
  59276. };
  59277. var message = {
  59278. payload: payload,
  59279. taskType: WorkerTaskType.COLLIDE
  59280. };
  59281. this._worker.postMessage(message);
  59282. };
  59283. CollisionCoordinatorWorker.prototype.init = function (scene) {
  59284. this._scene = scene;
  59285. this._scene.registerAfterRender(this._afterRender);
  59286. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  59287. this._worker = new Worker(workerUrl);
  59288. this._worker.onmessage = this._onMessageFromWorker;
  59289. var message = {
  59290. payload: {},
  59291. taskType: WorkerTaskType.INIT
  59292. };
  59293. this._worker.postMessage(message);
  59294. };
  59295. CollisionCoordinatorWorker.prototype.destroy = function () {
  59296. this._scene.unregisterAfterRender(this._afterRender);
  59297. this._worker.terminate();
  59298. };
  59299. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  59300. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  59301. this.onMeshUpdated(mesh);
  59302. };
  59303. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  59304. this._toRemoveMeshesArray.push(mesh.uniqueId);
  59305. };
  59306. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  59307. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  59308. geometry.onGeometryUpdated = this.onGeometryUpdated;
  59309. this.onGeometryUpdated(geometry);
  59310. };
  59311. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  59312. this._toRemoveGeometryArray.push(geometry.id);
  59313. };
  59314. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  59315. var submeshes = [];
  59316. if (mesh.subMeshes) {
  59317. submeshes = mesh.subMeshes.map(function (sm, idx) {
  59318. var boundingInfo = sm.getBoundingInfo();
  59319. return {
  59320. position: idx,
  59321. verticesStart: sm.verticesStart,
  59322. verticesCount: sm.verticesCount,
  59323. indexStart: sm.indexStart,
  59324. indexCount: sm.indexCount,
  59325. hasMaterial: !!sm.getMaterial(),
  59326. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  59327. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  59328. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  59329. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  59330. };
  59331. });
  59332. }
  59333. var geometryId = null;
  59334. if (mesh instanceof BABYLON.Mesh) {
  59335. var geometry = mesh.geometry;
  59336. geometryId = geometry ? geometry.id : null;
  59337. }
  59338. else if (mesh instanceof BABYLON.InstancedMesh) {
  59339. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  59340. geometryId = geometry ? geometry.id : null;
  59341. }
  59342. var boundingInfo = mesh.getBoundingInfo();
  59343. return {
  59344. uniqueId: mesh.uniqueId,
  59345. id: mesh.id,
  59346. name: mesh.name,
  59347. geometryId: geometryId,
  59348. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  59349. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  59350. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  59351. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  59352. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  59353. subMeshes: submeshes,
  59354. checkCollisions: mesh.checkCollisions
  59355. };
  59356. };
  59357. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  59358. return {
  59359. id: geometry.id,
  59360. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  59361. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  59362. indices: new Uint32Array(geometry.getIndices() || []),
  59363. };
  59364. };
  59365. return CollisionCoordinatorWorker;
  59366. }());
  59367. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  59368. /** @hidden */
  59369. var CollisionCoordinatorLegacy = /** @class */ (function () {
  59370. function CollisionCoordinatorLegacy() {
  59371. this._scaledPosition = BABYLON.Vector3.Zero();
  59372. this._scaledVelocity = BABYLON.Vector3.Zero();
  59373. this._finalPosition = BABYLON.Vector3.Zero();
  59374. }
  59375. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  59376. position.divideToRef(collider._radius, this._scaledPosition);
  59377. displacement.divideToRef(collider._radius, this._scaledVelocity);
  59378. collider.collidedMesh = null;
  59379. collider._retry = 0;
  59380. collider._initialVelocity = this._scaledVelocity;
  59381. collider._initialPosition = this._scaledPosition;
  59382. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  59383. this._finalPosition.multiplyInPlace(collider._radius);
  59384. //run the callback
  59385. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  59386. };
  59387. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  59388. this._scene = scene;
  59389. };
  59390. CollisionCoordinatorLegacy.prototype.destroy = function () {
  59391. //Legacy need no destruction method.
  59392. };
  59393. //No update in legacy mode
  59394. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  59395. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  59396. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  59397. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  59398. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  59399. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  59400. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  59401. if (excludedMesh === void 0) { excludedMesh = null; }
  59402. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  59403. if (collider._retry >= maximumRetry) {
  59404. finalPosition.copyFrom(position);
  59405. return;
  59406. }
  59407. // Check if this is a mesh else camera or -1
  59408. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  59409. collider._initialize(position, velocity, closeDistance);
  59410. // Check all meshes
  59411. for (var index = 0; index < this._scene.meshes.length; index++) {
  59412. var mesh = this._scene.meshes[index];
  59413. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  59414. mesh._checkCollision(collider);
  59415. }
  59416. }
  59417. if (!collider.collisionFound) {
  59418. position.addToRef(velocity, finalPosition);
  59419. return;
  59420. }
  59421. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  59422. collider._getResponse(position, velocity);
  59423. }
  59424. if (velocity.length() <= closeDistance) {
  59425. finalPosition.copyFrom(position);
  59426. return;
  59427. }
  59428. collider._retry++;
  59429. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  59430. };
  59431. return CollisionCoordinatorLegacy;
  59432. }());
  59433. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  59434. })(BABYLON || (BABYLON = {}));
  59435. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  59436. var BABYLON;
  59437. (function (BABYLON) {
  59438. /**
  59439. * A particle represents one of the element emitted by a particle system.
  59440. * This is mainly define by its coordinates, direction, velocity and age.
  59441. */
  59442. var Particle = /** @class */ (function () {
  59443. /**
  59444. * Creates a new instance Particle
  59445. * @param particleSystem the particle system the particle belongs to
  59446. */
  59447. function Particle(
  59448. /**
  59449. * The particle system the particle belongs to.
  59450. */
  59451. particleSystem) {
  59452. this.particleSystem = particleSystem;
  59453. /**
  59454. * The world position of the particle in the scene.
  59455. */
  59456. this.position = BABYLON.Vector3.Zero();
  59457. /**
  59458. * The world direction of the particle in the scene.
  59459. */
  59460. this.direction = BABYLON.Vector3.Zero();
  59461. /**
  59462. * The color of the particle.
  59463. */
  59464. this.color = new BABYLON.Color4(0, 0, 0, 0);
  59465. /**
  59466. * The color change of the particle per step.
  59467. */
  59468. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  59469. /**
  59470. * Defines how long will the life of the particle be.
  59471. */
  59472. this.lifeTime = 1.0;
  59473. /**
  59474. * The current age of the particle.
  59475. */
  59476. this.age = 0;
  59477. /**
  59478. * The current size of the particle.
  59479. */
  59480. this.size = 0;
  59481. /**
  59482. * The current scale of the particle.
  59483. */
  59484. this.scale = new BABYLON.Vector2(1, 1);
  59485. /**
  59486. * The current angle of the particle.
  59487. */
  59488. this.angle = 0;
  59489. /**
  59490. * Defines how fast is the angle changing.
  59491. */
  59492. this.angularSpeed = 0;
  59493. /**
  59494. * Defines the cell index used by the particle to be rendered from a sprite.
  59495. */
  59496. this.cellIndex = 0;
  59497. /** @hidden */
  59498. this._attachedSubEmitters = null;
  59499. /** @hidden */
  59500. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  59501. /** @hidden */
  59502. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  59503. /** @hidden */
  59504. this._currentSize1 = 0;
  59505. /** @hidden */
  59506. this._currentSize2 = 0;
  59507. /** @hidden */
  59508. this._currentAngularSpeed1 = 0;
  59509. /** @hidden */
  59510. this._currentAngularSpeed2 = 0;
  59511. /** @hidden */
  59512. this._currentVelocity1 = 0;
  59513. /** @hidden */
  59514. this._currentVelocity2 = 0;
  59515. /** @hidden */
  59516. this._currentLimitVelocity1 = 0;
  59517. /** @hidden */
  59518. this._currentLimitVelocity2 = 0;
  59519. /** @hidden */
  59520. this._currentDrag1 = 0;
  59521. /** @hidden */
  59522. this._currentDrag2 = 0;
  59523. this.id = Particle._Count++;
  59524. if (!this.particleSystem.isAnimationSheetEnabled) {
  59525. return;
  59526. }
  59527. this.updateCellInfoFromSystem();
  59528. }
  59529. Particle.prototype.updateCellInfoFromSystem = function () {
  59530. this.cellIndex = this.particleSystem.startSpriteCellID;
  59531. };
  59532. /**
  59533. * Defines how the sprite cell index is updated for the particle
  59534. */
  59535. Particle.prototype.updateCellIndex = function () {
  59536. var offsetAge = this.age;
  59537. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  59538. if (this.particleSystem.spriteRandomStartCell) {
  59539. if (this._randomCellOffset === undefined) {
  59540. this._randomCellOffset = Math.random() * this.lifeTime;
  59541. }
  59542. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  59543. changeSpeed = 1;
  59544. offsetAge = this._randomCellOffset;
  59545. }
  59546. else {
  59547. offsetAge += this._randomCellOffset;
  59548. }
  59549. }
  59550. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  59551. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  59552. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  59553. };
  59554. /** @hidden */
  59555. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  59556. if (subEmitter.particleSystem.emitter.position) {
  59557. var emitterMesh = subEmitter.particleSystem.emitter;
  59558. emitterMesh.position.copyFrom(this.position);
  59559. if (subEmitter.inheritDirection) {
  59560. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  59561. // Look at using Y as forward
  59562. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  59563. }
  59564. }
  59565. else {
  59566. var emitterPosition = subEmitter.particleSystem.emitter;
  59567. emitterPosition.copyFrom(this.position);
  59568. }
  59569. // Set inheritedVelocityOffset to be used when new particles are created
  59570. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  59571. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  59572. };
  59573. /** @hidden */
  59574. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  59575. var _this = this;
  59576. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  59577. this._attachedSubEmitters.forEach(function (subEmitter) {
  59578. _this._inheritParticleInfoToSubEmitter(subEmitter);
  59579. });
  59580. }
  59581. };
  59582. /** @hidden */
  59583. Particle.prototype._reset = function () {
  59584. this.age = 0;
  59585. this._currentColorGradient = null;
  59586. this._currentSizeGradient = null;
  59587. this._currentAngularSpeedGradient = null;
  59588. this._currentVelocityGradient = null;
  59589. this._currentLimitVelocityGradient = null;
  59590. this._currentDragGradient = null;
  59591. this.cellIndex = this.particleSystem.startSpriteCellID;
  59592. this._randomCellOffset = undefined;
  59593. };
  59594. /**
  59595. * Copy the properties of particle to another one.
  59596. * @param other the particle to copy the information to.
  59597. */
  59598. Particle.prototype.copyTo = function (other) {
  59599. other.position.copyFrom(this.position);
  59600. if (this._initialDirection) {
  59601. if (other._initialDirection) {
  59602. other._initialDirection.copyFrom(this._initialDirection);
  59603. }
  59604. else {
  59605. other._initialDirection = this._initialDirection.clone();
  59606. }
  59607. }
  59608. else {
  59609. other._initialDirection = null;
  59610. }
  59611. other.direction.copyFrom(this.direction);
  59612. other.color.copyFrom(this.color);
  59613. other.colorStep.copyFrom(this.colorStep);
  59614. other.lifeTime = this.lifeTime;
  59615. other.age = this.age;
  59616. other._randomCellOffset = this._randomCellOffset;
  59617. other.size = this.size;
  59618. other.scale.copyFrom(this.scale);
  59619. other.angle = this.angle;
  59620. other.angularSpeed = this.angularSpeed;
  59621. other.particleSystem = this.particleSystem;
  59622. other.cellIndex = this.cellIndex;
  59623. other.id = this.id;
  59624. other._attachedSubEmitters = this._attachedSubEmitters;
  59625. if (this._currentColorGradient) {
  59626. other._currentColorGradient = this._currentColorGradient;
  59627. other._currentColor1.copyFrom(this._currentColor1);
  59628. other._currentColor2.copyFrom(this._currentColor2);
  59629. }
  59630. if (this._currentSizeGradient) {
  59631. other._currentSizeGradient = this._currentSizeGradient;
  59632. other._currentSize1 = this._currentSize1;
  59633. other._currentSize2 = this._currentSize2;
  59634. }
  59635. if (this._currentAngularSpeedGradient) {
  59636. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  59637. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  59638. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  59639. }
  59640. if (this._currentVelocityGradient) {
  59641. other._currentVelocityGradient = this._currentVelocityGradient;
  59642. other._currentVelocity1 = this._currentVelocity1;
  59643. other._currentVelocity2 = this._currentVelocity2;
  59644. }
  59645. if (this._currentLimitVelocityGradient) {
  59646. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  59647. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  59648. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  59649. }
  59650. if (this._currentDragGradient) {
  59651. other._currentDragGradient = this._currentDragGradient;
  59652. other._currentDrag1 = this._currentDrag1;
  59653. other._currentDrag2 = this._currentDrag2;
  59654. }
  59655. if (this.particleSystem.isAnimationSheetEnabled) {
  59656. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  59657. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  59658. }
  59659. if (this.particleSystem.useRampGradients) {
  59660. other.remapData.copyFrom(this.remapData);
  59661. }
  59662. if (this._randomNoiseCoordinates1) {
  59663. if (other._randomNoiseCoordinates1) {
  59664. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  59665. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  59666. }
  59667. else {
  59668. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  59669. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  59670. }
  59671. }
  59672. };
  59673. Particle._Count = 0;
  59674. return Particle;
  59675. }());
  59676. BABYLON.Particle = Particle;
  59677. })(BABYLON || (BABYLON = {}));
  59678. //# sourceMappingURL=babylon.particle.js.map
  59679. var BABYLON;
  59680. (function (BABYLON) {
  59681. /**
  59682. * This represents the base class for particle system in Babylon.
  59683. * 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.
  59684. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  59685. * @example https://doc.babylonjs.com/babylon101/particles
  59686. */
  59687. var BaseParticleSystem = /** @class */ (function () {
  59688. /**
  59689. * Instantiates a particle system.
  59690. * 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.
  59691. * @param name The name of the particle system
  59692. */
  59693. function BaseParticleSystem(name) {
  59694. /**
  59695. * List of animations used by the particle system.
  59696. */
  59697. this.animations = [];
  59698. /**
  59699. * The rendering group used by the Particle system to chose when to render.
  59700. */
  59701. this.renderingGroupId = 0;
  59702. /**
  59703. * The emitter represents the Mesh or position we are attaching the particle system to.
  59704. */
  59705. this.emitter = null;
  59706. /**
  59707. * The maximum number of particles to emit per frame
  59708. */
  59709. this.emitRate = 10;
  59710. /**
  59711. * If you want to launch only a few particles at once, that can be done, as well.
  59712. */
  59713. this.manualEmitCount = -1;
  59714. /**
  59715. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  59716. */
  59717. this.updateSpeed = 0.01;
  59718. /**
  59719. * The amount of time the particle system is running (depends of the overall update speed).
  59720. */
  59721. this.targetStopDuration = 0;
  59722. /**
  59723. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  59724. */
  59725. this.disposeOnStop = false;
  59726. /**
  59727. * Minimum power of emitting particles.
  59728. */
  59729. this.minEmitPower = 1;
  59730. /**
  59731. * Maximum power of emitting particles.
  59732. */
  59733. this.maxEmitPower = 1;
  59734. /**
  59735. * Minimum life time of emitting particles.
  59736. */
  59737. this.minLifeTime = 1;
  59738. /**
  59739. * Maximum life time of emitting particles.
  59740. */
  59741. this.maxLifeTime = 1;
  59742. /**
  59743. * Minimum Size of emitting particles.
  59744. */
  59745. this.minSize = 1;
  59746. /**
  59747. * Maximum Size of emitting particles.
  59748. */
  59749. this.maxSize = 1;
  59750. /**
  59751. * Minimum scale of emitting particles on X axis.
  59752. */
  59753. this.minScaleX = 1;
  59754. /**
  59755. * Maximum scale of emitting particles on X axis.
  59756. */
  59757. this.maxScaleX = 1;
  59758. /**
  59759. * Minimum scale of emitting particles on Y axis.
  59760. */
  59761. this.minScaleY = 1;
  59762. /**
  59763. * Maximum scale of emitting particles on Y axis.
  59764. */
  59765. this.maxScaleY = 1;
  59766. /**
  59767. * Gets or sets the minimal initial rotation in radians.
  59768. */
  59769. this.minInitialRotation = 0;
  59770. /**
  59771. * Gets or sets the maximal initial rotation in radians.
  59772. */
  59773. this.maxInitialRotation = 0;
  59774. /**
  59775. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  59776. */
  59777. this.minAngularSpeed = 0;
  59778. /**
  59779. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  59780. */
  59781. this.maxAngularSpeed = 0;
  59782. /**
  59783. * The layer mask we are rendering the particles through.
  59784. */
  59785. this.layerMask = 0x0FFFFFFF;
  59786. /**
  59787. * This can help using your own shader to render the particle system.
  59788. * The according effect will be created
  59789. */
  59790. this.customShader = null;
  59791. /**
  59792. * By default particle system starts as soon as they are created. This prevents the
  59793. * automatic start to happen and let you decide when to start emitting particles.
  59794. */
  59795. this.preventAutoStart = false;
  59796. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  59797. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  59798. /**
  59799. * Callback triggered when the particle animation is ending.
  59800. */
  59801. this.onAnimationEnd = null;
  59802. /**
  59803. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  59804. */
  59805. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  59806. /**
  59807. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  59808. * to override the particles.
  59809. */
  59810. this.forceDepthWrite = false;
  59811. /** 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 */
  59812. this.preWarmCycles = 0;
  59813. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  59814. this.preWarmStepOffset = 1;
  59815. /**
  59816. * 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)
  59817. */
  59818. this.spriteCellChangeSpeed = 1;
  59819. /**
  59820. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  59821. */
  59822. this.startSpriteCellID = 0;
  59823. /**
  59824. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  59825. */
  59826. this.endSpriteCellID = 0;
  59827. /**
  59828. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  59829. */
  59830. this.spriteCellWidth = 0;
  59831. /**
  59832. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  59833. */
  59834. this.spriteCellHeight = 0;
  59835. /**
  59836. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  59837. */
  59838. this.spriteRandomStartCell = false;
  59839. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  59840. this.translationPivot = new BABYLON.Vector2(0, 0);
  59841. /**
  59842. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  59843. */
  59844. this.beginAnimationOnStart = false;
  59845. /**
  59846. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  59847. */
  59848. this.beginAnimationFrom = 0;
  59849. /**
  59850. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  59851. */
  59852. this.beginAnimationTo = 60;
  59853. /**
  59854. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  59855. */
  59856. this.beginAnimationLoop = false;
  59857. /**
  59858. * You can use gravity if you want to give an orientation to your particles.
  59859. */
  59860. this.gravity = BABYLON.Vector3.Zero();
  59861. this._colorGradients = null;
  59862. this._sizeGradients = null;
  59863. this._lifeTimeGradients = null;
  59864. this._angularSpeedGradients = null;
  59865. this._velocityGradients = null;
  59866. this._limitVelocityGradients = null;
  59867. this._dragGradients = null;
  59868. this._emitRateGradients = null;
  59869. this._startSizeGradients = null;
  59870. this._rampGradients = null;
  59871. this._colorRemapGradients = null;
  59872. this._alphaRemapGradients = null;
  59873. /**
  59874. * Defines the delay in milliseconds before starting the system (0 by default)
  59875. */
  59876. this.startDelay = 0;
  59877. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  59878. this.limitVelocityDamping = 0.4;
  59879. /**
  59880. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  59881. */
  59882. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59883. /**
  59884. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  59885. */
  59886. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59887. /**
  59888. * Color the particle will have at the end of its lifetime
  59889. */
  59890. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  59891. /**
  59892. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  59893. */
  59894. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59895. /** @hidden */
  59896. this._isSubEmitter = false;
  59897. /**
  59898. * Gets or sets the billboard mode to use when isBillboardBased = true.
  59899. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  59900. */
  59901. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  59902. this._isBillboardBased = true;
  59903. /**
  59904. * Local cache of defines for image processing.
  59905. */
  59906. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  59907. this.id = name;
  59908. this.name = name;
  59909. }
  59910. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  59911. /**
  59912. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  59913. */
  59914. get: function () {
  59915. return this._isAnimationSheetEnabled;
  59916. },
  59917. set: function (value) {
  59918. if (this._isAnimationSheetEnabled == value) {
  59919. return;
  59920. }
  59921. this._isAnimationSheetEnabled = value;
  59922. this._reset();
  59923. },
  59924. enumerable: true,
  59925. configurable: true
  59926. });
  59927. /**
  59928. * Get hosting scene
  59929. * @returns the scene
  59930. */
  59931. BaseParticleSystem.prototype.getScene = function () {
  59932. return this._scene;
  59933. };
  59934. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  59935. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  59936. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  59937. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  59938. };
  59939. /**
  59940. * Gets the current list of drag gradients.
  59941. * You must use addDragGradient and removeDragGradient to udpate this list
  59942. * @returns the list of drag gradients
  59943. */
  59944. BaseParticleSystem.prototype.getDragGradients = function () {
  59945. return this._dragGradients;
  59946. };
  59947. /**
  59948. * Gets the current list of limit velocity gradients.
  59949. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  59950. * @returns the list of limit velocity gradients
  59951. */
  59952. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  59953. return this._limitVelocityGradients;
  59954. };
  59955. /**
  59956. * Gets the current list of color gradients.
  59957. * You must use addColorGradient and removeColorGradient to udpate this list
  59958. * @returns the list of color gradients
  59959. */
  59960. BaseParticleSystem.prototype.getColorGradients = function () {
  59961. return this._colorGradients;
  59962. };
  59963. /**
  59964. * Gets the current list of size gradients.
  59965. * You must use addSizeGradient and removeSizeGradient to udpate this list
  59966. * @returns the list of size gradients
  59967. */
  59968. BaseParticleSystem.prototype.getSizeGradients = function () {
  59969. return this._sizeGradients;
  59970. };
  59971. /**
  59972. * Gets the current list of color remap gradients.
  59973. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  59974. * @returns the list of color remap gradients
  59975. */
  59976. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  59977. return this._colorRemapGradients;
  59978. };
  59979. /**
  59980. * Gets the current list of alpha remap gradients.
  59981. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  59982. * @returns the list of alpha remap gradients
  59983. */
  59984. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  59985. return this._alphaRemapGradients;
  59986. };
  59987. /**
  59988. * Gets the current list of life time gradients.
  59989. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  59990. * @returns the list of life time gradients
  59991. */
  59992. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  59993. return this._lifeTimeGradients;
  59994. };
  59995. /**
  59996. * Gets the current list of angular speed gradients.
  59997. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  59998. * @returns the list of angular speed gradients
  59999. */
  60000. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  60001. return this._angularSpeedGradients;
  60002. };
  60003. /**
  60004. * Gets the current list of velocity gradients.
  60005. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  60006. * @returns the list of velocity gradients
  60007. */
  60008. BaseParticleSystem.prototype.getVelocityGradients = function () {
  60009. return this._velocityGradients;
  60010. };
  60011. /**
  60012. * Gets the current list of start size gradients.
  60013. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  60014. * @returns the list of start size gradients
  60015. */
  60016. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  60017. return this._startSizeGradients;
  60018. };
  60019. /**
  60020. * Gets the current list of emit rate gradients.
  60021. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  60022. * @returns the list of emit rate gradients
  60023. */
  60024. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  60025. return this._emitRateGradients;
  60026. };
  60027. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  60028. /**
  60029. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60030. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60031. */
  60032. get: function () {
  60033. if (this.particleEmitterType.direction1) {
  60034. return this.particleEmitterType.direction1;
  60035. }
  60036. return BABYLON.Vector3.Zero();
  60037. },
  60038. set: function (value) {
  60039. if (this.particleEmitterType.direction1) {
  60040. this.particleEmitterType.direction1 = value;
  60041. }
  60042. },
  60043. enumerable: true,
  60044. configurable: true
  60045. });
  60046. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  60047. /**
  60048. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60049. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60050. */
  60051. get: function () {
  60052. if (this.particleEmitterType.direction2) {
  60053. return this.particleEmitterType.direction2;
  60054. }
  60055. return BABYLON.Vector3.Zero();
  60056. },
  60057. set: function (value) {
  60058. if (this.particleEmitterType.direction2) {
  60059. this.particleEmitterType.direction2 = value;
  60060. }
  60061. },
  60062. enumerable: true,
  60063. configurable: true
  60064. });
  60065. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  60066. /**
  60067. * 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.
  60068. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60069. */
  60070. get: function () {
  60071. if (this.particleEmitterType.minEmitBox) {
  60072. return this.particleEmitterType.minEmitBox;
  60073. }
  60074. return BABYLON.Vector3.Zero();
  60075. },
  60076. set: function (value) {
  60077. if (this.particleEmitterType.minEmitBox) {
  60078. this.particleEmitterType.minEmitBox = value;
  60079. }
  60080. },
  60081. enumerable: true,
  60082. configurable: true
  60083. });
  60084. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  60085. /**
  60086. * 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.
  60087. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60088. */
  60089. get: function () {
  60090. if (this.particleEmitterType.maxEmitBox) {
  60091. return this.particleEmitterType.maxEmitBox;
  60092. }
  60093. return BABYLON.Vector3.Zero();
  60094. },
  60095. set: function (value) {
  60096. if (this.particleEmitterType.maxEmitBox) {
  60097. this.particleEmitterType.maxEmitBox = value;
  60098. }
  60099. },
  60100. enumerable: true,
  60101. configurable: true
  60102. });
  60103. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  60104. /**
  60105. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  60106. */
  60107. get: function () {
  60108. return this._isBillboardBased;
  60109. },
  60110. set: function (value) {
  60111. if (this._isBillboardBased === value) {
  60112. return;
  60113. }
  60114. this._isBillboardBased = value;
  60115. this._reset();
  60116. },
  60117. enumerable: true,
  60118. configurable: true
  60119. });
  60120. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  60121. /**
  60122. * Gets the image processing configuration used either in this material.
  60123. */
  60124. get: function () {
  60125. return this._imageProcessingConfiguration;
  60126. },
  60127. /**
  60128. * Sets the Default image processing configuration used either in the this material.
  60129. *
  60130. * If sets to null, the scene one is in use.
  60131. */
  60132. set: function (value) {
  60133. this._attachImageProcessingConfiguration(value);
  60134. },
  60135. enumerable: true,
  60136. configurable: true
  60137. });
  60138. /**
  60139. * Attaches a new image processing configuration to the Standard Material.
  60140. * @param configuration
  60141. */
  60142. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  60143. if (configuration === this._imageProcessingConfiguration) {
  60144. return;
  60145. }
  60146. // Pick the scene configuration if needed.
  60147. if (!configuration) {
  60148. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  60149. }
  60150. else {
  60151. this._imageProcessingConfiguration = configuration;
  60152. }
  60153. };
  60154. /** @hidden */
  60155. BaseParticleSystem.prototype._reset = function () {
  60156. };
  60157. /** @hidden */
  60158. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  60159. if (!gradients) {
  60160. return this;
  60161. }
  60162. var index = 0;
  60163. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60164. var valueGradient = gradients_1[_i];
  60165. if (valueGradient.gradient === gradient) {
  60166. gradients.splice(index, 1);
  60167. break;
  60168. }
  60169. index++;
  60170. }
  60171. if (texture) {
  60172. texture.dispose();
  60173. }
  60174. return this;
  60175. };
  60176. /**
  60177. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  60178. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  60179. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  60180. * @returns the emitter
  60181. */
  60182. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  60183. var particleEmitter = new BABYLON.PointParticleEmitter();
  60184. particleEmitter.direction1 = direction1;
  60185. particleEmitter.direction2 = direction2;
  60186. this.particleEmitterType = particleEmitter;
  60187. return particleEmitter;
  60188. };
  60189. /**
  60190. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  60191. * @param radius The radius of the hemisphere to emit from
  60192. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  60193. * @returns the emitter
  60194. */
  60195. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  60196. if (radius === void 0) { radius = 1; }
  60197. if (radiusRange === void 0) { radiusRange = 1; }
  60198. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  60199. this.particleEmitterType = particleEmitter;
  60200. return particleEmitter;
  60201. };
  60202. /**
  60203. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  60204. * @param radius The radius of the sphere to emit from
  60205. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  60206. * @returns the emitter
  60207. */
  60208. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  60209. if (radius === void 0) { radius = 1; }
  60210. if (radiusRange === void 0) { radiusRange = 1; }
  60211. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  60212. this.particleEmitterType = particleEmitter;
  60213. return particleEmitter;
  60214. };
  60215. /**
  60216. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  60217. * @param radius The radius of the sphere to emit from
  60218. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  60219. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  60220. * @returns the emitter
  60221. */
  60222. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  60223. if (radius === void 0) { radius = 1; }
  60224. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  60225. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  60226. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  60227. this.particleEmitterType = particleEmitter;
  60228. return particleEmitter;
  60229. };
  60230. /**
  60231. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  60232. * @param radius The radius of the emission cylinder
  60233. * @param height The height of the emission cylinder
  60234. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  60235. * @param directionRandomizer How much to randomize the particle direction [0-1]
  60236. * @returns the emitter
  60237. */
  60238. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  60239. if (radius === void 0) { radius = 1; }
  60240. if (height === void 0) { height = 1; }
  60241. if (radiusRange === void 0) { radiusRange = 1; }
  60242. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60243. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  60244. this.particleEmitterType = particleEmitter;
  60245. return particleEmitter;
  60246. };
  60247. /**
  60248. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  60249. * @param radius The radius of the cylinder to emit from
  60250. * @param height The height of the emission cylinder
  60251. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60252. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  60253. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  60254. * @returns the emitter
  60255. */
  60256. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  60257. if (radius === void 0) { radius = 1; }
  60258. if (height === void 0) { height = 1; }
  60259. if (radiusRange === void 0) { radiusRange = 1; }
  60260. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  60261. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  60262. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  60263. this.particleEmitterType = particleEmitter;
  60264. return particleEmitter;
  60265. };
  60266. /**
  60267. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  60268. * @param radius The radius of the cone to emit from
  60269. * @param angle The base angle of the cone
  60270. * @returns the emitter
  60271. */
  60272. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  60273. if (radius === void 0) { radius = 1; }
  60274. if (angle === void 0) { angle = Math.PI / 4; }
  60275. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  60276. this.particleEmitterType = particleEmitter;
  60277. return particleEmitter;
  60278. };
  60279. /**
  60280. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  60281. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  60282. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  60283. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  60284. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  60285. * @returns the emitter
  60286. */
  60287. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  60288. var particleEmitter = new BABYLON.BoxParticleEmitter();
  60289. this.particleEmitterType = particleEmitter;
  60290. this.direction1 = direction1;
  60291. this.direction2 = direction2;
  60292. this.minEmitBox = minEmitBox;
  60293. this.maxEmitBox = maxEmitBox;
  60294. return particleEmitter;
  60295. };
  60296. /**
  60297. * Source color is added to the destination color without alpha affecting the result
  60298. */
  60299. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  60300. /**
  60301. * Blend current color and particle color using particle’s alpha
  60302. */
  60303. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  60304. /**
  60305. * Add current color and particle color multiplied by particle’s alpha
  60306. */
  60307. BaseParticleSystem.BLENDMODE_ADD = 2;
  60308. /**
  60309. * Multiply current color with particle color
  60310. */
  60311. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  60312. /**
  60313. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  60314. */
  60315. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  60316. return BaseParticleSystem;
  60317. }());
  60318. BABYLON.BaseParticleSystem = BaseParticleSystem;
  60319. })(BABYLON || (BABYLON = {}));
  60320. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  60321. var BABYLON;
  60322. (function (BABYLON) {
  60323. /**
  60324. * This represents a particle system in Babylon.
  60325. * 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.
  60326. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  60327. * @example https://doc.babylonjs.com/babylon101/particles
  60328. */
  60329. var ParticleSystem = /** @class */ (function (_super) {
  60330. __extends(ParticleSystem, _super);
  60331. /**
  60332. * Instantiates a particle system.
  60333. * 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.
  60334. * @param name The name of the particle system
  60335. * @param capacity The max number of particles alive at the same time
  60336. * @param scene The scene the particle system belongs to
  60337. * @param customEffect a custom effect used to change the way particles are rendered by default
  60338. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60339. * @param epsilon Offset used to render the particles
  60340. */
  60341. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  60342. if (customEffect === void 0) { customEffect = null; }
  60343. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60344. if (epsilon === void 0) { epsilon = 0.01; }
  60345. var _this = _super.call(this, name) || this;
  60346. /**
  60347. * @hidden
  60348. */
  60349. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  60350. /**
  60351. * An event triggered when the system is disposed
  60352. */
  60353. _this.onDisposeObservable = new BABYLON.Observable();
  60354. _this._particles = new Array();
  60355. _this._stockParticles = new Array();
  60356. _this._newPartsExcess = 0;
  60357. _this._vertexBuffers = {};
  60358. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  60359. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  60360. _this._scaledDirection = BABYLON.Vector3.Zero();
  60361. _this._scaledGravity = BABYLON.Vector3.Zero();
  60362. _this._currentRenderId = -1;
  60363. _this._useInstancing = false;
  60364. _this._started = false;
  60365. _this._stopped = false;
  60366. _this._actualFrame = 0;
  60367. /** @hidden */
  60368. _this._currentEmitRate1 = 0;
  60369. /** @hidden */
  60370. _this._currentEmitRate2 = 0;
  60371. /** @hidden */
  60372. _this._currentStartSize1 = 0;
  60373. /** @hidden */
  60374. _this._currentStartSize2 = 0;
  60375. _this._rawTextureWidth = 256;
  60376. _this._useRampGradients = false;
  60377. /**
  60378. * @hidden
  60379. * If the particle systems emitter should be disposed when the particle system is disposed
  60380. */
  60381. _this._disposeEmitterOnDispose = false;
  60382. // start of sub system methods
  60383. /**
  60384. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  60385. * Its lifetime will start back at 0.
  60386. */
  60387. _this.recycleParticle = function (particle) {
  60388. // move particle from activeParticle list to stock particles
  60389. var lastParticle = _this._particles.pop();
  60390. if (lastParticle !== particle) {
  60391. lastParticle.copyTo(particle);
  60392. }
  60393. _this._stockParticles.push(lastParticle);
  60394. };
  60395. _this._createParticle = function () {
  60396. var particle;
  60397. if (_this._stockParticles.length !== 0) {
  60398. particle = _this._stockParticles.pop();
  60399. particle._reset();
  60400. }
  60401. else {
  60402. particle = new BABYLON.Particle(_this);
  60403. }
  60404. // Attach emitters
  60405. if (_this._subEmitters && _this._subEmitters.length > 0) {
  60406. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  60407. particle._attachedSubEmitters = [];
  60408. subEmitters.forEach(function (subEmitter) {
  60409. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  60410. var newEmitter = subEmitter.clone();
  60411. particle._attachedSubEmitters.push(newEmitter);
  60412. newEmitter.particleSystem.start();
  60413. }
  60414. });
  60415. }
  60416. return particle;
  60417. };
  60418. _this._emitFromParticle = function (particle) {
  60419. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  60420. return;
  60421. }
  60422. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  60423. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  60424. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  60425. var subSystem = subEmitter.clone();
  60426. particle._inheritParticleInfoToSubEmitter(subSystem);
  60427. subSystem.particleSystem._rootParticleSystem = _this;
  60428. _this.activeSubSystems.push(subSystem.particleSystem);
  60429. subSystem.particleSystem.start();
  60430. }
  60431. });
  60432. };
  60433. _this._capacity = capacity;
  60434. _this._epsilon = epsilon;
  60435. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60436. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60437. // Setup the default processing configuration to the scene.
  60438. _this._attachImageProcessingConfiguration(null);
  60439. _this._customEffect = customEffect;
  60440. _this._scene.particleSystems.push(_this);
  60441. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  60442. _this._createIndexBuffer();
  60443. _this._createVertexBuffers();
  60444. // Default emitter type
  60445. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60446. // Update
  60447. _this.updateFunction = function (particles) {
  60448. var noiseTextureSize = null;
  60449. var noiseTextureData = null;
  60450. if (_this.noiseTexture) { // We need to get texture data back to CPU
  60451. noiseTextureSize = _this.noiseTexture.getSize();
  60452. noiseTextureData = (_this.noiseTexture.getContent());
  60453. }
  60454. var _loop_1 = function () {
  60455. particle = particles[index];
  60456. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  60457. var previousAge = particle.age;
  60458. particle.age += scaledUpdateSpeed;
  60459. // Evaluate step to death
  60460. if (particle.age > particle.lifeTime) {
  60461. var diff = particle.age - previousAge;
  60462. var oldDiff = particle.lifeTime - previousAge;
  60463. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  60464. particle.age = particle.lifeTime;
  60465. }
  60466. var ratio = particle.age / particle.lifeTime;
  60467. // Color
  60468. if (_this._colorGradients && _this._colorGradients.length > 0) {
  60469. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  60470. if (currentGradient !== particle._currentColorGradient) {
  60471. particle._currentColor1.copyFrom(particle._currentColor2);
  60472. nextGradient.getColorToRef(particle._currentColor2);
  60473. particle._currentColorGradient = currentGradient;
  60474. }
  60475. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  60476. });
  60477. }
  60478. else {
  60479. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  60480. particle.color.addInPlace(_this._scaledColorStep);
  60481. if (particle.color.a < 0) {
  60482. particle.color.a = 0;
  60483. }
  60484. }
  60485. // Angular speed
  60486. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  60487. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  60488. if (currentGradient !== particle._currentAngularSpeedGradient) {
  60489. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  60490. particle._currentAngularSpeed2 = nextGradient.getFactor();
  60491. particle._currentAngularSpeedGradient = currentGradient;
  60492. }
  60493. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  60494. });
  60495. }
  60496. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  60497. // Direction
  60498. var directionScale = scaledUpdateSpeed;
  60499. /// Velocity
  60500. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  60501. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  60502. if (currentGradient !== particle._currentVelocityGradient) {
  60503. particle._currentVelocity1 = particle._currentVelocity2;
  60504. particle._currentVelocity2 = nextGradient.getFactor();
  60505. particle._currentVelocityGradient = currentGradient;
  60506. }
  60507. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  60508. });
  60509. }
  60510. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  60511. /// Limit velocity
  60512. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  60513. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  60514. if (currentGradient !== particle._currentLimitVelocityGradient) {
  60515. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  60516. particle._currentLimitVelocity2 = nextGradient.getFactor();
  60517. particle._currentLimitVelocityGradient = currentGradient;
  60518. }
  60519. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  60520. var currentVelocity = particle.direction.length();
  60521. if (currentVelocity > limitVelocity) {
  60522. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  60523. }
  60524. });
  60525. }
  60526. /// Drag
  60527. if (_this._dragGradients && _this._dragGradients.length > 0) {
  60528. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  60529. if (currentGradient !== particle._currentDragGradient) {
  60530. particle._currentDrag1 = particle._currentDrag2;
  60531. particle._currentDrag2 = nextGradient.getFactor();
  60532. particle._currentDragGradient = currentGradient;
  60533. }
  60534. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  60535. _this._scaledDirection.scaleInPlace(1.0 - drag);
  60536. });
  60537. }
  60538. particle.position.addInPlace(_this._scaledDirection);
  60539. // Noise
  60540. if (noiseTextureData && noiseTextureSize) {
  60541. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60542. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60543. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60544. var force = BABYLON.Tmp.Vector3[0];
  60545. var scaledForce = BABYLON.Tmp.Vector3[1];
  60546. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  60547. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  60548. particle.direction.addInPlace(scaledForce);
  60549. }
  60550. // Gravity
  60551. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  60552. particle.direction.addInPlace(_this._scaledGravity);
  60553. // Size
  60554. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  60555. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  60556. if (currentGradient !== particle._currentSizeGradient) {
  60557. particle._currentSize1 = particle._currentSize2;
  60558. particle._currentSize2 = nextGradient.getFactor();
  60559. particle._currentSizeGradient = currentGradient;
  60560. }
  60561. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  60562. });
  60563. }
  60564. // Remap data
  60565. if (_this._useRampGradients) {
  60566. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  60567. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  60568. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60569. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  60570. particle.remapData.x = min;
  60571. particle.remapData.y = max - min;
  60572. });
  60573. }
  60574. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  60575. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  60576. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60577. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  60578. particle.remapData.z = min;
  60579. particle.remapData.w = max - min;
  60580. });
  60581. }
  60582. }
  60583. if (_this._isAnimationSheetEnabled) {
  60584. particle.updateCellIndex();
  60585. }
  60586. // Update the position of the attached sub-emitters to match their attached particle
  60587. particle._inheritParticleInfoToSubEmitters();
  60588. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  60589. _this._emitFromParticle(particle);
  60590. if (particle._attachedSubEmitters) {
  60591. particle._attachedSubEmitters.forEach(function (subEmitter) {
  60592. subEmitter.particleSystem.disposeOnStop = true;
  60593. subEmitter.particleSystem.stop();
  60594. });
  60595. particle._attachedSubEmitters = null;
  60596. }
  60597. _this.recycleParticle(particle);
  60598. index--;
  60599. return "continue";
  60600. }
  60601. };
  60602. var particle;
  60603. for (var index = 0; index < particles.length; index++) {
  60604. _loop_1();
  60605. }
  60606. };
  60607. return _this;
  60608. }
  60609. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  60610. /**
  60611. * Sets a callback that will be triggered when the system is disposed
  60612. */
  60613. set: function (callback) {
  60614. if (this._onDisposeObserver) {
  60615. this.onDisposeObservable.remove(this._onDisposeObserver);
  60616. }
  60617. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  60618. },
  60619. enumerable: true,
  60620. configurable: true
  60621. });
  60622. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  60623. /** Gets or sets a boolean indicating that ramp gradients must be used
  60624. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  60625. */
  60626. get: function () {
  60627. return this._useRampGradients;
  60628. },
  60629. set: function (value) {
  60630. if (this._useRampGradients === value) {
  60631. return;
  60632. }
  60633. this._useRampGradients = value;
  60634. this._resetEffect();
  60635. },
  60636. enumerable: true,
  60637. configurable: true
  60638. });
  60639. Object.defineProperty(ParticleSystem.prototype, "particles", {
  60640. //end of Sub-emitter
  60641. /**
  60642. * Gets the current list of active particles
  60643. */
  60644. get: function () {
  60645. return this._particles;
  60646. },
  60647. enumerable: true,
  60648. configurable: true
  60649. });
  60650. /**
  60651. * Returns the string "ParticleSystem"
  60652. * @returns a string containing the class name
  60653. */
  60654. ParticleSystem.prototype.getClassName = function () {
  60655. return "ParticleSystem";
  60656. };
  60657. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  60658. var newGradient = new BABYLON.FactorGradient();
  60659. newGradient.gradient = gradient;
  60660. newGradient.factor1 = factor;
  60661. newGradient.factor2 = factor2;
  60662. factorGradients.push(newGradient);
  60663. factorGradients.sort(function (a, b) {
  60664. if (a.gradient < b.gradient) {
  60665. return -1;
  60666. }
  60667. else if (a.gradient > b.gradient) {
  60668. return 1;
  60669. }
  60670. return 0;
  60671. });
  60672. };
  60673. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  60674. if (!factorGradients) {
  60675. return;
  60676. }
  60677. var index = 0;
  60678. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  60679. var factorGradient = factorGradients_1[_i];
  60680. if (factorGradient.gradient === gradient) {
  60681. factorGradients.splice(index, 1);
  60682. break;
  60683. }
  60684. index++;
  60685. }
  60686. };
  60687. /**
  60688. * Adds a new life time gradient
  60689. * @param gradient defines the gradient to use (between 0 and 1)
  60690. * @param factor defines the life time factor to affect to the specified gradient
  60691. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60692. * @returns the current particle system
  60693. */
  60694. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  60695. if (!this._lifeTimeGradients) {
  60696. this._lifeTimeGradients = [];
  60697. }
  60698. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  60699. return this;
  60700. };
  60701. /**
  60702. * Remove a specific life time gradient
  60703. * @param gradient defines the gradient to remove
  60704. * @returns the current particle system
  60705. */
  60706. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  60707. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  60708. return this;
  60709. };
  60710. /**
  60711. * Adds a new size gradient
  60712. * @param gradient defines the gradient to use (between 0 and 1)
  60713. * @param factor defines the size factor to affect to the specified gradient
  60714. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60715. * @returns the current particle system
  60716. */
  60717. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  60718. if (!this._sizeGradients) {
  60719. this._sizeGradients = [];
  60720. }
  60721. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  60722. return this;
  60723. };
  60724. /**
  60725. * Remove a specific size gradient
  60726. * @param gradient defines the gradient to remove
  60727. * @returns the current particle system
  60728. */
  60729. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  60730. this._removeFactorGradient(this._sizeGradients, gradient);
  60731. return this;
  60732. };
  60733. /**
  60734. * Adds a new color remap gradient
  60735. * @param gradient defines the gradient to use (between 0 and 1)
  60736. * @param min defines the color remap minimal range
  60737. * @param max defines the color remap maximal range
  60738. * @returns the current particle system
  60739. */
  60740. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  60741. if (!this._colorRemapGradients) {
  60742. this._colorRemapGradients = [];
  60743. }
  60744. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  60745. return this;
  60746. };
  60747. /**
  60748. * Remove a specific color remap gradient
  60749. * @param gradient defines the gradient to remove
  60750. * @returns the current particle system
  60751. */
  60752. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  60753. this._removeFactorGradient(this._colorRemapGradients, gradient);
  60754. return this;
  60755. };
  60756. /**
  60757. * Adds a new alpha remap gradient
  60758. * @param gradient defines the gradient to use (between 0 and 1)
  60759. * @param min defines the alpha remap minimal range
  60760. * @param max defines the alpha remap maximal range
  60761. * @returns the current particle system
  60762. */
  60763. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  60764. if (!this._alphaRemapGradients) {
  60765. this._alphaRemapGradients = [];
  60766. }
  60767. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  60768. return this;
  60769. };
  60770. /**
  60771. * Remove a specific alpha remap gradient
  60772. * @param gradient defines the gradient to remove
  60773. * @returns the current particle system
  60774. */
  60775. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  60776. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  60777. return this;
  60778. };
  60779. /**
  60780. * Adds a new angular speed gradient
  60781. * @param gradient defines the gradient to use (between 0 and 1)
  60782. * @param factor defines the angular speed to affect to the specified gradient
  60783. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60784. * @returns the current particle system
  60785. */
  60786. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  60787. if (!this._angularSpeedGradients) {
  60788. this._angularSpeedGradients = [];
  60789. }
  60790. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  60791. return this;
  60792. };
  60793. /**
  60794. * Remove a specific angular speed gradient
  60795. * @param gradient defines the gradient to remove
  60796. * @returns the current particle system
  60797. */
  60798. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  60799. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  60800. return this;
  60801. };
  60802. /**
  60803. * Adds a new velocity gradient
  60804. * @param gradient defines the gradient to use (between 0 and 1)
  60805. * @param factor defines the velocity to affect to the specified gradient
  60806. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60807. * @returns the current particle system
  60808. */
  60809. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  60810. if (!this._velocityGradients) {
  60811. this._velocityGradients = [];
  60812. }
  60813. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  60814. return this;
  60815. };
  60816. /**
  60817. * Remove a specific velocity gradient
  60818. * @param gradient defines the gradient to remove
  60819. * @returns the current particle system
  60820. */
  60821. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60822. this._removeFactorGradient(this._velocityGradients, gradient);
  60823. return this;
  60824. };
  60825. /**
  60826. * Adds a new limit velocity gradient
  60827. * @param gradient defines the gradient to use (between 0 and 1)
  60828. * @param factor defines the limit velocity value to affect to the specified gradient
  60829. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60830. * @returns the current particle system
  60831. */
  60832. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  60833. if (!this._limitVelocityGradients) {
  60834. this._limitVelocityGradients = [];
  60835. }
  60836. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  60837. return this;
  60838. };
  60839. /**
  60840. * Remove a specific limit velocity gradient
  60841. * @param gradient defines the gradient to remove
  60842. * @returns the current particle system
  60843. */
  60844. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  60845. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  60846. return this;
  60847. };
  60848. /**
  60849. * Adds a new drag gradient
  60850. * @param gradient defines the gradient to use (between 0 and 1)
  60851. * @param factor defines the drag value to affect to the specified gradient
  60852. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60853. * @returns the current particle system
  60854. */
  60855. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  60856. if (!this._dragGradients) {
  60857. this._dragGradients = [];
  60858. }
  60859. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  60860. return this;
  60861. };
  60862. /**
  60863. * Remove a specific drag gradient
  60864. * @param gradient defines the gradient to remove
  60865. * @returns the current particle system
  60866. */
  60867. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  60868. this._removeFactorGradient(this._dragGradients, gradient);
  60869. return this;
  60870. };
  60871. /**
  60872. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  60873. * @param gradient defines the gradient to use (between 0 and 1)
  60874. * @param factor defines the emit rate value to affect to the specified gradient
  60875. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60876. * @returns the current particle system
  60877. */
  60878. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  60879. if (!this._emitRateGradients) {
  60880. this._emitRateGradients = [];
  60881. }
  60882. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  60883. return this;
  60884. };
  60885. /**
  60886. * Remove a specific emit rate gradient
  60887. * @param gradient defines the gradient to remove
  60888. * @returns the current particle system
  60889. */
  60890. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  60891. this._removeFactorGradient(this._emitRateGradients, gradient);
  60892. return this;
  60893. };
  60894. /**
  60895. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  60896. * @param gradient defines the gradient to use (between 0 and 1)
  60897. * @param factor defines the start size value to affect to the specified gradient
  60898. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60899. * @returns the current particle system
  60900. */
  60901. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  60902. if (!this._startSizeGradients) {
  60903. this._startSizeGradients = [];
  60904. }
  60905. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  60906. return this;
  60907. };
  60908. /**
  60909. * Remove a specific start size gradient
  60910. * @param gradient defines the gradient to remove
  60911. * @returns the current particle system
  60912. */
  60913. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  60914. this._removeFactorGradient(this._emitRateGradients, gradient);
  60915. return this;
  60916. };
  60917. ParticleSystem.prototype._createRampGradientTexture = function () {
  60918. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  60919. return;
  60920. }
  60921. var data = new Uint8Array(this._rawTextureWidth * 4);
  60922. var tmpColor = BABYLON.Tmp.Color3[0];
  60923. for (var x = 0; x < this._rawTextureWidth; x++) {
  60924. var ratio = x / this._rawTextureWidth;
  60925. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  60926. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  60927. data[x * 4] = tmpColor.r * 255;
  60928. data[x * 4 + 1] = tmpColor.g * 255;
  60929. data[x * 4 + 2] = tmpColor.b * 255;
  60930. data[x * 4 + 3] = 255;
  60931. });
  60932. }
  60933. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60934. };
  60935. /**
  60936. * Gets the current list of ramp gradients.
  60937. * You must use addRampGradient and removeRampGradient to udpate this list
  60938. * @returns the list of ramp gradients
  60939. */
  60940. ParticleSystem.prototype.getRampGradients = function () {
  60941. return this._rampGradients;
  60942. };
  60943. /**
  60944. * Adds a new ramp gradient used to remap particle colors
  60945. * @param gradient defines the gradient to use (between 0 and 1)
  60946. * @param color defines the color to affect to the specified gradient
  60947. * @returns the current particle system
  60948. */
  60949. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  60950. if (!this._rampGradients) {
  60951. this._rampGradients = [];
  60952. }
  60953. var rampGradient = new BABYLON.Color3Gradient();
  60954. rampGradient.gradient = gradient;
  60955. rampGradient.color = color;
  60956. this._rampGradients.push(rampGradient);
  60957. this._rampGradients.sort(function (a, b) {
  60958. if (a.gradient < b.gradient) {
  60959. return -1;
  60960. }
  60961. else if (a.gradient > b.gradient) {
  60962. return 1;
  60963. }
  60964. return 0;
  60965. });
  60966. if (this._rampGradientsTexture) {
  60967. this._rampGradientsTexture.dispose();
  60968. this._rampGradientsTexture = null;
  60969. }
  60970. this._createRampGradientTexture();
  60971. return this;
  60972. };
  60973. /**
  60974. * Remove a specific ramp gradient
  60975. * @param gradient defines the gradient to remove
  60976. * @returns the current particle system
  60977. */
  60978. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  60979. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  60980. this._rampGradientsTexture = null;
  60981. if (this._rampGradients && this._rampGradients.length > 0) {
  60982. this._createRampGradientTexture();
  60983. }
  60984. return this;
  60985. };
  60986. /**
  60987. * Adds a new color gradient
  60988. * @param gradient defines the gradient to use (between 0 and 1)
  60989. * @param color1 defines the color to affect to the specified gradient
  60990. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  60991. * @returns this particle system
  60992. */
  60993. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  60994. if (!this._colorGradients) {
  60995. this._colorGradients = [];
  60996. }
  60997. var colorGradient = new BABYLON.ColorGradient();
  60998. colorGradient.gradient = gradient;
  60999. colorGradient.color1 = color1;
  61000. colorGradient.color2 = color2;
  61001. this._colorGradients.push(colorGradient);
  61002. this._colorGradients.sort(function (a, b) {
  61003. if (a.gradient < b.gradient) {
  61004. return -1;
  61005. }
  61006. else if (a.gradient > b.gradient) {
  61007. return 1;
  61008. }
  61009. return 0;
  61010. });
  61011. return this;
  61012. };
  61013. /**
  61014. * Remove a specific color gradient
  61015. * @param gradient defines the gradient to remove
  61016. * @returns this particle system
  61017. */
  61018. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  61019. if (!this._colorGradients) {
  61020. return this;
  61021. }
  61022. var index = 0;
  61023. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  61024. var colorGradient = _a[_i];
  61025. if (colorGradient.gradient === gradient) {
  61026. this._colorGradients.splice(index, 1);
  61027. break;
  61028. }
  61029. index++;
  61030. }
  61031. return this;
  61032. };
  61033. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  61034. u = Math.abs(u) * 0.5 + 0.5;
  61035. v = Math.abs(v) * 0.5 + 0.5;
  61036. var wrappedU = ((u * width) % width) | 0;
  61037. var wrappedV = ((v * height) % height) | 0;
  61038. var position = (wrappedU + wrappedV * width) * 4;
  61039. return pixels[position] / 255;
  61040. };
  61041. ParticleSystem.prototype._reset = function () {
  61042. this._resetEffect();
  61043. };
  61044. ParticleSystem.prototype._resetEffect = function () {
  61045. if (this._vertexBuffer) {
  61046. this._vertexBuffer.dispose();
  61047. this._vertexBuffer = null;
  61048. }
  61049. if (this._spriteBuffer) {
  61050. this._spriteBuffer.dispose();
  61051. this._spriteBuffer = null;
  61052. }
  61053. this._createVertexBuffers();
  61054. };
  61055. ParticleSystem.prototype._createVertexBuffers = function () {
  61056. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  61057. if (this._isAnimationSheetEnabled) {
  61058. this._vertexBufferSize += 1;
  61059. }
  61060. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61061. this._vertexBufferSize += 3;
  61062. }
  61063. if (this._useRampGradients) {
  61064. this._vertexBufferSize += 4;
  61065. }
  61066. var engine = this._scene.getEngine();
  61067. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  61068. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  61069. var dataOffset = 0;
  61070. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  61071. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  61072. dataOffset += 3;
  61073. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  61074. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  61075. dataOffset += 4;
  61076. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  61077. this._vertexBuffers["angle"] = options;
  61078. dataOffset += 1;
  61079. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  61080. this._vertexBuffers["size"] = size;
  61081. dataOffset += 2;
  61082. if (this._isAnimationSheetEnabled) {
  61083. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  61084. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  61085. dataOffset += 1;
  61086. }
  61087. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61088. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  61089. this._vertexBuffers["direction"] = directionBuffer;
  61090. dataOffset += 3;
  61091. }
  61092. if (this._useRampGradients) {
  61093. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  61094. this._vertexBuffers["remapData"] = rampDataBuffer;
  61095. dataOffset += 4;
  61096. }
  61097. var offsets;
  61098. if (this._useInstancing) {
  61099. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  61100. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  61101. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  61102. }
  61103. else {
  61104. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  61105. dataOffset += 2;
  61106. }
  61107. this._vertexBuffers["offset"] = offsets;
  61108. };
  61109. ParticleSystem.prototype._createIndexBuffer = function () {
  61110. if (this._useInstancing) {
  61111. return;
  61112. }
  61113. var indices = [];
  61114. var index = 0;
  61115. for (var count = 0; count < this._capacity; count++) {
  61116. indices.push(index);
  61117. indices.push(index + 1);
  61118. indices.push(index + 2);
  61119. indices.push(index);
  61120. indices.push(index + 2);
  61121. indices.push(index + 3);
  61122. index += 4;
  61123. }
  61124. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  61125. };
  61126. /**
  61127. * Gets the maximum number of particles active at the same time.
  61128. * @returns The max number of active particles.
  61129. */
  61130. ParticleSystem.prototype.getCapacity = function () {
  61131. return this._capacity;
  61132. };
  61133. /**
  61134. * Gets whether there are still active particles in the system.
  61135. * @returns True if it is alive, otherwise false.
  61136. */
  61137. ParticleSystem.prototype.isAlive = function () {
  61138. return this._alive;
  61139. };
  61140. /**
  61141. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61142. * @returns True if it has been started, otherwise false.
  61143. */
  61144. ParticleSystem.prototype.isStarted = function () {
  61145. return this._started;
  61146. };
  61147. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  61148. var _this = this;
  61149. this._subEmitters = new Array();
  61150. if (this.subEmitters) {
  61151. this.subEmitters.forEach(function (subEmitter) {
  61152. if (subEmitter instanceof ParticleSystem) {
  61153. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  61154. }
  61155. else if (subEmitter instanceof BABYLON.SubEmitter) {
  61156. _this._subEmitters.push([subEmitter]);
  61157. }
  61158. else if (subEmitter instanceof Array) {
  61159. _this._subEmitters.push(subEmitter);
  61160. }
  61161. });
  61162. }
  61163. };
  61164. /**
  61165. * Starts the particle system and begins to emit
  61166. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  61167. */
  61168. ParticleSystem.prototype.start = function (delay) {
  61169. var _this = this;
  61170. if (delay === void 0) { delay = this.startDelay; }
  61171. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  61172. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  61173. }
  61174. if (delay) {
  61175. setTimeout(function () {
  61176. _this.start(0);
  61177. }, delay);
  61178. return;
  61179. }
  61180. // Convert the subEmitters field to the constant type field _subEmitters
  61181. this._prepareSubEmitterInternalArray();
  61182. this._started = true;
  61183. this._stopped = false;
  61184. this._actualFrame = 0;
  61185. if (this._subEmitters && this._subEmitters.length != 0) {
  61186. this.activeSubSystems = new Array();
  61187. }
  61188. // Reset emit gradient so it acts the same on every start
  61189. if (this._emitRateGradients) {
  61190. if (this._emitRateGradients.length > 0) {
  61191. this._currentEmitRateGradient = this._emitRateGradients[0];
  61192. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  61193. this._currentEmitRate2 = this._currentEmitRate1;
  61194. }
  61195. if (this._emitRateGradients.length > 1) {
  61196. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  61197. }
  61198. }
  61199. // Reset start size gradient so it acts the same on every start
  61200. if (this._startSizeGradients) {
  61201. if (this._startSizeGradients.length > 0) {
  61202. this._currentStartSizeGradient = this._startSizeGradients[0];
  61203. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  61204. this._currentStartSize2 = this._currentStartSize1;
  61205. }
  61206. if (this._startSizeGradients.length > 1) {
  61207. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  61208. }
  61209. }
  61210. if (this.preWarmCycles) {
  61211. if (this.emitter instanceof BABYLON.AbstractMesh) {
  61212. this.emitter.computeWorldMatrix(true);
  61213. }
  61214. var noiseTextureAsProcedural_1 = this.noiseTexture;
  61215. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  61216. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  61217. setTimeout(function () {
  61218. for (var index = 0; index < _this.preWarmCycles; index++) {
  61219. _this.animate(true);
  61220. noiseTextureAsProcedural_1.render();
  61221. }
  61222. });
  61223. });
  61224. }
  61225. else {
  61226. for (var index = 0; index < this.preWarmCycles; index++) {
  61227. this.animate(true);
  61228. }
  61229. }
  61230. }
  61231. // Animations
  61232. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  61233. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  61234. }
  61235. };
  61236. /**
  61237. * Stops the particle system.
  61238. * @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.
  61239. */
  61240. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  61241. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  61242. this._stopped = true;
  61243. if (stopSubEmitters) {
  61244. this._stopSubEmitters();
  61245. }
  61246. };
  61247. // animation sheet
  61248. /**
  61249. * Remove all active particles
  61250. */
  61251. ParticleSystem.prototype.reset = function () {
  61252. this._stockParticles = [];
  61253. this._particles = [];
  61254. };
  61255. /**
  61256. * @hidden (for internal use only)
  61257. */
  61258. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  61259. var offset = index * this._vertexBufferSize;
  61260. this._vertexData[offset++] = particle.position.x;
  61261. this._vertexData[offset++] = particle.position.y;
  61262. this._vertexData[offset++] = particle.position.z;
  61263. this._vertexData[offset++] = particle.color.r;
  61264. this._vertexData[offset++] = particle.color.g;
  61265. this._vertexData[offset++] = particle.color.b;
  61266. this._vertexData[offset++] = particle.color.a;
  61267. this._vertexData[offset++] = particle.angle;
  61268. this._vertexData[offset++] = particle.scale.x * particle.size;
  61269. this._vertexData[offset++] = particle.scale.y * particle.size;
  61270. if (this._isAnimationSheetEnabled) {
  61271. this._vertexData[offset++] = particle.cellIndex;
  61272. }
  61273. if (!this._isBillboardBased) {
  61274. if (particle._initialDirection) {
  61275. this._vertexData[offset++] = particle._initialDirection.x;
  61276. this._vertexData[offset++] = particle._initialDirection.y;
  61277. this._vertexData[offset++] = particle._initialDirection.z;
  61278. }
  61279. else {
  61280. this._vertexData[offset++] = particle.direction.x;
  61281. this._vertexData[offset++] = particle.direction.y;
  61282. this._vertexData[offset++] = particle.direction.z;
  61283. }
  61284. }
  61285. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61286. this._vertexData[offset++] = particle.direction.x;
  61287. this._vertexData[offset++] = particle.direction.y;
  61288. this._vertexData[offset++] = particle.direction.z;
  61289. }
  61290. if (this._useRampGradients) {
  61291. this._vertexData[offset++] = particle.remapData.x;
  61292. this._vertexData[offset++] = particle.remapData.y;
  61293. this._vertexData[offset++] = particle.remapData.z;
  61294. this._vertexData[offset++] = particle.remapData.w;
  61295. }
  61296. if (!this._useInstancing) {
  61297. if (this._isAnimationSheetEnabled) {
  61298. if (offsetX === 0) {
  61299. offsetX = this._epsilon;
  61300. }
  61301. else if (offsetX === 1) {
  61302. offsetX = 1 - this._epsilon;
  61303. }
  61304. if (offsetY === 0) {
  61305. offsetY = this._epsilon;
  61306. }
  61307. else if (offsetY === 1) {
  61308. offsetY = 1 - this._epsilon;
  61309. }
  61310. }
  61311. this._vertexData[offset++] = offsetX;
  61312. this._vertexData[offset++] = offsetY;
  61313. }
  61314. };
  61315. ParticleSystem.prototype._stopSubEmitters = function () {
  61316. if (!this.activeSubSystems) {
  61317. return;
  61318. }
  61319. this.activeSubSystems.forEach(function (subSystem) {
  61320. subSystem.stop(true);
  61321. });
  61322. this.activeSubSystems = new Array();
  61323. };
  61324. ParticleSystem.prototype._removeFromRoot = function () {
  61325. if (!this._rootParticleSystem) {
  61326. return;
  61327. }
  61328. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  61329. if (index !== -1) {
  61330. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  61331. }
  61332. this._rootParticleSystem = null;
  61333. };
  61334. // End of sub system methods
  61335. ParticleSystem.prototype._update = function (newParticles) {
  61336. var _this = this;
  61337. // Update current
  61338. this._alive = this._particles.length > 0;
  61339. if (this.emitter.position) {
  61340. var emitterMesh = this.emitter;
  61341. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  61342. }
  61343. else {
  61344. var emitterPosition = this.emitter;
  61345. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  61346. }
  61347. this.updateFunction(this._particles);
  61348. // Add new ones
  61349. var particle;
  61350. var _loop_2 = function () {
  61351. if (this_1._particles.length === this_1._capacity) {
  61352. return "break";
  61353. }
  61354. particle = this_1._createParticle();
  61355. this_1._particles.push(particle);
  61356. // Emitter
  61357. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  61358. if (this_1.startPositionFunction) {
  61359. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  61360. }
  61361. else {
  61362. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  61363. }
  61364. if (this_1.startDirectionFunction) {
  61365. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  61366. }
  61367. else {
  61368. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  61369. }
  61370. if (emitPower === 0) {
  61371. if (!particle._initialDirection) {
  61372. particle._initialDirection = particle.direction.clone();
  61373. }
  61374. else {
  61375. particle._initialDirection.copyFrom(particle.direction);
  61376. }
  61377. }
  61378. else {
  61379. particle._initialDirection = null;
  61380. }
  61381. particle.direction.scaleInPlace(emitPower);
  61382. // Life time
  61383. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  61384. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  61385. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  61386. var factorGradient1 = currentGradient;
  61387. var factorGradient2 = nextGradient;
  61388. var lifeTime1 = factorGradient1.getFactor();
  61389. var lifeTime2 = factorGradient2.getFactor();
  61390. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  61391. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  61392. });
  61393. }
  61394. else {
  61395. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  61396. }
  61397. // Size
  61398. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  61399. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  61400. }
  61401. else {
  61402. particle._currentSizeGradient = this_1._sizeGradients[0];
  61403. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  61404. particle.size = particle._currentSize1;
  61405. if (this_1._sizeGradients.length > 1) {
  61406. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  61407. }
  61408. else {
  61409. particle._currentSize2 = particle._currentSize1;
  61410. }
  61411. }
  61412. // Size and scale
  61413. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  61414. // Adjust scale by start size
  61415. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  61416. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  61417. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  61418. if (currentGradient !== _this._currentStartSizeGradient) {
  61419. _this._currentStartSize1 = _this._currentStartSize2;
  61420. _this._currentStartSize2 = nextGradient.getFactor();
  61421. _this._currentStartSizeGradient = currentGradient;
  61422. }
  61423. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  61424. particle.scale.scaleInPlace(value);
  61425. });
  61426. }
  61427. // Angle
  61428. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  61429. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  61430. }
  61431. else {
  61432. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  61433. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  61434. particle._currentAngularSpeed1 = particle.angularSpeed;
  61435. if (this_1._angularSpeedGradients.length > 1) {
  61436. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  61437. }
  61438. else {
  61439. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  61440. }
  61441. }
  61442. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  61443. // Velocity
  61444. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  61445. particle._currentVelocityGradient = this_1._velocityGradients[0];
  61446. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  61447. if (this_1._velocityGradients.length > 1) {
  61448. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  61449. }
  61450. else {
  61451. particle._currentVelocity2 = particle._currentVelocity1;
  61452. }
  61453. }
  61454. // Limit velocity
  61455. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  61456. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  61457. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  61458. if (this_1._limitVelocityGradients.length > 1) {
  61459. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  61460. }
  61461. else {
  61462. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  61463. }
  61464. }
  61465. // Drag
  61466. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  61467. particle._currentDragGradient = this_1._dragGradients[0];
  61468. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  61469. if (this_1._dragGradients.length > 1) {
  61470. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  61471. }
  61472. else {
  61473. particle._currentDrag2 = particle._currentDrag1;
  61474. }
  61475. }
  61476. // Color
  61477. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  61478. step = BABYLON.Scalar.RandomRange(0, 1.0);
  61479. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  61480. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  61481. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  61482. }
  61483. else {
  61484. particle._currentColorGradient = this_1._colorGradients[0];
  61485. particle._currentColorGradient.getColorToRef(particle.color);
  61486. particle._currentColor1.copyFrom(particle.color);
  61487. if (this_1._colorGradients.length > 1) {
  61488. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  61489. }
  61490. else {
  61491. particle._currentColor2.copyFrom(particle.color);
  61492. }
  61493. }
  61494. // Sheet
  61495. if (this_1._isAnimationSheetEnabled) {
  61496. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  61497. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  61498. }
  61499. // Inherited Velocity
  61500. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  61501. // Ramp
  61502. if (this_1._useRampGradients) {
  61503. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  61504. }
  61505. // Noise texture coordinates
  61506. if (this_1.noiseTexture) {
  61507. if (particle._randomNoiseCoordinates1) {
  61508. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  61509. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  61510. }
  61511. else {
  61512. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  61513. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  61514. }
  61515. }
  61516. // Update the position of the attached sub-emitters to match their attached particle
  61517. particle._inheritParticleInfoToSubEmitters();
  61518. };
  61519. var this_1 = this, step;
  61520. for (var index = 0; index < newParticles; index++) {
  61521. var state_1 = _loop_2();
  61522. if (state_1 === "break")
  61523. break;
  61524. }
  61525. };
  61526. /** @hidden */
  61527. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  61528. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61529. if (isBillboardBased === void 0) { isBillboardBased = false; }
  61530. if (useRampGradients === void 0) { useRampGradients = false; }
  61531. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  61532. if (isAnimationSheetEnabled) {
  61533. attributeNamesOrOptions.push("cellIndex");
  61534. }
  61535. if (!isBillboardBased) {
  61536. attributeNamesOrOptions.push("direction");
  61537. }
  61538. if (useRampGradients) {
  61539. attributeNamesOrOptions.push("remapData");
  61540. }
  61541. return attributeNamesOrOptions;
  61542. };
  61543. /** @hidden */
  61544. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  61545. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61546. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  61547. if (isAnimationSheetEnabled) {
  61548. effectCreationOption.push("particlesInfos");
  61549. }
  61550. return effectCreationOption;
  61551. };
  61552. /** @hidden */
  61553. ParticleSystem.prototype._getEffect = function (blendMode) {
  61554. if (this._customEffect) {
  61555. return this._customEffect;
  61556. }
  61557. var defines = [];
  61558. if (this._scene.clipPlane) {
  61559. defines.push("#define CLIPPLANE");
  61560. }
  61561. if (this._scene.clipPlane2) {
  61562. defines.push("#define CLIPPLANE2");
  61563. }
  61564. if (this._scene.clipPlane3) {
  61565. defines.push("#define CLIPPLANE3");
  61566. }
  61567. if (this._scene.clipPlane4) {
  61568. defines.push("#define CLIPPLANE4");
  61569. }
  61570. if (this._isAnimationSheetEnabled) {
  61571. defines.push("#define ANIMATESHEET");
  61572. }
  61573. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  61574. defines.push("#define BLENDMULTIPLYMODE");
  61575. }
  61576. if (this._useRampGradients) {
  61577. defines.push("#define RAMPGRADIENT");
  61578. }
  61579. if (this._isBillboardBased) {
  61580. defines.push("#define BILLBOARD");
  61581. switch (this.billboardMode) {
  61582. case ParticleSystem.BILLBOARDMODE_Y:
  61583. defines.push("#define BILLBOARDY");
  61584. break;
  61585. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  61586. defines.push("#define BILLBOARDSTRETCHED");
  61587. break;
  61588. case ParticleSystem.BILLBOARDMODE_ALL:
  61589. default:
  61590. break;
  61591. }
  61592. }
  61593. if (this._imageProcessingConfiguration) {
  61594. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  61595. defines.push(this._imageProcessingConfigurationDefines.toString());
  61596. }
  61597. // Effect
  61598. var join = defines.join("\n");
  61599. if (this._cachedDefines !== join) {
  61600. this._cachedDefines = join;
  61601. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  61602. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  61603. var samplers = ["diffuseSampler", "rampSampler"];
  61604. if (BABYLON.ImageProcessingConfiguration) {
  61605. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  61606. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  61607. }
  61608. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  61609. }
  61610. return this._effect;
  61611. };
  61612. /**
  61613. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  61614. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  61615. */
  61616. ParticleSystem.prototype.animate = function (preWarmOnly) {
  61617. var _this = this;
  61618. if (preWarmOnly === void 0) { preWarmOnly = false; }
  61619. if (!this._started) {
  61620. return;
  61621. }
  61622. if (!preWarmOnly) {
  61623. // Check
  61624. if (!this.isReady()) {
  61625. return;
  61626. }
  61627. if (this._currentRenderId === this._scene.getFrameId()) {
  61628. return;
  61629. }
  61630. this._currentRenderId = this._scene.getFrameId();
  61631. }
  61632. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  61633. // Determine the number of particles we need to create
  61634. var newParticles;
  61635. if (this.manualEmitCount > -1) {
  61636. newParticles = this.manualEmitCount;
  61637. this._newPartsExcess = 0;
  61638. this.manualEmitCount = 0;
  61639. }
  61640. else {
  61641. var rate_1 = this.emitRate;
  61642. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  61643. var ratio = this._actualFrame / this.targetStopDuration;
  61644. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  61645. if (currentGradient !== _this._currentEmitRateGradient) {
  61646. _this._currentEmitRate1 = _this._currentEmitRate2;
  61647. _this._currentEmitRate2 = nextGradient.getFactor();
  61648. _this._currentEmitRateGradient = currentGradient;
  61649. }
  61650. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  61651. });
  61652. }
  61653. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  61654. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  61655. }
  61656. if (this._newPartsExcess > 1.0) {
  61657. newParticles += this._newPartsExcess >> 0;
  61658. this._newPartsExcess -= this._newPartsExcess >> 0;
  61659. }
  61660. this._alive = false;
  61661. if (!this._stopped) {
  61662. this._actualFrame += this._scaledUpdateSpeed;
  61663. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  61664. this.stop();
  61665. }
  61666. }
  61667. else {
  61668. newParticles = 0;
  61669. }
  61670. this._update(newParticles);
  61671. // Stopped?
  61672. if (this._stopped) {
  61673. if (!this._alive) {
  61674. this._started = false;
  61675. if (this.onAnimationEnd) {
  61676. this.onAnimationEnd();
  61677. }
  61678. if (this.disposeOnStop) {
  61679. this._scene._toBeDisposed.push(this);
  61680. }
  61681. }
  61682. }
  61683. if (!preWarmOnly) {
  61684. // Update VBO
  61685. var offset = 0;
  61686. for (var index = 0; index < this._particles.length; index++) {
  61687. var particle = this._particles[index];
  61688. this._appendParticleVertices(offset, particle);
  61689. offset += this._useInstancing ? 1 : 4;
  61690. }
  61691. if (this._vertexBuffer) {
  61692. this._vertexBuffer.update(this._vertexData);
  61693. }
  61694. }
  61695. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  61696. this.stop();
  61697. }
  61698. };
  61699. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  61700. this._appendParticleVertex(offset++, particle, 0, 0);
  61701. if (!this._useInstancing) {
  61702. this._appendParticleVertex(offset++, particle, 1, 0);
  61703. this._appendParticleVertex(offset++, particle, 1, 1);
  61704. this._appendParticleVertex(offset++, particle, 0, 1);
  61705. }
  61706. };
  61707. /**
  61708. * Rebuilds the particle system.
  61709. */
  61710. ParticleSystem.prototype.rebuild = function () {
  61711. this._createIndexBuffer();
  61712. if (this._vertexBuffer) {
  61713. this._vertexBuffer._rebuild();
  61714. }
  61715. };
  61716. /**
  61717. * Is this system ready to be used/rendered
  61718. * @return true if the system is ready
  61719. */
  61720. ParticleSystem.prototype.isReady = function () {
  61721. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61722. return false;
  61723. }
  61724. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  61725. if (!this._getEffect(this.blendMode).isReady()) {
  61726. return false;
  61727. }
  61728. }
  61729. else {
  61730. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  61731. return false;
  61732. }
  61733. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  61734. return false;
  61735. }
  61736. }
  61737. return true;
  61738. };
  61739. ParticleSystem.prototype._render = function (blendMode) {
  61740. var effect = this._getEffect(blendMode);
  61741. var engine = this._scene.getEngine();
  61742. // Render
  61743. engine.enableEffect(effect);
  61744. var viewMatrix = this._scene.getViewMatrix();
  61745. effect.setTexture("diffuseSampler", this.particleTexture);
  61746. effect.setMatrix("view", viewMatrix);
  61747. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  61748. if (this._isAnimationSheetEnabled && this.particleTexture) {
  61749. var baseSize = this.particleTexture.getBaseSize();
  61750. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  61751. }
  61752. effect.setVector2("translationPivot", this.translationPivot);
  61753. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  61754. if (this._isBillboardBased) {
  61755. var camera = this._scene.activeCamera;
  61756. effect.setVector3("eyePosition", camera.globalPosition);
  61757. }
  61758. if (this._rampGradientsTexture) {
  61759. effect.setTexture("rampSampler", this._rampGradientsTexture);
  61760. }
  61761. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  61762. var invView = viewMatrix.clone();
  61763. invView.invert();
  61764. effect.setMatrix("invView", invView);
  61765. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  61766. }
  61767. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  61768. // image processing
  61769. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  61770. this._imageProcessingConfiguration.bind(effect);
  61771. }
  61772. // Draw order
  61773. switch (blendMode) {
  61774. case ParticleSystem.BLENDMODE_ADD:
  61775. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  61776. break;
  61777. case ParticleSystem.BLENDMODE_ONEONE:
  61778. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  61779. break;
  61780. case ParticleSystem.BLENDMODE_STANDARD:
  61781. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61782. break;
  61783. case ParticleSystem.BLENDMODE_MULTIPLY:
  61784. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  61785. break;
  61786. }
  61787. if (this._useInstancing) {
  61788. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  61789. }
  61790. else {
  61791. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  61792. }
  61793. return this._particles.length;
  61794. };
  61795. /**
  61796. * Renders the particle system in its current state.
  61797. * @returns the current number of particles
  61798. */
  61799. ParticleSystem.prototype.render = function () {
  61800. // Check
  61801. if (!this.isReady() || !this._particles.length) {
  61802. return 0;
  61803. }
  61804. var engine = this._scene.getEngine();
  61805. engine.setState(false);
  61806. if (this.forceDepthWrite) {
  61807. engine.setDepthWrite(true);
  61808. }
  61809. var outparticles = 0;
  61810. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  61811. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  61812. }
  61813. outparticles = this._render(this.blendMode);
  61814. engine.unbindInstanceAttributes();
  61815. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61816. return outparticles;
  61817. };
  61818. /**
  61819. * Disposes the particle system and free the associated resources
  61820. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  61821. */
  61822. ParticleSystem.prototype.dispose = function (disposeTexture) {
  61823. if (disposeTexture === void 0) { disposeTexture = true; }
  61824. if (this._vertexBuffer) {
  61825. this._vertexBuffer.dispose();
  61826. this._vertexBuffer = null;
  61827. }
  61828. if (this._spriteBuffer) {
  61829. this._spriteBuffer.dispose();
  61830. this._spriteBuffer = null;
  61831. }
  61832. if (this._indexBuffer) {
  61833. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61834. this._indexBuffer = null;
  61835. }
  61836. if (disposeTexture && this.particleTexture) {
  61837. this.particleTexture.dispose();
  61838. this.particleTexture = null;
  61839. }
  61840. if (disposeTexture && this.noiseTexture) {
  61841. this.noiseTexture.dispose();
  61842. this.noiseTexture = null;
  61843. }
  61844. if (this._rampGradientsTexture) {
  61845. this._rampGradientsTexture.dispose();
  61846. this._rampGradientsTexture = null;
  61847. }
  61848. this._removeFromRoot();
  61849. if (this._subEmitters && this._subEmitters.length) {
  61850. for (var index = 0; index < this._subEmitters.length; index++) {
  61851. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  61852. var subEmitter = _a[_i];
  61853. subEmitter.dispose();
  61854. }
  61855. }
  61856. this._subEmitters = [];
  61857. this.subEmitters = [];
  61858. }
  61859. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  61860. this.emitter.dispose(true);
  61861. }
  61862. // Remove from scene
  61863. var index = this._scene.particleSystems.indexOf(this);
  61864. if (index > -1) {
  61865. this._scene.particleSystems.splice(index, 1);
  61866. }
  61867. this._scene._activeParticleSystems.dispose();
  61868. // Callback
  61869. this.onDisposeObservable.notifyObservers(this);
  61870. this.onDisposeObservable.clear();
  61871. this.reset();
  61872. };
  61873. // Clone
  61874. /**
  61875. * Clones the particle system.
  61876. * @param name The name of the cloned object
  61877. * @param newEmitter The new emitter to use
  61878. * @returns the cloned particle system
  61879. */
  61880. ParticleSystem.prototype.clone = function (name, newEmitter) {
  61881. var custom = null;
  61882. var program = null;
  61883. if (this.customShader != null) {
  61884. program = this.customShader;
  61885. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  61886. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  61887. }
  61888. else if (this._customEffect) {
  61889. custom = this._customEffect;
  61890. }
  61891. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  61892. result.customShader = program;
  61893. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  61894. if (newEmitter === undefined) {
  61895. newEmitter = this.emitter;
  61896. }
  61897. result.noiseTexture = this.noiseTexture;
  61898. result.emitter = newEmitter;
  61899. if (this.particleTexture) {
  61900. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  61901. }
  61902. // Clone gradients
  61903. if (this._colorGradients) {
  61904. this._colorGradients.forEach(function (v) {
  61905. result.addColorGradient(v.gradient, v.color1, v.color2);
  61906. });
  61907. }
  61908. if (this._dragGradients) {
  61909. this._dragGradients.forEach(function (v) {
  61910. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  61911. });
  61912. }
  61913. if (this._angularSpeedGradients) {
  61914. this._angularSpeedGradients.forEach(function (v) {
  61915. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  61916. });
  61917. }
  61918. if (this._emitRateGradients) {
  61919. this._emitRateGradients.forEach(function (v) {
  61920. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  61921. });
  61922. }
  61923. if (this._lifeTimeGradients) {
  61924. this._lifeTimeGradients.forEach(function (v) {
  61925. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  61926. });
  61927. }
  61928. if (this._limitVelocityGradients) {
  61929. this._limitVelocityGradients.forEach(function (v) {
  61930. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  61931. });
  61932. }
  61933. if (this._sizeGradients) {
  61934. this._sizeGradients.forEach(function (v) {
  61935. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  61936. });
  61937. }
  61938. if (this._startSizeGradients) {
  61939. this._startSizeGradients.forEach(function (v) {
  61940. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  61941. });
  61942. }
  61943. if (this._velocityGradients) {
  61944. this._velocityGradients.forEach(function (v) {
  61945. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  61946. });
  61947. }
  61948. if (this._rampGradients) {
  61949. this._rampGradients.forEach(function (v) {
  61950. result.addRampGradient(v.gradient, v.color);
  61951. });
  61952. }
  61953. if (this._colorRemapGradients) {
  61954. this._colorRemapGradients.forEach(function (v) {
  61955. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  61956. });
  61957. }
  61958. if (this._alphaRemapGradients) {
  61959. this._alphaRemapGradients.forEach(function (v) {
  61960. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  61961. });
  61962. }
  61963. if (!this.preventAutoStart) {
  61964. result.start();
  61965. }
  61966. return result;
  61967. };
  61968. /**
  61969. * Serializes the particle system to a JSON object.
  61970. * @returns the JSON object
  61971. */
  61972. ParticleSystem.prototype.serialize = function () {
  61973. var serializationObject = {};
  61974. ParticleSystem._Serialize(serializationObject, this);
  61975. serializationObject.textureMask = this.textureMask.asArray();
  61976. serializationObject.customShader = this.customShader;
  61977. serializationObject.preventAutoStart = this.preventAutoStart;
  61978. // SubEmitters
  61979. if (this.subEmitters) {
  61980. serializationObject.subEmitters = [];
  61981. if (!this._subEmitters) {
  61982. this._prepareSubEmitterInternalArray();
  61983. }
  61984. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  61985. var subs = _a[_i];
  61986. var cell = [];
  61987. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  61988. var sub = subs_1[_b];
  61989. cell.push(sub.serialize());
  61990. }
  61991. serializationObject.subEmitters.push(cell);
  61992. }
  61993. }
  61994. return serializationObject;
  61995. };
  61996. /** @hidden */
  61997. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  61998. serializationObject.name = particleSystem.name;
  61999. serializationObject.id = particleSystem.id;
  62000. serializationObject.capacity = particleSystem.getCapacity();
  62001. // Emitter
  62002. if (particleSystem.emitter.position) {
  62003. var emitterMesh = particleSystem.emitter;
  62004. serializationObject.emitterId = emitterMesh.id;
  62005. }
  62006. else {
  62007. var emitterPosition = particleSystem.emitter;
  62008. serializationObject.emitter = emitterPosition.asArray();
  62009. }
  62010. // Emitter
  62011. if (particleSystem.particleEmitterType) {
  62012. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  62013. }
  62014. if (particleSystem.particleTexture) {
  62015. serializationObject.textureName = particleSystem.particleTexture.name;
  62016. serializationObject.invertY = particleSystem.particleTexture._invertY;
  62017. }
  62018. // Animations
  62019. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  62020. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  62021. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  62022. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  62023. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  62024. // Particle system
  62025. serializationObject.startDelay = particleSystem.startDelay;
  62026. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  62027. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  62028. serializationObject.billboardMode = particleSystem.billboardMode;
  62029. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  62030. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  62031. serializationObject.minSize = particleSystem.minSize;
  62032. serializationObject.maxSize = particleSystem.maxSize;
  62033. serializationObject.minScaleX = particleSystem.minScaleX;
  62034. serializationObject.maxScaleX = particleSystem.maxScaleX;
  62035. serializationObject.minScaleY = particleSystem.minScaleY;
  62036. serializationObject.maxScaleY = particleSystem.maxScaleY;
  62037. serializationObject.minEmitPower = particleSystem.minEmitPower;
  62038. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  62039. serializationObject.minLifeTime = particleSystem.minLifeTime;
  62040. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  62041. serializationObject.emitRate = particleSystem.emitRate;
  62042. serializationObject.gravity = particleSystem.gravity.asArray();
  62043. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  62044. serializationObject.color1 = particleSystem.color1.asArray();
  62045. serializationObject.color2 = particleSystem.color2.asArray();
  62046. serializationObject.colorDead = particleSystem.colorDead.asArray();
  62047. serializationObject.updateSpeed = particleSystem.updateSpeed;
  62048. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  62049. serializationObject.blendMode = particleSystem.blendMode;
  62050. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  62051. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  62052. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  62053. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  62054. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  62055. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  62056. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  62057. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  62058. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  62059. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  62060. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  62061. var colorGradients = particleSystem.getColorGradients();
  62062. if (colorGradients) {
  62063. serializationObject.colorGradients = [];
  62064. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  62065. var colorGradient = colorGradients_1[_i];
  62066. var serializedGradient = {
  62067. gradient: colorGradient.gradient,
  62068. color1: colorGradient.color1.asArray()
  62069. };
  62070. if (colorGradient.color2) {
  62071. serializedGradient.color2 = colorGradient.color2.asArray();
  62072. }
  62073. serializationObject.colorGradients.push(serializedGradient);
  62074. }
  62075. }
  62076. var rampGradients = particleSystem.getRampGradients();
  62077. if (rampGradients) {
  62078. serializationObject.rampGradients = [];
  62079. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  62080. var rampGradient = rampGradients_1[_a];
  62081. var serializedGradient = {
  62082. gradient: rampGradient.gradient,
  62083. color: rampGradient.color.asArray()
  62084. };
  62085. serializationObject.rampGradients.push(serializedGradient);
  62086. }
  62087. serializationObject.useRampGradients = particleSystem.useRampGradients;
  62088. }
  62089. var colorRemapGradients = particleSystem.getColorRemapGradients();
  62090. if (colorRemapGradients) {
  62091. serializationObject.colorRemapGradients = [];
  62092. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  62093. var colorRemapGradient = colorRemapGradients_1[_b];
  62094. var serializedGradient = {
  62095. gradient: colorRemapGradient.gradient,
  62096. factor1: colorRemapGradient.factor1
  62097. };
  62098. if (colorRemapGradient.factor2 !== undefined) {
  62099. serializedGradient.factor2 = colorRemapGradient.factor2;
  62100. }
  62101. serializationObject.colorRemapGradients.push(serializedGradient);
  62102. }
  62103. }
  62104. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  62105. if (alphaRemapGradients) {
  62106. serializationObject.alphaRemapGradients = [];
  62107. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  62108. var alphaRemapGradient = alphaRemapGradients_1[_c];
  62109. var serializedGradient = {
  62110. gradient: alphaRemapGradient.gradient,
  62111. factor1: alphaRemapGradient.factor1
  62112. };
  62113. if (alphaRemapGradient.factor2 !== undefined) {
  62114. serializedGradient.factor2 = alphaRemapGradient.factor2;
  62115. }
  62116. serializationObject.alphaRemapGradients.push(serializedGradient);
  62117. }
  62118. }
  62119. var sizeGradients = particleSystem.getSizeGradients();
  62120. if (sizeGradients) {
  62121. serializationObject.sizeGradients = [];
  62122. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  62123. var sizeGradient = sizeGradients_1[_d];
  62124. var serializedGradient = {
  62125. gradient: sizeGradient.gradient,
  62126. factor1: sizeGradient.factor1
  62127. };
  62128. if (sizeGradient.factor2 !== undefined) {
  62129. serializedGradient.factor2 = sizeGradient.factor2;
  62130. }
  62131. serializationObject.sizeGradients.push(serializedGradient);
  62132. }
  62133. }
  62134. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  62135. if (angularSpeedGradients) {
  62136. serializationObject.angularSpeedGradients = [];
  62137. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  62138. var angularSpeedGradient = angularSpeedGradients_1[_e];
  62139. var serializedGradient = {
  62140. gradient: angularSpeedGradient.gradient,
  62141. factor1: angularSpeedGradient.factor1
  62142. };
  62143. if (angularSpeedGradient.factor2 !== undefined) {
  62144. serializedGradient.factor2 = angularSpeedGradient.factor2;
  62145. }
  62146. serializationObject.angularSpeedGradients.push(serializedGradient);
  62147. }
  62148. }
  62149. var velocityGradients = particleSystem.getVelocityGradients();
  62150. if (velocityGradients) {
  62151. serializationObject.velocityGradients = [];
  62152. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  62153. var velocityGradient = velocityGradients_1[_f];
  62154. var serializedGradient = {
  62155. gradient: velocityGradient.gradient,
  62156. factor1: velocityGradient.factor1
  62157. };
  62158. if (velocityGradient.factor2 !== undefined) {
  62159. serializedGradient.factor2 = velocityGradient.factor2;
  62160. }
  62161. serializationObject.velocityGradients.push(serializedGradient);
  62162. }
  62163. }
  62164. var dragGradients = particleSystem.getDragGradients();
  62165. if (dragGradients) {
  62166. serializationObject.dragyGradients = [];
  62167. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  62168. var dragGradient = dragGradients_1[_g];
  62169. var serializedGradient = {
  62170. gradient: dragGradient.gradient,
  62171. factor1: dragGradient.factor1
  62172. };
  62173. if (dragGradient.factor2 !== undefined) {
  62174. serializedGradient.factor2 = dragGradient.factor2;
  62175. }
  62176. serializationObject.dragGradients.push(serializedGradient);
  62177. }
  62178. }
  62179. var emitRateGradients = particleSystem.getEmitRateGradients();
  62180. if (emitRateGradients) {
  62181. serializationObject.emitRateGradients = [];
  62182. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  62183. var emitRateGradient = emitRateGradients_1[_h];
  62184. var serializedGradient = {
  62185. gradient: emitRateGradient.gradient,
  62186. factor1: emitRateGradient.factor1
  62187. };
  62188. if (emitRateGradient.factor2 !== undefined) {
  62189. serializedGradient.factor2 = emitRateGradient.factor2;
  62190. }
  62191. serializationObject.emitRateGradients.push(serializedGradient);
  62192. }
  62193. }
  62194. var startSizeGradients = particleSystem.getStartSizeGradients();
  62195. if (startSizeGradients) {
  62196. serializationObject.startSizeGradients = [];
  62197. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  62198. var startSizeGradient = startSizeGradients_1[_j];
  62199. var serializedGradient = {
  62200. gradient: startSizeGradient.gradient,
  62201. factor1: startSizeGradient.factor1
  62202. };
  62203. if (startSizeGradient.factor2 !== undefined) {
  62204. serializedGradient.factor2 = startSizeGradient.factor2;
  62205. }
  62206. serializationObject.startSizeGradients.push(serializedGradient);
  62207. }
  62208. }
  62209. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  62210. if (lifeTimeGradients) {
  62211. serializationObject.lifeTimeGradients = [];
  62212. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  62213. var lifeTimeGradient = lifeTimeGradients_1[_k];
  62214. var serializedGradient = {
  62215. gradient: lifeTimeGradient.gradient,
  62216. factor1: lifeTimeGradient.factor1
  62217. };
  62218. if (lifeTimeGradient.factor2 !== undefined) {
  62219. serializedGradient.factor2 = lifeTimeGradient.factor2;
  62220. }
  62221. serializationObject.lifeTimeGradients.push(serializedGradient);
  62222. }
  62223. }
  62224. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  62225. if (limitVelocityGradients) {
  62226. serializationObject.limitVelocityGradients = [];
  62227. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  62228. var limitVelocityGradient = limitVelocityGradients_1[_l];
  62229. var serializedGradient = {
  62230. gradient: limitVelocityGradient.gradient,
  62231. factor1: limitVelocityGradient.factor1
  62232. };
  62233. if (limitVelocityGradient.factor2 !== undefined) {
  62234. serializedGradient.factor2 = limitVelocityGradient.factor2;
  62235. }
  62236. serializationObject.limitVelocityGradients.push(serializedGradient);
  62237. }
  62238. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  62239. }
  62240. if (particleSystem.noiseTexture) {
  62241. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  62242. }
  62243. };
  62244. /** @hidden */
  62245. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  62246. // Texture
  62247. if (parsedParticleSystem.textureName) {
  62248. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  62249. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  62250. }
  62251. // Emitter
  62252. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  62253. particleSystem.emitter = BABYLON.Vector3.Zero();
  62254. }
  62255. else if (parsedParticleSystem.emitterId) {
  62256. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  62257. }
  62258. else {
  62259. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  62260. }
  62261. // Misc.
  62262. if (parsedParticleSystem.renderingGroupId !== undefined) {
  62263. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  62264. }
  62265. if (parsedParticleSystem.isBillboardBased !== undefined) {
  62266. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  62267. }
  62268. if (parsedParticleSystem.billboardMode !== undefined) {
  62269. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  62270. }
  62271. // Animations
  62272. if (parsedParticleSystem.animations) {
  62273. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  62274. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  62275. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62276. }
  62277. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  62278. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  62279. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  62280. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  62281. }
  62282. if (parsedParticleSystem.autoAnimate) {
  62283. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  62284. }
  62285. // Particle system
  62286. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  62287. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  62288. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  62289. particleSystem.minSize = parsedParticleSystem.minSize;
  62290. particleSystem.maxSize = parsedParticleSystem.maxSize;
  62291. if (parsedParticleSystem.minScaleX) {
  62292. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  62293. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  62294. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  62295. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  62296. }
  62297. if (parsedParticleSystem.preWarmCycles !== undefined) {
  62298. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  62299. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  62300. }
  62301. if (parsedParticleSystem.minInitialRotation !== undefined) {
  62302. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  62303. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  62304. }
  62305. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  62306. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  62307. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  62308. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  62309. particleSystem.emitRate = parsedParticleSystem.emitRate;
  62310. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  62311. if (parsedParticleSystem.noiseStrength) {
  62312. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  62313. }
  62314. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  62315. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  62316. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  62317. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  62318. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  62319. particleSystem.blendMode = parsedParticleSystem.blendMode;
  62320. if (parsedParticleSystem.colorGradients) {
  62321. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  62322. var colorGradient = _a[_i];
  62323. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  62324. }
  62325. }
  62326. if (parsedParticleSystem.rampGradients) {
  62327. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  62328. var rampGradient = _c[_b];
  62329. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  62330. }
  62331. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  62332. }
  62333. if (parsedParticleSystem.colorRemapGradients) {
  62334. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  62335. var colorRemapGradient = _e[_d];
  62336. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  62337. }
  62338. }
  62339. if (parsedParticleSystem.alphaRemapGradients) {
  62340. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  62341. var alphaRemapGradient = _g[_f];
  62342. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  62343. }
  62344. }
  62345. if (parsedParticleSystem.sizeGradients) {
  62346. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  62347. var sizeGradient = _j[_h];
  62348. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  62349. }
  62350. }
  62351. if (parsedParticleSystem.sizeGradients) {
  62352. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  62353. var sizeGradient = _l[_k];
  62354. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  62355. }
  62356. }
  62357. if (parsedParticleSystem.angularSpeedGradients) {
  62358. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  62359. var angularSpeedGradient = _o[_m];
  62360. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  62361. }
  62362. }
  62363. if (parsedParticleSystem.velocityGradients) {
  62364. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  62365. var velocityGradient = _q[_p];
  62366. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  62367. }
  62368. }
  62369. if (parsedParticleSystem.dragGradients) {
  62370. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  62371. var dragGradient = _s[_r];
  62372. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  62373. }
  62374. }
  62375. if (parsedParticleSystem.emitRateGradients) {
  62376. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  62377. var emitRateGradient = _u[_t];
  62378. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  62379. }
  62380. }
  62381. if (parsedParticleSystem.startSizeGradients) {
  62382. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  62383. var startSizeGradient = _w[_v];
  62384. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  62385. }
  62386. }
  62387. if (parsedParticleSystem.lifeTimeGradients) {
  62388. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  62389. var lifeTimeGradient = _y[_x];
  62390. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  62391. }
  62392. }
  62393. if (parsedParticleSystem.limitVelocityGradients) {
  62394. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  62395. var limitVelocityGradient = _0[_z];
  62396. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  62397. }
  62398. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  62399. }
  62400. if (parsedParticleSystem.noiseTexture) {
  62401. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  62402. }
  62403. // Emitter
  62404. var emitterType;
  62405. if (parsedParticleSystem.particleEmitterType) {
  62406. switch (parsedParticleSystem.particleEmitterType.type) {
  62407. case "SphereParticleEmitter":
  62408. emitterType = new BABYLON.SphereParticleEmitter();
  62409. break;
  62410. case "SphereDirectedParticleEmitter":
  62411. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  62412. break;
  62413. case "ConeEmitter":
  62414. case "ConeParticleEmitter":
  62415. emitterType = new BABYLON.ConeParticleEmitter();
  62416. break;
  62417. case "CylinderParticleEmitter":
  62418. emitterType = new BABYLON.CylinderParticleEmitter();
  62419. break;
  62420. case "HemisphericParticleEmitter":
  62421. emitterType = new BABYLON.HemisphericParticleEmitter();
  62422. break;
  62423. case "BoxEmitter":
  62424. case "BoxParticleEmitter":
  62425. default:
  62426. emitterType = new BABYLON.BoxParticleEmitter();
  62427. break;
  62428. }
  62429. emitterType.parse(parsedParticleSystem.particleEmitterType);
  62430. }
  62431. else {
  62432. emitterType = new BABYLON.BoxParticleEmitter();
  62433. emitterType.parse(parsedParticleSystem);
  62434. }
  62435. particleSystem.particleEmitterType = emitterType;
  62436. // Animation sheet
  62437. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  62438. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  62439. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  62440. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  62441. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  62442. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  62443. };
  62444. /**
  62445. * Parses a JSON object to create a particle system.
  62446. * @param parsedParticleSystem The JSON object to parse
  62447. * @param scene The scene to create the particle system in
  62448. * @param rootUrl The root url to use to load external dependencies like texture
  62449. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  62450. * @returns the Parsed particle system
  62451. */
  62452. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  62453. if (doNotStart === void 0) { doNotStart = false; }
  62454. var name = parsedParticleSystem.name;
  62455. var custom = null;
  62456. var program = null;
  62457. if (parsedParticleSystem.customShader) {
  62458. program = parsedParticleSystem.customShader;
  62459. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  62460. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  62461. }
  62462. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  62463. particleSystem.customShader = program;
  62464. if (parsedParticleSystem.id) {
  62465. particleSystem.id = parsedParticleSystem.id;
  62466. }
  62467. // SubEmitters
  62468. if (parsedParticleSystem.subEmitters) {
  62469. particleSystem.subEmitters = [];
  62470. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  62471. var cell = _a[_i];
  62472. var cellArray = [];
  62473. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  62474. var sub = cell_1[_b];
  62475. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  62476. }
  62477. particleSystem.subEmitters.push(cellArray);
  62478. }
  62479. }
  62480. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62481. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  62482. // Auto start
  62483. if (parsedParticleSystem.preventAutoStart) {
  62484. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  62485. }
  62486. if (!doNotStart && !particleSystem.preventAutoStart) {
  62487. particleSystem.start();
  62488. }
  62489. return particleSystem;
  62490. };
  62491. /**
  62492. * Billboard mode will only apply to Y axis
  62493. */
  62494. ParticleSystem.BILLBOARDMODE_Y = 2;
  62495. /**
  62496. * Billboard mode will apply to all axes
  62497. */
  62498. ParticleSystem.BILLBOARDMODE_ALL = 7;
  62499. /**
  62500. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  62501. */
  62502. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  62503. return ParticleSystem;
  62504. }(BABYLON.BaseParticleSystem));
  62505. BABYLON.ParticleSystem = ParticleSystem;
  62506. })(BABYLON || (BABYLON = {}));
  62507. //# sourceMappingURL=babylon.particleSystem.js.map
  62508. var BABYLON;
  62509. (function (BABYLON) {
  62510. /**
  62511. * Particle emitter emitting particles from the inside of a box.
  62512. * It emits the particles randomly between 2 given directions.
  62513. */
  62514. var BoxParticleEmitter = /** @class */ (function () {
  62515. /**
  62516. * Creates a new instance BoxParticleEmitter
  62517. */
  62518. function BoxParticleEmitter() {
  62519. /**
  62520. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62521. */
  62522. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  62523. /**
  62524. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62525. */
  62526. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  62527. /**
  62528. * 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.
  62529. */
  62530. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  62531. /**
  62532. * 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.
  62533. */
  62534. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  62535. }
  62536. /**
  62537. * Called by the particle System when the direction is computed for the created particle.
  62538. * @param worldMatrix is the world matrix of the particle system
  62539. * @param directionToUpdate is the direction vector to update with the result
  62540. * @param particle is the particle we are computed the direction for
  62541. */
  62542. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62543. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62544. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62545. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62546. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62547. };
  62548. /**
  62549. * Called by the particle System when the position is computed for the created particle.
  62550. * @param worldMatrix is the world matrix of the particle system
  62551. * @param positionToUpdate is the position vector to update with the result
  62552. * @param particle is the particle we are computed the position for
  62553. */
  62554. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62555. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  62556. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  62557. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  62558. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  62559. };
  62560. /**
  62561. * Clones the current emitter and returns a copy of it
  62562. * @returns the new emitter
  62563. */
  62564. BoxParticleEmitter.prototype.clone = function () {
  62565. var newOne = new BoxParticleEmitter();
  62566. BABYLON.Tools.DeepCopy(this, newOne);
  62567. return newOne;
  62568. };
  62569. /**
  62570. * Called by the GPUParticleSystem to setup the update shader
  62571. * @param effect defines the update shader
  62572. */
  62573. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  62574. effect.setVector3("direction1", this.direction1);
  62575. effect.setVector3("direction2", this.direction2);
  62576. effect.setVector3("minEmitBox", this.minEmitBox);
  62577. effect.setVector3("maxEmitBox", this.maxEmitBox);
  62578. };
  62579. /**
  62580. * Returns a string to use to update the GPU particles update shader
  62581. * @returns a string containng the defines string
  62582. */
  62583. BoxParticleEmitter.prototype.getEffectDefines = function () {
  62584. return "#define BOXEMITTER";
  62585. };
  62586. /**
  62587. * Returns the string "BoxParticleEmitter"
  62588. * @returns a string containing the class name
  62589. */
  62590. BoxParticleEmitter.prototype.getClassName = function () {
  62591. return "BoxParticleEmitter";
  62592. };
  62593. /**
  62594. * Serializes the particle system to a JSON object.
  62595. * @returns the JSON object
  62596. */
  62597. BoxParticleEmitter.prototype.serialize = function () {
  62598. var serializationObject = {};
  62599. serializationObject.type = this.getClassName();
  62600. serializationObject.direction1 = this.direction1.asArray();
  62601. serializationObject.direction2 = this.direction2.asArray();
  62602. serializationObject.minEmitBox = this.minEmitBox.asArray();
  62603. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  62604. return serializationObject;
  62605. };
  62606. /**
  62607. * Parse properties from a JSON object
  62608. * @param serializationObject defines the JSON object
  62609. */
  62610. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  62611. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  62612. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  62613. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  62614. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  62615. };
  62616. return BoxParticleEmitter;
  62617. }());
  62618. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  62619. })(BABYLON || (BABYLON = {}));
  62620. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  62621. var BABYLON;
  62622. (function (BABYLON) {
  62623. /**
  62624. * Particle emitter emitting particles from the inside of a cylinder.
  62625. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  62626. */
  62627. var CylinderParticleEmitter = /** @class */ (function () {
  62628. /**
  62629. * Creates a new instance CylinderParticleEmitter
  62630. * @param radius the radius of the emission cylinder (1 by default)
  62631. * @param height the height of the emission cylinder (1 by default)
  62632. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  62633. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  62634. */
  62635. function CylinderParticleEmitter(
  62636. /**
  62637. * The radius of the emission cylinder.
  62638. */
  62639. radius,
  62640. /**
  62641. * The height of the emission cylinder.
  62642. */
  62643. height,
  62644. /**
  62645. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  62646. */
  62647. radiusRange,
  62648. /**
  62649. * How much to randomize the particle direction [0-1].
  62650. */
  62651. directionRandomizer) {
  62652. if (radius === void 0) { radius = 1; }
  62653. if (height === void 0) { height = 1; }
  62654. if (radiusRange === void 0) { radiusRange = 1; }
  62655. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  62656. this.radius = radius;
  62657. this.height = height;
  62658. this.radiusRange = radiusRange;
  62659. this.directionRandomizer = directionRandomizer;
  62660. }
  62661. /**
  62662. * Called by the particle System when the direction is computed for the created particle.
  62663. * @param worldMatrix is the world matrix of the particle system
  62664. * @param directionToUpdate is the direction vector to update with the result
  62665. * @param particle is the particle we are computed the direction for
  62666. */
  62667. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62668. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  62669. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  62670. var angle = Math.atan2(direction.x, direction.z);
  62671. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  62672. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  62673. direction.x = Math.sin(angle);
  62674. direction.z = Math.cos(angle);
  62675. direction.normalize();
  62676. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  62677. };
  62678. /**
  62679. * Called by the particle System when the position is computed for the created particle.
  62680. * @param worldMatrix is the world matrix of the particle system
  62681. * @param positionToUpdate is the position vector to update with the result
  62682. * @param particle is the particle we are computed the position for
  62683. */
  62684. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62685. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  62686. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  62687. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  62688. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  62689. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  62690. var xPos = positionRadius * Math.cos(angle);
  62691. var zPos = positionRadius * Math.sin(angle);
  62692. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  62693. };
  62694. /**
  62695. * Clones the current emitter and returns a copy of it
  62696. * @returns the new emitter
  62697. */
  62698. CylinderParticleEmitter.prototype.clone = function () {
  62699. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  62700. BABYLON.Tools.DeepCopy(this, newOne);
  62701. return newOne;
  62702. };
  62703. /**
  62704. * Called by the GPUParticleSystem to setup the update shader
  62705. * @param effect defines the update shader
  62706. */
  62707. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  62708. effect.setFloat("radius", this.radius);
  62709. effect.setFloat("height", this.height);
  62710. effect.setFloat("radiusRange", this.radiusRange);
  62711. effect.setFloat("directionRandomizer", this.directionRandomizer);
  62712. };
  62713. /**
  62714. * Returns a string to use to update the GPU particles update shader
  62715. * @returns a string containng the defines string
  62716. */
  62717. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  62718. return "#define CYLINDEREMITTER";
  62719. };
  62720. /**
  62721. * Returns the string "CylinderParticleEmitter"
  62722. * @returns a string containing the class name
  62723. */
  62724. CylinderParticleEmitter.prototype.getClassName = function () {
  62725. return "CylinderParticleEmitter";
  62726. };
  62727. /**
  62728. * Serializes the particle system to a JSON object.
  62729. * @returns the JSON object
  62730. */
  62731. CylinderParticleEmitter.prototype.serialize = function () {
  62732. var serializationObject = {};
  62733. serializationObject.type = this.getClassName();
  62734. serializationObject.radius = this.radius;
  62735. serializationObject.height = this.height;
  62736. serializationObject.radiusRange = this.radiusRange;
  62737. serializationObject.directionRandomizer = this.directionRandomizer;
  62738. return serializationObject;
  62739. };
  62740. /**
  62741. * Parse properties from a JSON object
  62742. * @param serializationObject defines the JSON object
  62743. */
  62744. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  62745. this.radius = serializationObject.radius;
  62746. this.height = serializationObject.height;
  62747. this.radiusRange = serializationObject.radiusRange;
  62748. this.directionRandomizer = serializationObject.directionRandomizer;
  62749. };
  62750. return CylinderParticleEmitter;
  62751. }());
  62752. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  62753. /**
  62754. * Particle emitter emitting particles from the inside of a cylinder.
  62755. * It emits the particles randomly between two vectors.
  62756. */
  62757. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  62758. __extends(CylinderDirectedParticleEmitter, _super);
  62759. /**
  62760. * Creates a new instance CylinderDirectedParticleEmitter
  62761. * @param radius the radius of the emission cylinder (1 by default)
  62762. * @param height the height of the emission cylinder (1 by default)
  62763. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  62764. * @param direction1 the min limit of the emission direction (up vector by default)
  62765. * @param direction2 the max limit of the emission direction (up vector by default)
  62766. */
  62767. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  62768. /**
  62769. * The min limit of the emission direction.
  62770. */
  62771. direction1,
  62772. /**
  62773. * The max limit of the emission direction.
  62774. */
  62775. direction2) {
  62776. if (radius === void 0) { radius = 1; }
  62777. if (height === void 0) { height = 1; }
  62778. if (radiusRange === void 0) { radiusRange = 1; }
  62779. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  62780. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  62781. var _this = _super.call(this, radius, height, radiusRange) || this;
  62782. _this.direction1 = direction1;
  62783. _this.direction2 = direction2;
  62784. return _this;
  62785. }
  62786. /**
  62787. * Called by the particle System when the direction is computed for the created particle.
  62788. * @param worldMatrix is the world matrix of the particle system
  62789. * @param directionToUpdate is the direction vector to update with the result
  62790. * @param particle is the particle we are computed the direction for
  62791. */
  62792. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62793. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62794. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62795. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62796. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62797. };
  62798. /**
  62799. * Clones the current emitter and returns a copy of it
  62800. * @returns the new emitter
  62801. */
  62802. CylinderDirectedParticleEmitter.prototype.clone = function () {
  62803. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  62804. BABYLON.Tools.DeepCopy(this, newOne);
  62805. return newOne;
  62806. };
  62807. /**
  62808. * Called by the GPUParticleSystem to setup the update shader
  62809. * @param effect defines the update shader
  62810. */
  62811. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  62812. effect.setFloat("radius", this.radius);
  62813. effect.setFloat("height", this.height);
  62814. effect.setFloat("radiusRange", this.radiusRange);
  62815. effect.setVector3("direction1", this.direction1);
  62816. effect.setVector3("direction2", this.direction2);
  62817. };
  62818. /**
  62819. * Returns a string to use to update the GPU particles update shader
  62820. * @returns a string containng the defines string
  62821. */
  62822. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  62823. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  62824. };
  62825. /**
  62826. * Returns the string "CylinderDirectedParticleEmitter"
  62827. * @returns a string containing the class name
  62828. */
  62829. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  62830. return "CylinderDirectedParticleEmitter";
  62831. };
  62832. /**
  62833. * Serializes the particle system to a JSON object.
  62834. * @returns the JSON object
  62835. */
  62836. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  62837. var serializationObject = _super.prototype.serialize.call(this);
  62838. serializationObject.direction1 = this.direction1.asArray();
  62839. serializationObject.direction2 = this.direction2.asArray();
  62840. return serializationObject;
  62841. };
  62842. /**
  62843. * Parse properties from a JSON object
  62844. * @param serializationObject defines the JSON object
  62845. */
  62846. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  62847. _super.prototype.parse.call(this, serializationObject);
  62848. this.direction1.copyFrom(serializationObject.direction1);
  62849. this.direction2.copyFrom(serializationObject.direction2);
  62850. };
  62851. return CylinderDirectedParticleEmitter;
  62852. }(CylinderParticleEmitter));
  62853. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  62854. })(BABYLON || (BABYLON = {}));
  62855. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  62856. var BABYLON;
  62857. (function (BABYLON) {
  62858. /**
  62859. * Particle emitter emitting particles from the inside of a cone.
  62860. * It emits the particles alongside the cone volume from the base to the particle.
  62861. * The emission direction might be randomized.
  62862. */
  62863. var ConeParticleEmitter = /** @class */ (function () {
  62864. /**
  62865. * Creates a new instance ConeParticleEmitter
  62866. * @param radius the radius of the emission cone (1 by default)
  62867. * @param angles the cone base angle (PI by default)
  62868. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  62869. */
  62870. function ConeParticleEmitter(radius, angle,
  62871. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  62872. directionRandomizer) {
  62873. if (radius === void 0) { radius = 1; }
  62874. if (angle === void 0) { angle = Math.PI; }
  62875. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  62876. this.directionRandomizer = directionRandomizer;
  62877. /**
  62878. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  62879. */
  62880. this.radiusRange = 1;
  62881. /**
  62882. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  62883. */
  62884. this.heightRange = 1;
  62885. /**
  62886. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  62887. */
  62888. this.emitFromSpawnPointOnly = false;
  62889. this.angle = angle;
  62890. this.radius = radius;
  62891. }
  62892. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  62893. /**
  62894. * Gets or sets the radius of the emission cone
  62895. */
  62896. get: function () {
  62897. return this._radius;
  62898. },
  62899. set: function (value) {
  62900. this._radius = value;
  62901. this._buildHeight();
  62902. },
  62903. enumerable: true,
  62904. configurable: true
  62905. });
  62906. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  62907. /**
  62908. * Gets or sets the angle of the emission cone
  62909. */
  62910. get: function () {
  62911. return this._angle;
  62912. },
  62913. set: function (value) {
  62914. this._angle = value;
  62915. this._buildHeight();
  62916. },
  62917. enumerable: true,
  62918. configurable: true
  62919. });
  62920. ConeParticleEmitter.prototype._buildHeight = function () {
  62921. if (this._angle !== 0) {
  62922. this._height = this._radius / Math.tan(this._angle / 2);
  62923. }
  62924. else {
  62925. this._height = 1;
  62926. }
  62927. };
  62928. /**
  62929. * Called by the particle System when the direction is computed for the created particle.
  62930. * @param worldMatrix is the world matrix of the particle system
  62931. * @param directionToUpdate is the direction vector to update with the result
  62932. * @param particle is the particle we are computed the direction for
  62933. */
  62934. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62935. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  62936. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  62937. }
  62938. else {
  62939. // measure the direction Vector from the emitter to the particle.
  62940. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  62941. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62942. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62943. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62944. direction.x += randX;
  62945. direction.y += randY;
  62946. direction.z += randZ;
  62947. direction.normalize();
  62948. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  62949. }
  62950. };
  62951. /**
  62952. * Called by the particle System when the position is computed for the created particle.
  62953. * @param worldMatrix is the world matrix of the particle system
  62954. * @param positionToUpdate is the position vector to update with the result
  62955. * @param particle is the particle we are computed the position for
  62956. */
  62957. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62958. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  62959. var h;
  62960. if (!this.emitFromSpawnPointOnly) {
  62961. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  62962. // Better distribution in a cone at normal angles.
  62963. h = 1 - h * h;
  62964. }
  62965. else {
  62966. h = 0.0001;
  62967. }
  62968. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  62969. radius = radius * h;
  62970. var randX = radius * Math.sin(s);
  62971. var randZ = radius * Math.cos(s);
  62972. var randY = h * this._height;
  62973. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  62974. };
  62975. /**
  62976. * Clones the current emitter and returns a copy of it
  62977. * @returns the new emitter
  62978. */
  62979. ConeParticleEmitter.prototype.clone = function () {
  62980. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  62981. BABYLON.Tools.DeepCopy(this, newOne);
  62982. return newOne;
  62983. };
  62984. /**
  62985. * Called by the GPUParticleSystem to setup the update shader
  62986. * @param effect defines the update shader
  62987. */
  62988. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  62989. effect.setFloat2("radius", this._radius, this.radiusRange);
  62990. effect.setFloat("coneAngle", this._angle);
  62991. effect.setFloat2("height", this._height, this.heightRange);
  62992. effect.setFloat("directionRandomizer", this.directionRandomizer);
  62993. };
  62994. /**
  62995. * Returns a string to use to update the GPU particles update shader
  62996. * @returns a string containng the defines string
  62997. */
  62998. ConeParticleEmitter.prototype.getEffectDefines = function () {
  62999. var defines = "#define CONEEMITTER";
  63000. if (this.emitFromSpawnPointOnly) {
  63001. defines += "\n#define CONEEMITTERSPAWNPOINT";
  63002. }
  63003. return defines;
  63004. };
  63005. /**
  63006. * Returns the string "ConeParticleEmitter"
  63007. * @returns a string containing the class name
  63008. */
  63009. ConeParticleEmitter.prototype.getClassName = function () {
  63010. return "ConeParticleEmitter";
  63011. };
  63012. /**
  63013. * Serializes the particle system to a JSON object.
  63014. * @returns the JSON object
  63015. */
  63016. ConeParticleEmitter.prototype.serialize = function () {
  63017. var serializationObject = {};
  63018. serializationObject.type = this.getClassName();
  63019. serializationObject.radius = this._radius;
  63020. serializationObject.angle = this._angle;
  63021. serializationObject.directionRandomizer = this.directionRandomizer;
  63022. return serializationObject;
  63023. };
  63024. /**
  63025. * Parse properties from a JSON object
  63026. * @param serializationObject defines the JSON object
  63027. */
  63028. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  63029. this.radius = serializationObject.radius;
  63030. this.angle = serializationObject.angle;
  63031. this.directionRandomizer = serializationObject.directionRandomizer;
  63032. };
  63033. return ConeParticleEmitter;
  63034. }());
  63035. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  63036. })(BABYLON || (BABYLON = {}));
  63037. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  63038. var BABYLON;
  63039. (function (BABYLON) {
  63040. /**
  63041. * Particle emitter emitting particles from the inside of a sphere.
  63042. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  63043. */
  63044. var SphereParticleEmitter = /** @class */ (function () {
  63045. /**
  63046. * Creates a new instance SphereParticleEmitter
  63047. * @param radius the radius of the emission sphere (1 by default)
  63048. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63049. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63050. */
  63051. function SphereParticleEmitter(
  63052. /**
  63053. * The radius of the emission sphere.
  63054. */
  63055. radius,
  63056. /**
  63057. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63058. */
  63059. radiusRange,
  63060. /**
  63061. * How much to randomize the particle direction [0-1].
  63062. */
  63063. directionRandomizer) {
  63064. if (radius === void 0) { radius = 1; }
  63065. if (radiusRange === void 0) { radiusRange = 1; }
  63066. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63067. this.radius = radius;
  63068. this.radiusRange = radiusRange;
  63069. this.directionRandomizer = directionRandomizer;
  63070. }
  63071. /**
  63072. * Called by the particle System when the direction is computed for the created particle.
  63073. * @param worldMatrix is the world matrix of the particle system
  63074. * @param directionToUpdate is the direction vector to update with the result
  63075. * @param particle is the particle we are computed the direction for
  63076. */
  63077. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63078. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63079. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63080. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63081. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63082. direction.x += randX;
  63083. direction.y += randY;
  63084. direction.z += randZ;
  63085. direction.normalize();
  63086. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63087. };
  63088. /**
  63089. * Called by the particle System when the position is computed for the created particle.
  63090. * @param worldMatrix is the world matrix of the particle system
  63091. * @param positionToUpdate is the position vector to update with the result
  63092. * @param particle is the particle we are computed the position for
  63093. */
  63094. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63095. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  63096. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  63097. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63098. var theta = Math.acos(2 * v - 1);
  63099. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  63100. var randY = randRadius * Math.cos(theta);
  63101. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  63102. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  63103. };
  63104. /**
  63105. * Clones the current emitter and returns a copy of it
  63106. * @returns the new emitter
  63107. */
  63108. SphereParticleEmitter.prototype.clone = function () {
  63109. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  63110. BABYLON.Tools.DeepCopy(this, newOne);
  63111. return newOne;
  63112. };
  63113. /**
  63114. * Called by the GPUParticleSystem to setup the update shader
  63115. * @param effect defines the update shader
  63116. */
  63117. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  63118. effect.setFloat("radius", this.radius);
  63119. effect.setFloat("radiusRange", this.radiusRange);
  63120. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63121. };
  63122. /**
  63123. * Returns a string to use to update the GPU particles update shader
  63124. * @returns a string containng the defines string
  63125. */
  63126. SphereParticleEmitter.prototype.getEffectDefines = function () {
  63127. return "#define SPHEREEMITTER";
  63128. };
  63129. /**
  63130. * Returns the string "SphereParticleEmitter"
  63131. * @returns a string containing the class name
  63132. */
  63133. SphereParticleEmitter.prototype.getClassName = function () {
  63134. return "SphereParticleEmitter";
  63135. };
  63136. /**
  63137. * Serializes the particle system to a JSON object.
  63138. * @returns the JSON object
  63139. */
  63140. SphereParticleEmitter.prototype.serialize = function () {
  63141. var serializationObject = {};
  63142. serializationObject.type = this.getClassName();
  63143. serializationObject.radius = this.radius;
  63144. serializationObject.radiusRange = this.radiusRange;
  63145. serializationObject.directionRandomizer = this.directionRandomizer;
  63146. return serializationObject;
  63147. };
  63148. /**
  63149. * Parse properties from a JSON object
  63150. * @param serializationObject defines the JSON object
  63151. */
  63152. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  63153. this.radius = serializationObject.radius;
  63154. this.radiusRange = serializationObject.radiusRange;
  63155. this.directionRandomizer = serializationObject.directionRandomizer;
  63156. };
  63157. return SphereParticleEmitter;
  63158. }());
  63159. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  63160. /**
  63161. * Particle emitter emitting particles from the inside of a sphere.
  63162. * It emits the particles randomly between two vectors.
  63163. */
  63164. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  63165. __extends(SphereDirectedParticleEmitter, _super);
  63166. /**
  63167. * Creates a new instance SphereDirectedParticleEmitter
  63168. * @param radius the radius of the emission sphere (1 by default)
  63169. * @param direction1 the min limit of the emission direction (up vector by default)
  63170. * @param direction2 the max limit of the emission direction (up vector by default)
  63171. */
  63172. function SphereDirectedParticleEmitter(radius,
  63173. /**
  63174. * The min limit of the emission direction.
  63175. */
  63176. direction1,
  63177. /**
  63178. * The max limit of the emission direction.
  63179. */
  63180. direction2) {
  63181. if (radius === void 0) { radius = 1; }
  63182. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  63183. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  63184. var _this = _super.call(this, radius) || this;
  63185. _this.direction1 = direction1;
  63186. _this.direction2 = direction2;
  63187. return _this;
  63188. }
  63189. /**
  63190. * Called by the particle System when the direction is computed for the created particle.
  63191. * @param worldMatrix is the world matrix of the particle system
  63192. * @param directionToUpdate is the direction vector to update with the result
  63193. * @param particle is the particle we are computed the direction for
  63194. */
  63195. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63196. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63197. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63198. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63199. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63200. };
  63201. /**
  63202. * Clones the current emitter and returns a copy of it
  63203. * @returns the new emitter
  63204. */
  63205. SphereDirectedParticleEmitter.prototype.clone = function () {
  63206. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  63207. BABYLON.Tools.DeepCopy(this, newOne);
  63208. return newOne;
  63209. };
  63210. /**
  63211. * Called by the GPUParticleSystem to setup the update shader
  63212. * @param effect defines the update shader
  63213. */
  63214. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  63215. effect.setFloat("radius", this.radius);
  63216. effect.setFloat("radiusRange", this.radiusRange);
  63217. effect.setVector3("direction1", this.direction1);
  63218. effect.setVector3("direction2", this.direction2);
  63219. };
  63220. /**
  63221. * Returns a string to use to update the GPU particles update shader
  63222. * @returns a string containng the defines string
  63223. */
  63224. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  63225. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  63226. };
  63227. /**
  63228. * Returns the string "SphereDirectedParticleEmitter"
  63229. * @returns a string containing the class name
  63230. */
  63231. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  63232. return "SphereDirectedParticleEmitter";
  63233. };
  63234. /**
  63235. * Serializes the particle system to a JSON object.
  63236. * @returns the JSON object
  63237. */
  63238. SphereDirectedParticleEmitter.prototype.serialize = function () {
  63239. var serializationObject = _super.prototype.serialize.call(this);
  63240. serializationObject.direction1 = this.direction1.asArray();
  63241. serializationObject.direction2 = this.direction2.asArray();
  63242. return serializationObject;
  63243. };
  63244. /**
  63245. * Parse properties from a JSON object
  63246. * @param serializationObject defines the JSON object
  63247. */
  63248. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  63249. _super.prototype.parse.call(this, serializationObject);
  63250. this.direction1.copyFrom(serializationObject.direction1);
  63251. this.direction2.copyFrom(serializationObject.direction2);
  63252. };
  63253. return SphereDirectedParticleEmitter;
  63254. }(SphereParticleEmitter));
  63255. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  63256. })(BABYLON || (BABYLON = {}));
  63257. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  63258. var BABYLON;
  63259. (function (BABYLON) {
  63260. /**
  63261. * Particle emitter emitting particles from the inside of a hemisphere.
  63262. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  63263. */
  63264. var HemisphericParticleEmitter = /** @class */ (function () {
  63265. /**
  63266. * Creates a new instance HemisphericParticleEmitter
  63267. * @param radius the radius of the emission hemisphere (1 by default)
  63268. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63269. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63270. */
  63271. function HemisphericParticleEmitter(
  63272. /**
  63273. * The radius of the emission hemisphere.
  63274. */
  63275. radius,
  63276. /**
  63277. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63278. */
  63279. radiusRange,
  63280. /**
  63281. * How much to randomize the particle direction [0-1].
  63282. */
  63283. directionRandomizer) {
  63284. if (radius === void 0) { radius = 1; }
  63285. if (radiusRange === void 0) { radiusRange = 1; }
  63286. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63287. this.radius = radius;
  63288. this.radiusRange = radiusRange;
  63289. this.directionRandomizer = directionRandomizer;
  63290. }
  63291. /**
  63292. * Called by the particle System when the direction is computed for the created particle.
  63293. * @param worldMatrix is the world matrix of the particle system
  63294. * @param directionToUpdate is the direction vector to update with the result
  63295. * @param particle is the particle we are computed the direction for
  63296. */
  63297. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63298. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63299. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63300. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63301. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63302. direction.x += randX;
  63303. direction.y += randY;
  63304. direction.z += randZ;
  63305. direction.normalize();
  63306. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63307. };
  63308. /**
  63309. * Called by the particle System when the position is computed for the created particle.
  63310. * @param worldMatrix is the world matrix of the particle system
  63311. * @param positionToUpdate is the position vector to update with the result
  63312. * @param particle is the particle we are computed the position for
  63313. */
  63314. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63315. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  63316. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  63317. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63318. var theta = Math.acos(2 * v - 1);
  63319. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  63320. var randY = randRadius * Math.cos(theta);
  63321. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  63322. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  63323. };
  63324. /**
  63325. * Clones the current emitter and returns a copy of it
  63326. * @returns the new emitter
  63327. */
  63328. HemisphericParticleEmitter.prototype.clone = function () {
  63329. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  63330. BABYLON.Tools.DeepCopy(this, newOne);
  63331. return newOne;
  63332. };
  63333. /**
  63334. * Called by the GPUParticleSystem to setup the update shader
  63335. * @param effect defines the update shader
  63336. */
  63337. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  63338. effect.setFloat("radius", this.radius);
  63339. effect.setFloat("radiusRange", this.radiusRange);
  63340. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63341. };
  63342. /**
  63343. * Returns a string to use to update the GPU particles update shader
  63344. * @returns a string containng the defines string
  63345. */
  63346. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  63347. return "#define HEMISPHERICEMITTER";
  63348. };
  63349. /**
  63350. * Returns the string "HemisphericParticleEmitter"
  63351. * @returns a string containing the class name
  63352. */
  63353. HemisphericParticleEmitter.prototype.getClassName = function () {
  63354. return "HemisphericParticleEmitter";
  63355. };
  63356. /**
  63357. * Serializes the particle system to a JSON object.
  63358. * @returns the JSON object
  63359. */
  63360. HemisphericParticleEmitter.prototype.serialize = function () {
  63361. var serializationObject = {};
  63362. serializationObject.type = this.getClassName();
  63363. serializationObject.radius = this.radius;
  63364. serializationObject.radiusRange = this.radiusRange;
  63365. serializationObject.directionRandomizer = this.directionRandomizer;
  63366. return serializationObject;
  63367. };
  63368. /**
  63369. * Parse properties from a JSON object
  63370. * @param serializationObject defines the JSON object
  63371. */
  63372. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  63373. this.radius = serializationObject.radius;
  63374. this.radiusRange = serializationObject.radiusRange;
  63375. this.directionRandomizer = serializationObject.directionRandomizer;
  63376. };
  63377. return HemisphericParticleEmitter;
  63378. }());
  63379. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  63380. })(BABYLON || (BABYLON = {}));
  63381. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  63382. var BABYLON;
  63383. (function (BABYLON) {
  63384. /**
  63385. * Particle emitter emitting particles from a point.
  63386. * It emits the particles randomly between 2 given directions.
  63387. */
  63388. var PointParticleEmitter = /** @class */ (function () {
  63389. /**
  63390. * Creates a new instance PointParticleEmitter
  63391. */
  63392. function PointParticleEmitter() {
  63393. /**
  63394. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63395. */
  63396. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  63397. /**
  63398. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63399. */
  63400. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  63401. }
  63402. /**
  63403. * Called by the particle System when the direction is computed for the created particle.
  63404. * @param worldMatrix is the world matrix of the particle system
  63405. * @param directionToUpdate is the direction vector to update with the result
  63406. * @param particle is the particle we are computed the direction for
  63407. */
  63408. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63409. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63410. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63411. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63412. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63413. };
  63414. /**
  63415. * Called by the particle System when the position is computed for the created particle.
  63416. * @param worldMatrix is the world matrix of the particle system
  63417. * @param positionToUpdate is the position vector to update with the result
  63418. * @param particle is the particle we are computed the position for
  63419. */
  63420. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63421. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  63422. };
  63423. /**
  63424. * Clones the current emitter and returns a copy of it
  63425. * @returns the new emitter
  63426. */
  63427. PointParticleEmitter.prototype.clone = function () {
  63428. var newOne = new PointParticleEmitter();
  63429. BABYLON.Tools.DeepCopy(this, newOne);
  63430. return newOne;
  63431. };
  63432. /**
  63433. * Called by the GPUParticleSystem to setup the update shader
  63434. * @param effect defines the update shader
  63435. */
  63436. PointParticleEmitter.prototype.applyToShader = function (effect) {
  63437. effect.setVector3("direction1", this.direction1);
  63438. effect.setVector3("direction2", this.direction2);
  63439. };
  63440. /**
  63441. * Returns a string to use to update the GPU particles update shader
  63442. * @returns a string containng the defines string
  63443. */
  63444. PointParticleEmitter.prototype.getEffectDefines = function () {
  63445. return "#define POINTEMITTER";
  63446. };
  63447. /**
  63448. * Returns the string "PointParticleEmitter"
  63449. * @returns a string containing the class name
  63450. */
  63451. PointParticleEmitter.prototype.getClassName = function () {
  63452. return "PointParticleEmitter";
  63453. };
  63454. /**
  63455. * Serializes the particle system to a JSON object.
  63456. * @returns the JSON object
  63457. */
  63458. PointParticleEmitter.prototype.serialize = function () {
  63459. var serializationObject = {};
  63460. serializationObject.type = this.getClassName();
  63461. serializationObject.direction1 = this.direction1.asArray();
  63462. serializationObject.direction2 = this.direction2.asArray();
  63463. return serializationObject;
  63464. };
  63465. /**
  63466. * Parse properties from a JSON object
  63467. * @param serializationObject defines the JSON object
  63468. */
  63469. PointParticleEmitter.prototype.parse = function (serializationObject) {
  63470. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  63471. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  63472. };
  63473. return PointParticleEmitter;
  63474. }());
  63475. BABYLON.PointParticleEmitter = PointParticleEmitter;
  63476. })(BABYLON || (BABYLON = {}));
  63477. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  63478. var BABYLON;
  63479. (function (BABYLON) {
  63480. // Adds the parsers to the scene parsers.
  63481. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  63482. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  63483. if (!individualParser) {
  63484. return;
  63485. }
  63486. // Particles Systems
  63487. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63488. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63489. var parsedParticleSystem = parsedData.particleSystems[index];
  63490. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  63491. }
  63492. }
  63493. });
  63494. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  63495. if (parsedParticleSystem.activeParticleCount) {
  63496. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63497. return ps;
  63498. }
  63499. else {
  63500. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63501. return ps;
  63502. }
  63503. });
  63504. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  63505. if (uniformsNames === void 0) { uniformsNames = []; }
  63506. if (samplers === void 0) { samplers = []; }
  63507. if (defines === void 0) { defines = ""; }
  63508. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  63509. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  63510. if (defines.indexOf(" BILLBOARD") === -1) {
  63511. defines += "\n#define BILLBOARD\n";
  63512. }
  63513. if (samplers.indexOf("diffuseSampler") === -1) {
  63514. samplers.push("diffuseSampler");
  63515. }
  63516. return this.createEffect({
  63517. vertex: "particles",
  63518. fragmentElement: fragmentName
  63519. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  63520. };
  63521. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  63522. var results = new Array();
  63523. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  63524. var particleSystem = this.getScene().particleSystems[index];
  63525. if (particleSystem.emitter === this) {
  63526. results.push(particleSystem);
  63527. }
  63528. }
  63529. return results;
  63530. };
  63531. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  63532. var results = new Array();
  63533. var descendants = this.getDescendants();
  63534. descendants.push(this);
  63535. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  63536. var particleSystem = this.getScene().particleSystems[index];
  63537. var emitter = particleSystem.emitter;
  63538. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  63539. results.push(particleSystem);
  63540. }
  63541. }
  63542. return results;
  63543. };
  63544. })(BABYLON || (BABYLON = {}));
  63545. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  63546. var BABYLON;
  63547. (function (BABYLON) {
  63548. /**
  63549. * Type of sub emitter
  63550. */
  63551. var SubEmitterType;
  63552. (function (SubEmitterType) {
  63553. /**
  63554. * Attached to the particle over it's lifetime
  63555. */
  63556. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  63557. /**
  63558. * Created when the particle dies
  63559. */
  63560. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  63561. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  63562. /**
  63563. * Sub emitter class used to emit particles from an existing particle
  63564. */
  63565. var SubEmitter = /** @class */ (function () {
  63566. /**
  63567. * Creates a sub emitter
  63568. * @param particleSystem the particle system to be used by the sub emitter
  63569. */
  63570. function SubEmitter(
  63571. /**
  63572. * the particle system to be used by the sub emitter
  63573. */
  63574. particleSystem) {
  63575. this.particleSystem = particleSystem;
  63576. /**
  63577. * Type of the submitter (Default: END)
  63578. */
  63579. this.type = SubEmitterType.END;
  63580. /**
  63581. * 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)
  63582. * Note: This only is supported when using an emitter of type Mesh
  63583. */
  63584. this.inheritDirection = false;
  63585. /**
  63586. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  63587. */
  63588. this.inheritedVelocityAmount = 0;
  63589. // Create mesh as emitter to support rotation
  63590. if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
  63591. particleSystem.emitter = new BABYLON.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
  63592. }
  63593. // Automatically dispose of subemitter when system is disposed
  63594. particleSystem.onDisposeObservable.add(function () {
  63595. if (particleSystem.emitter && particleSystem.emitter.dispose) {
  63596. particleSystem.emitter.dispose();
  63597. }
  63598. });
  63599. }
  63600. /**
  63601. * Clones the sub emitter
  63602. * @returns the cloned sub emitter
  63603. */
  63604. SubEmitter.prototype.clone = function () {
  63605. // Clone particle system
  63606. var emitter = this.particleSystem.emitter;
  63607. if (!emitter) {
  63608. emitter = new BABYLON.Vector3();
  63609. }
  63610. else if (emitter instanceof BABYLON.Vector3) {
  63611. emitter = emitter.clone();
  63612. }
  63613. else if (emitter instanceof BABYLON.AbstractMesh) {
  63614. emitter = new BABYLON.Mesh("", emitter.getScene());
  63615. emitter.isVisible = false;
  63616. }
  63617. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  63618. // Clone properties
  63619. clone.type = this.type;
  63620. clone.inheritDirection = this.inheritDirection;
  63621. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  63622. clone.particleSystem._disposeEmitterOnDispose = true;
  63623. clone.particleSystem.disposeOnStop = true;
  63624. return clone;
  63625. };
  63626. /**
  63627. * Serialize current object to a JSON object
  63628. * @returns the serialized object
  63629. */
  63630. SubEmitter.prototype.serialize = function () {
  63631. var serializationObject = {};
  63632. serializationObject.type = this.type;
  63633. serializationObject.inheritDirection = this.inheritDirection;
  63634. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  63635. serializationObject.particleSystem = this.particleSystem.serialize();
  63636. return serializationObject;
  63637. };
  63638. /**
  63639. * Creates a new SubEmitter from a serialized JSON version
  63640. * @param serializationObject defines the JSON object to read from
  63641. * @param scene defines the hosting scene
  63642. * @param rootUrl defines the rootUrl for data loading
  63643. * @returns a new SubEmitter
  63644. */
  63645. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  63646. var system = serializationObject.particleSystem;
  63647. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  63648. subEmitter.type = serializationObject.type;
  63649. subEmitter.inheritDirection = serializationObject.inheritDirection;
  63650. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  63651. subEmitter.particleSystem._isSubEmitter = true;
  63652. return subEmitter;
  63653. };
  63654. /** Release associated resources */
  63655. SubEmitter.prototype.dispose = function () {
  63656. this.particleSystem.dispose();
  63657. };
  63658. return SubEmitter;
  63659. }());
  63660. BABYLON.SubEmitter = SubEmitter;
  63661. })(BABYLON || (BABYLON = {}));
  63662. //# sourceMappingURL=babylon.subEmitter.js.map
  63663. var BABYLON;
  63664. (function (BABYLON) {
  63665. /**
  63666. * 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.
  63667. *
  63668. * This returned material effects how the mesh will look based on the code in the shaders.
  63669. *
  63670. * @see http://doc.babylonjs.com/how_to/shader_material
  63671. */
  63672. var ShaderMaterial = /** @class */ (function (_super) {
  63673. __extends(ShaderMaterial, _super);
  63674. /**
  63675. * Instantiate a new shader material.
  63676. * 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.
  63677. * This returned material effects how the mesh will look based on the code in the shaders.
  63678. * @see http://doc.babylonjs.com/how_to/shader_material
  63679. * @param name Define the name of the material in the scene
  63680. * @param scene Define the scene the material belongs to
  63681. * @param shaderPath Defines the route to the shader code in one of three ways:
  63682. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  63683. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  63684. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  63685. * @param options Define the options used to create the shader
  63686. */
  63687. function ShaderMaterial(name, scene, shaderPath, options) {
  63688. if (options === void 0) { options = {}; }
  63689. var _this = _super.call(this, name, scene) || this;
  63690. _this._textures = {};
  63691. _this._textureArrays = {};
  63692. _this._floats = {};
  63693. _this._ints = {};
  63694. _this._floatsArrays = {};
  63695. _this._colors3 = {};
  63696. _this._colors3Arrays = {};
  63697. _this._colors4 = {};
  63698. _this._vectors2 = {};
  63699. _this._vectors3 = {};
  63700. _this._vectors4 = {};
  63701. _this._matrices = {};
  63702. _this._matrices3x3 = {};
  63703. _this._matrices2x2 = {};
  63704. _this._vectors2Arrays = {};
  63705. _this._vectors3Arrays = {};
  63706. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  63707. _this._shaderPath = shaderPath;
  63708. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  63709. return _this;
  63710. }
  63711. /**
  63712. * Gets the current class name of the material e.g. "ShaderMaterial"
  63713. * Mainly use in serialization.
  63714. * @returns the class name
  63715. */
  63716. ShaderMaterial.prototype.getClassName = function () {
  63717. return "ShaderMaterial";
  63718. };
  63719. /**
  63720. * Specifies if the material will require alpha blending
  63721. * @returns a boolean specifying if alpha blending is needed
  63722. */
  63723. ShaderMaterial.prototype.needAlphaBlending = function () {
  63724. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  63725. };
  63726. /**
  63727. * Specifies if this material should be rendered in alpha test mode
  63728. * @returns a boolean specifying if an alpha test is needed.
  63729. */
  63730. ShaderMaterial.prototype.needAlphaTesting = function () {
  63731. return this._options.needAlphaTesting;
  63732. };
  63733. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  63734. if (this._options.uniforms.indexOf(uniformName) === -1) {
  63735. this._options.uniforms.push(uniformName);
  63736. }
  63737. };
  63738. /**
  63739. * Set a texture in the shader.
  63740. * @param name Define the name of the uniform samplers as defined in the shader
  63741. * @param texture Define the texture to bind to this sampler
  63742. * @return the material itself allowing "fluent" like uniform updates
  63743. */
  63744. ShaderMaterial.prototype.setTexture = function (name, texture) {
  63745. if (this._options.samplers.indexOf(name) === -1) {
  63746. this._options.samplers.push(name);
  63747. }
  63748. this._textures[name] = texture;
  63749. return this;
  63750. };
  63751. /**
  63752. * Set a texture array in the shader.
  63753. * @param name Define the name of the uniform sampler array as defined in the shader
  63754. * @param textures Define the list of textures to bind to this sampler
  63755. * @return the material itself allowing "fluent" like uniform updates
  63756. */
  63757. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  63758. if (this._options.samplers.indexOf(name) === -1) {
  63759. this._options.samplers.push(name);
  63760. }
  63761. this._checkUniform(name);
  63762. this._textureArrays[name] = textures;
  63763. return this;
  63764. };
  63765. /**
  63766. * Set a float in the shader.
  63767. * @param name Define the name of the uniform as defined in the shader
  63768. * @param value Define the value to give to the uniform
  63769. * @return the material itself allowing "fluent" like uniform updates
  63770. */
  63771. ShaderMaterial.prototype.setFloat = function (name, value) {
  63772. this._checkUniform(name);
  63773. this._floats[name] = value;
  63774. return this;
  63775. };
  63776. /**
  63777. * Set a int in the shader.
  63778. * @param name Define the name of the uniform as defined in the shader
  63779. * @param value Define the value to give to the uniform
  63780. * @return the material itself allowing "fluent" like uniform updates
  63781. */
  63782. ShaderMaterial.prototype.setInt = function (name, value) {
  63783. this._checkUniform(name);
  63784. this._ints[name] = value;
  63785. return this;
  63786. };
  63787. /**
  63788. * Set an array of floats in the shader.
  63789. * @param name Define the name of the uniform as defined in the shader
  63790. * @param value Define the value to give to the uniform
  63791. * @return the material itself allowing "fluent" like uniform updates
  63792. */
  63793. ShaderMaterial.prototype.setFloats = function (name, value) {
  63794. this._checkUniform(name);
  63795. this._floatsArrays[name] = value;
  63796. return this;
  63797. };
  63798. /**
  63799. * Set a vec3 in the shader from a Color3.
  63800. * @param name Define the name of the uniform as defined in the shader
  63801. * @param value Define the value to give to the uniform
  63802. * @return the material itself allowing "fluent" like uniform updates
  63803. */
  63804. ShaderMaterial.prototype.setColor3 = function (name, value) {
  63805. this._checkUniform(name);
  63806. this._colors3[name] = value;
  63807. return this;
  63808. };
  63809. /**
  63810. * Set a vec3 array in the shader from a Color3 array.
  63811. * @param name Define the name of the uniform as defined in the shader
  63812. * @param value Define the value to give to the uniform
  63813. * @return the material itself allowing "fluent" like uniform updates
  63814. */
  63815. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  63816. this._checkUniform(name);
  63817. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  63818. color.toArray(arr, arr.length);
  63819. return arr;
  63820. }, []);
  63821. return this;
  63822. };
  63823. /**
  63824. * Set a vec4 in the shader from a Color4.
  63825. * @param name Define the name of the uniform as defined in the shader
  63826. * @param value Define the value to give to the uniform
  63827. * @return the material itself allowing "fluent" like uniform updates
  63828. */
  63829. ShaderMaterial.prototype.setColor4 = function (name, value) {
  63830. this._checkUniform(name);
  63831. this._colors4[name] = value;
  63832. return this;
  63833. };
  63834. /**
  63835. * Set a vec2 in the shader from a Vector2.
  63836. * @param name Define the name of the uniform as defined in the shader
  63837. * @param value Define the value to give to the uniform
  63838. * @return the material itself allowing "fluent" like uniform updates
  63839. */
  63840. ShaderMaterial.prototype.setVector2 = function (name, value) {
  63841. this._checkUniform(name);
  63842. this._vectors2[name] = value;
  63843. return this;
  63844. };
  63845. /**
  63846. * Set a vec3 in the shader from a Vector3.
  63847. * @param name Define the name of the uniform as defined in the shader
  63848. * @param value Define the value to give to the uniform
  63849. * @return the material itself allowing "fluent" like uniform updates
  63850. */
  63851. ShaderMaterial.prototype.setVector3 = function (name, value) {
  63852. this._checkUniform(name);
  63853. this._vectors3[name] = value;
  63854. return this;
  63855. };
  63856. /**
  63857. * Set a vec4 in the shader from a Vector4.
  63858. * @param name Define the name of the uniform as defined in the shader
  63859. * @param value Define the value to give to the uniform
  63860. * @return the material itself allowing "fluent" like uniform updates
  63861. */
  63862. ShaderMaterial.prototype.setVector4 = function (name, value) {
  63863. this._checkUniform(name);
  63864. this._vectors4[name] = value;
  63865. return this;
  63866. };
  63867. /**
  63868. * Set a mat4 in the shader from a Matrix.
  63869. * @param name Define the name of the uniform as defined in the shader
  63870. * @param value Define the value to give to the uniform
  63871. * @return the material itself allowing "fluent" like uniform updates
  63872. */
  63873. ShaderMaterial.prototype.setMatrix = function (name, value) {
  63874. this._checkUniform(name);
  63875. this._matrices[name] = value;
  63876. return this;
  63877. };
  63878. /**
  63879. * Set a mat3 in the shader from a Float32Array.
  63880. * @param name Define the name of the uniform as defined in the shader
  63881. * @param value Define the value to give to the uniform
  63882. * @return the material itself allowing "fluent" like uniform updates
  63883. */
  63884. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  63885. this._checkUniform(name);
  63886. this._matrices3x3[name] = value;
  63887. return this;
  63888. };
  63889. /**
  63890. * Set a mat2 in the shader from a Float32Array.
  63891. * @param name Define the name of the uniform as defined in the shader
  63892. * @param value Define the value to give to the uniform
  63893. * @return the material itself allowing "fluent" like uniform updates
  63894. */
  63895. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  63896. this._checkUniform(name);
  63897. this._matrices2x2[name] = value;
  63898. return this;
  63899. };
  63900. /**
  63901. * Set a vec2 array in the shader from a number array.
  63902. * @param name Define the name of the uniform as defined in the shader
  63903. * @param value Define the value to give to the uniform
  63904. * @return the material itself allowing "fluent" like uniform updates
  63905. */
  63906. ShaderMaterial.prototype.setArray2 = function (name, value) {
  63907. this._checkUniform(name);
  63908. this._vectors2Arrays[name] = value;
  63909. return this;
  63910. };
  63911. /**
  63912. * Set a vec3 array in the shader from a number array.
  63913. * @param name Define the name of the uniform as defined in the shader
  63914. * @param value Define the value to give to the uniform
  63915. * @return the material itself allowing "fluent" like uniform updates
  63916. */
  63917. ShaderMaterial.prototype.setArray3 = function (name, value) {
  63918. this._checkUniform(name);
  63919. this._vectors3Arrays[name] = value;
  63920. return this;
  63921. };
  63922. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  63923. if (!mesh) {
  63924. return true;
  63925. }
  63926. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  63927. return false;
  63928. }
  63929. return false;
  63930. };
  63931. /**
  63932. * Checks if the material is ready to render the requested mesh
  63933. * @param mesh Define the mesh to render
  63934. * @param useInstances Define whether or not the material is used with instances
  63935. * @returns true if ready, otherwise false
  63936. */
  63937. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  63938. var scene = this.getScene();
  63939. var engine = scene.getEngine();
  63940. if (!this.checkReadyOnEveryCall) {
  63941. if (this._renderId === scene.getRenderId()) {
  63942. if (this._checkCache(scene, mesh, useInstances)) {
  63943. return true;
  63944. }
  63945. }
  63946. }
  63947. // Instances
  63948. var defines = [];
  63949. var attribs = [];
  63950. var fallbacks = new BABYLON.EffectFallbacks();
  63951. for (var index = 0; index < this._options.defines.length; index++) {
  63952. defines.push(this._options.defines[index]);
  63953. }
  63954. for (var index = 0; index < this._options.attributes.length; index++) {
  63955. attribs.push(this._options.attributes[index]);
  63956. }
  63957. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  63958. attribs.push(BABYLON.VertexBuffer.ColorKind);
  63959. defines.push("#define VERTEXCOLOR");
  63960. }
  63961. if (useInstances) {
  63962. defines.push("#define INSTANCES");
  63963. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  63964. }
  63965. // Bones
  63966. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  63967. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63968. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63969. if (mesh.numBoneInfluencers > 4) {
  63970. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63971. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63972. }
  63973. var skeleton = mesh.skeleton;
  63974. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63975. fallbacks.addCPUSkinningFallback(0, mesh);
  63976. if (skeleton.isUsingTextureForMatrices) {
  63977. defines.push("#define BONETEXTURE");
  63978. if (this._options.uniforms.indexOf("boneTextureWidth") === -1) {
  63979. this._options.uniforms.push("boneTextureWidth");
  63980. }
  63981. if (this._options.samplers.indexOf("boneSampler") === -1) {
  63982. this._options.samplers.push("boneSampler");
  63983. }
  63984. }
  63985. else {
  63986. defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
  63987. if (this._options.uniforms.indexOf("mBones") === -1) {
  63988. this._options.uniforms.push("mBones");
  63989. }
  63990. }
  63991. }
  63992. else {
  63993. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63994. }
  63995. // Textures
  63996. for (var name in this._textures) {
  63997. if (!this._textures[name].isReady()) {
  63998. return false;
  63999. }
  64000. }
  64001. // Alpha test
  64002. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  64003. defines.push("#define ALPHATEST");
  64004. }
  64005. var previousEffect = this._effect;
  64006. var join = defines.join("\n");
  64007. this._effect = engine.createEffect(this._shaderPath, {
  64008. attributes: attribs,
  64009. uniformsNames: this._options.uniforms,
  64010. uniformBuffersNames: this._options.uniformBuffers,
  64011. samplers: this._options.samplers,
  64012. defines: join,
  64013. fallbacks: fallbacks,
  64014. onCompiled: this.onCompiled,
  64015. onError: this.onError
  64016. }, engine);
  64017. if (!this._effect.isReady()) {
  64018. return false;
  64019. }
  64020. if (previousEffect !== this._effect) {
  64021. scene.resetCachedMaterial();
  64022. }
  64023. this._renderId = scene.getRenderId();
  64024. return true;
  64025. };
  64026. /**
  64027. * Binds the world matrix to the material
  64028. * @param world defines the world transformation matrix
  64029. */
  64030. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  64031. var scene = this.getScene();
  64032. if (!this._effect) {
  64033. return;
  64034. }
  64035. if (this._options.uniforms.indexOf("world") !== -1) {
  64036. this._effect.setMatrix("world", world);
  64037. }
  64038. if (this._options.uniforms.indexOf("worldView") !== -1) {
  64039. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  64040. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  64041. }
  64042. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  64043. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  64044. }
  64045. };
  64046. /**
  64047. * Binds the material to the mesh
  64048. * @param world defines the world transformation matrix
  64049. * @param mesh defines the mesh to bind the material to
  64050. */
  64051. ShaderMaterial.prototype.bind = function (world, mesh) {
  64052. // Std values
  64053. this.bindOnlyWorldMatrix(world);
  64054. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  64055. if (this._options.uniforms.indexOf("view") !== -1) {
  64056. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  64057. }
  64058. if (this._options.uniforms.indexOf("projection") !== -1) {
  64059. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  64060. }
  64061. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  64062. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  64063. }
  64064. // Bones
  64065. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  64066. var name;
  64067. // Texture
  64068. for (name in this._textures) {
  64069. this._effect.setTexture(name, this._textures[name]);
  64070. }
  64071. // Texture arrays
  64072. for (name in this._textureArrays) {
  64073. this._effect.setTextureArray(name, this._textureArrays[name]);
  64074. }
  64075. // Int
  64076. for (name in this._ints) {
  64077. this._effect.setInt(name, this._ints[name]);
  64078. }
  64079. // Float
  64080. for (name in this._floats) {
  64081. this._effect.setFloat(name, this._floats[name]);
  64082. }
  64083. // Floats
  64084. for (name in this._floatsArrays) {
  64085. this._effect.setArray(name, this._floatsArrays[name]);
  64086. }
  64087. // Color3
  64088. for (name in this._colors3) {
  64089. this._effect.setColor3(name, this._colors3[name]);
  64090. }
  64091. for (name in this._colors3Arrays) {
  64092. this._effect.setArray3(name, this._colors3Arrays[name]);
  64093. }
  64094. // Color4
  64095. for (name in this._colors4) {
  64096. var color = this._colors4[name];
  64097. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64098. }
  64099. // Vector2
  64100. for (name in this._vectors2) {
  64101. this._effect.setVector2(name, this._vectors2[name]);
  64102. }
  64103. // Vector3
  64104. for (name in this._vectors3) {
  64105. this._effect.setVector3(name, this._vectors3[name]);
  64106. }
  64107. // Vector4
  64108. for (name in this._vectors4) {
  64109. this._effect.setVector4(name, this._vectors4[name]);
  64110. }
  64111. // Matrix
  64112. for (name in this._matrices) {
  64113. this._effect.setMatrix(name, this._matrices[name]);
  64114. }
  64115. // Matrix 3x3
  64116. for (name in this._matrices3x3) {
  64117. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  64118. }
  64119. // Matrix 2x2
  64120. for (name in this._matrices2x2) {
  64121. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  64122. }
  64123. // Vector2Array
  64124. for (name in this._vectors2Arrays) {
  64125. this._effect.setArray2(name, this._vectors2Arrays[name]);
  64126. }
  64127. // Vector3Array
  64128. for (name in this._vectors3Arrays) {
  64129. this._effect.setArray3(name, this._vectors3Arrays[name]);
  64130. }
  64131. }
  64132. this._afterBind(mesh);
  64133. };
  64134. /**
  64135. * Gets the active textures from the material
  64136. * @returns an array of textures
  64137. */
  64138. ShaderMaterial.prototype.getActiveTextures = function () {
  64139. var activeTextures = _super.prototype.getActiveTextures.call(this);
  64140. for (var name in this._textures) {
  64141. activeTextures.push(this._textures[name]);
  64142. }
  64143. for (var name in this._textureArrays) {
  64144. var array = this._textureArrays[name];
  64145. for (var index = 0; index < array.length; index++) {
  64146. activeTextures.push(array[index]);
  64147. }
  64148. }
  64149. return activeTextures;
  64150. };
  64151. /**
  64152. * Specifies if the material uses a texture
  64153. * @param texture defines the texture to check against the material
  64154. * @returns a boolean specifying if the material uses the texture
  64155. */
  64156. ShaderMaterial.prototype.hasTexture = function (texture) {
  64157. if (_super.prototype.hasTexture.call(this, texture)) {
  64158. return true;
  64159. }
  64160. for (var name in this._textures) {
  64161. if (this._textures[name] === texture) {
  64162. return true;
  64163. }
  64164. }
  64165. for (var name in this._textureArrays) {
  64166. var array = this._textureArrays[name];
  64167. for (var index = 0; index < array.length; index++) {
  64168. if (array[index] === texture) {
  64169. return true;
  64170. }
  64171. }
  64172. }
  64173. return false;
  64174. };
  64175. /**
  64176. * Makes a duplicate of the material, and gives it a new name
  64177. * @param name defines the new name for the duplicated material
  64178. * @returns the cloned material
  64179. */
  64180. ShaderMaterial.prototype.clone = function (name) {
  64181. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  64182. return newShaderMaterial;
  64183. };
  64184. /**
  64185. * Disposes the material
  64186. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  64187. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  64188. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  64189. */
  64190. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
  64191. if (forceDisposeTextures) {
  64192. var name;
  64193. for (name in this._textures) {
  64194. this._textures[name].dispose();
  64195. }
  64196. for (name in this._textureArrays) {
  64197. var array = this._textureArrays[name];
  64198. for (var index = 0; index < array.length; index++) {
  64199. array[index].dispose();
  64200. }
  64201. }
  64202. }
  64203. this._textures = {};
  64204. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  64205. };
  64206. /**
  64207. * Serializes this material in a JSON representation
  64208. * @returns the serialized material object
  64209. */
  64210. ShaderMaterial.prototype.serialize = function () {
  64211. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64212. serializationObject.customType = "BABYLON.ShaderMaterial";
  64213. serializationObject.options = this._options;
  64214. serializationObject.shaderPath = this._shaderPath;
  64215. var name;
  64216. // Texture
  64217. serializationObject.textures = {};
  64218. for (name in this._textures) {
  64219. serializationObject.textures[name] = this._textures[name].serialize();
  64220. }
  64221. // Texture arrays
  64222. serializationObject.textureArrays = {};
  64223. for (name in this._textureArrays) {
  64224. serializationObject.textureArrays[name] = [];
  64225. var array = this._textureArrays[name];
  64226. for (var index = 0; index < array.length; index++) {
  64227. serializationObject.textureArrays[name].push(array[index].serialize());
  64228. }
  64229. }
  64230. // Float
  64231. serializationObject.floats = {};
  64232. for (name in this._floats) {
  64233. serializationObject.floats[name] = this._floats[name];
  64234. }
  64235. // Float s
  64236. serializationObject.FloatArrays = {};
  64237. for (name in this._floatsArrays) {
  64238. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  64239. }
  64240. // Color3
  64241. serializationObject.colors3 = {};
  64242. for (name in this._colors3) {
  64243. serializationObject.colors3[name] = this._colors3[name].asArray();
  64244. }
  64245. // Color3 array
  64246. serializationObject.colors3Arrays = {};
  64247. for (name in this._colors3Arrays) {
  64248. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  64249. }
  64250. // Color4
  64251. serializationObject.colors4 = {};
  64252. for (name in this._colors4) {
  64253. serializationObject.colors4[name] = this._colors4[name].asArray();
  64254. }
  64255. // Vector2
  64256. serializationObject.vectors2 = {};
  64257. for (name in this._vectors2) {
  64258. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  64259. }
  64260. // Vector3
  64261. serializationObject.vectors3 = {};
  64262. for (name in this._vectors3) {
  64263. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  64264. }
  64265. // Vector4
  64266. serializationObject.vectors4 = {};
  64267. for (name in this._vectors4) {
  64268. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  64269. }
  64270. // Matrix
  64271. serializationObject.matrices = {};
  64272. for (name in this._matrices) {
  64273. serializationObject.matrices[name] = this._matrices[name].asArray();
  64274. }
  64275. // Matrix 3x3
  64276. serializationObject.matrices3x3 = {};
  64277. for (name in this._matrices3x3) {
  64278. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  64279. }
  64280. // Matrix 2x2
  64281. serializationObject.matrices2x2 = {};
  64282. for (name in this._matrices2x2) {
  64283. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  64284. }
  64285. // Vector2Array
  64286. serializationObject.vectors2Arrays = {};
  64287. for (name in this._vectors2Arrays) {
  64288. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  64289. }
  64290. // Vector3Array
  64291. serializationObject.vectors3Arrays = {};
  64292. for (name in this._vectors3Arrays) {
  64293. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  64294. }
  64295. return serializationObject;
  64296. };
  64297. /**
  64298. * Creates a shader material from parsed shader material data
  64299. * @param source defines the JSON represnetation of the material
  64300. * @param scene defines the hosting scene
  64301. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  64302. * @returns a new material
  64303. */
  64304. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  64305. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  64306. var name;
  64307. // Texture
  64308. for (name in source.textures) {
  64309. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  64310. }
  64311. // Texture arrays
  64312. for (name in source.textureArrays) {
  64313. var array = source.textureArrays[name];
  64314. var textureArray = new Array();
  64315. for (var index = 0; index < array.length; index++) {
  64316. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  64317. }
  64318. material.setTextureArray(name, textureArray);
  64319. }
  64320. // Float
  64321. for (name in source.floats) {
  64322. material.setFloat(name, source.floats[name]);
  64323. }
  64324. // Float s
  64325. for (name in source.floatsArrays) {
  64326. material.setFloats(name, source.floatsArrays[name]);
  64327. }
  64328. // Color3
  64329. for (name in source.colors3) {
  64330. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  64331. }
  64332. // Color3 arrays
  64333. for (name in source.colors3Arrays) {
  64334. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  64335. if (i % 3 === 0) {
  64336. arr.push([num]);
  64337. }
  64338. else {
  64339. arr[arr.length - 1].push(num);
  64340. }
  64341. return arr;
  64342. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  64343. material.setColor3Array(name, colors);
  64344. }
  64345. // Color4
  64346. for (name in source.colors4) {
  64347. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  64348. }
  64349. // Vector2
  64350. for (name in source.vectors2) {
  64351. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  64352. }
  64353. // Vector3
  64354. for (name in source.vectors3) {
  64355. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  64356. }
  64357. // Vector4
  64358. for (name in source.vectors4) {
  64359. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  64360. }
  64361. // Matrix
  64362. for (name in source.matrices) {
  64363. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  64364. }
  64365. // Matrix 3x3
  64366. for (name in source.matrices3x3) {
  64367. material.setMatrix3x3(name, source.matrices3x3[name]);
  64368. }
  64369. // Matrix 2x2
  64370. for (name in source.matrices2x2) {
  64371. material.setMatrix2x2(name, source.matrices2x2[name]);
  64372. }
  64373. // Vector2Array
  64374. for (name in source.vectors2Arrays) {
  64375. material.setArray2(name, source.vectors2Arrays[name]);
  64376. }
  64377. // Vector3Array
  64378. for (name in source.vectors3Arrays) {
  64379. material.setArray3(name, source.vectors3Arrays[name]);
  64380. }
  64381. return material;
  64382. };
  64383. return ShaderMaterial;
  64384. }(BABYLON.Material));
  64385. BABYLON.ShaderMaterial = ShaderMaterial;
  64386. })(BABYLON || (BABYLON = {}));
  64387. //# sourceMappingURL=babylon.shaderMaterial.js.map
  64388. var BABYLON;
  64389. (function (BABYLON) {
  64390. /**
  64391. * Mesh representing the gorund
  64392. */
  64393. var GroundMesh = /** @class */ (function (_super) {
  64394. __extends(GroundMesh, _super);
  64395. function GroundMesh(name, scene) {
  64396. var _this = _super.call(this, name, scene) || this;
  64397. /** If octree should be generated */
  64398. _this.generateOctree = false;
  64399. return _this;
  64400. }
  64401. /**
  64402. * "GroundMesh"
  64403. * @returns "GroundMesh"
  64404. */
  64405. GroundMesh.prototype.getClassName = function () {
  64406. return "GroundMesh";
  64407. };
  64408. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  64409. /**
  64410. * The minimum of x and y subdivisions
  64411. */
  64412. get: function () {
  64413. return Math.min(this._subdivisionsX, this._subdivisionsY);
  64414. },
  64415. enumerable: true,
  64416. configurable: true
  64417. });
  64418. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  64419. /**
  64420. * X subdivisions
  64421. */
  64422. get: function () {
  64423. return this._subdivisionsX;
  64424. },
  64425. enumerable: true,
  64426. configurable: true
  64427. });
  64428. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  64429. /**
  64430. * Y subdivisions
  64431. */
  64432. get: function () {
  64433. return this._subdivisionsY;
  64434. },
  64435. enumerable: true,
  64436. configurable: true
  64437. });
  64438. /**
  64439. * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
  64440. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  64441. * @param chunksCount the number of subdivisions for x and y
  64442. * @param octreeBlocksSize (Default: 32)
  64443. */
  64444. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  64445. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  64446. this._subdivisionsX = chunksCount;
  64447. this._subdivisionsY = chunksCount;
  64448. this.subdivide(chunksCount);
  64449. // Call the octree system optimization if it is defined.
  64450. var thisAsAny = this;
  64451. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  64452. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  64453. }
  64454. };
  64455. /**
  64456. * Returns a height (y) value in the Worl system :
  64457. * the ground altitude at the coordinates (x, z) expressed in the World system.
  64458. * @param x x coordinate
  64459. * @param z z coordinate
  64460. * @returns the ground y position if (x, z) are outside the ground surface.
  64461. */
  64462. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  64463. var world = this.getWorldMatrix();
  64464. var invMat = BABYLON.Tmp.Matrix[5];
  64465. world.invertToRef(invMat);
  64466. var tmpVect = BABYLON.Tmp.Vector3[8];
  64467. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  64468. x = tmpVect.x;
  64469. z = tmpVect.z;
  64470. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  64471. return this.position.y;
  64472. }
  64473. if (!this._heightQuads || this._heightQuads.length == 0) {
  64474. this._initHeightQuads();
  64475. this._computeHeightQuads();
  64476. }
  64477. var facet = this._getFacetAt(x, z);
  64478. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  64479. // return y in the World system
  64480. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  64481. return tmpVect.y;
  64482. };
  64483. /**
  64484. * Returns a normalized vector (Vector3) orthogonal to the ground
  64485. * at the ground coordinates (x, z) expressed in the World system.
  64486. * @param x x coordinate
  64487. * @param z z coordinate
  64488. * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  64489. */
  64490. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  64491. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  64492. this.getNormalAtCoordinatesToRef(x, z, normal);
  64493. return normal;
  64494. };
  64495. /**
  64496. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  64497. * at the ground coordinates (x, z) expressed in the World system.
  64498. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  64499. * @param x x coordinate
  64500. * @param z z coordinate
  64501. * @param ref vector to store the result
  64502. * @returns the GroundMesh.
  64503. */
  64504. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  64505. var world = this.getWorldMatrix();
  64506. var tmpMat = BABYLON.Tmp.Matrix[5];
  64507. world.invertToRef(tmpMat);
  64508. var tmpVect = BABYLON.Tmp.Vector3[8];
  64509. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  64510. x = tmpVect.x;
  64511. z = tmpVect.z;
  64512. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  64513. return this;
  64514. }
  64515. if (!this._heightQuads || this._heightQuads.length == 0) {
  64516. this._initHeightQuads();
  64517. this._computeHeightQuads();
  64518. }
  64519. var facet = this._getFacetAt(x, z);
  64520. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  64521. return this;
  64522. };
  64523. /**
  64524. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  64525. * if the ground has been updated.
  64526. * This can be used in the render loop.
  64527. * @returns the GroundMesh.
  64528. */
  64529. GroundMesh.prototype.updateCoordinateHeights = function () {
  64530. if (!this._heightQuads || this._heightQuads.length == 0) {
  64531. this._initHeightQuads();
  64532. }
  64533. this._computeHeightQuads();
  64534. return this;
  64535. };
  64536. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  64537. GroundMesh.prototype._getFacetAt = function (x, z) {
  64538. // retrieve col and row from x, z coordinates in the ground local system
  64539. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  64540. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  64541. var quad = this._heightQuads[row * this._subdivisionsX + col];
  64542. var facet;
  64543. if (z < quad.slope.x * x + quad.slope.y) {
  64544. facet = quad.facet1;
  64545. }
  64546. else {
  64547. facet = quad.facet2;
  64548. }
  64549. return facet;
  64550. };
  64551. // Creates and populates the heightMap array with "facet" elements :
  64552. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  64553. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  64554. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  64555. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  64556. // Returns the GroundMesh.
  64557. GroundMesh.prototype._initHeightQuads = function () {
  64558. var subdivisionsX = this._subdivisionsX;
  64559. var subdivisionsY = this._subdivisionsY;
  64560. this._heightQuads = new Array();
  64561. for (var row = 0; row < subdivisionsY; row++) {
  64562. for (var col = 0; col < subdivisionsX; col++) {
  64563. 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) };
  64564. this._heightQuads[row * subdivisionsX + col] = quad;
  64565. }
  64566. }
  64567. return this;
  64568. };
  64569. // Compute each quad element values and update the the heightMap array :
  64570. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  64571. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  64572. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  64573. // Returns the GroundMesh.
  64574. GroundMesh.prototype._computeHeightQuads = function () {
  64575. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64576. if (!positions) {
  64577. return this;
  64578. }
  64579. var v1 = BABYLON.Tmp.Vector3[3];
  64580. var v2 = BABYLON.Tmp.Vector3[2];
  64581. var v3 = BABYLON.Tmp.Vector3[1];
  64582. var v4 = BABYLON.Tmp.Vector3[0];
  64583. var v1v2 = BABYLON.Tmp.Vector3[4];
  64584. var v1v3 = BABYLON.Tmp.Vector3[5];
  64585. var v1v4 = BABYLON.Tmp.Vector3[6];
  64586. var norm1 = BABYLON.Tmp.Vector3[7];
  64587. var norm2 = BABYLON.Tmp.Vector3[8];
  64588. var i = 0;
  64589. var j = 0;
  64590. var k = 0;
  64591. var cd = 0; // 2D slope coefficient : z = cd * x + h
  64592. var h = 0;
  64593. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  64594. var d2 = 0;
  64595. var subdivisionsX = this._subdivisionsX;
  64596. var subdivisionsY = this._subdivisionsY;
  64597. for (var row = 0; row < subdivisionsY; row++) {
  64598. for (var col = 0; col < subdivisionsX; col++) {
  64599. i = col * 3;
  64600. j = row * (subdivisionsX + 1) * 3;
  64601. k = (row + 1) * (subdivisionsX + 1) * 3;
  64602. v1.x = positions[j + i];
  64603. v1.y = positions[j + i + 1];
  64604. v1.z = positions[j + i + 2];
  64605. v2.x = positions[j + i + 3];
  64606. v2.y = positions[j + i + 4];
  64607. v2.z = positions[j + i + 5];
  64608. v3.x = positions[k + i];
  64609. v3.y = positions[k + i + 1];
  64610. v3.z = positions[k + i + 2];
  64611. v4.x = positions[k + i + 3];
  64612. v4.y = positions[k + i + 4];
  64613. v4.z = positions[k + i + 5];
  64614. // 2D slope V1V4
  64615. cd = (v4.z - v1.z) / (v4.x - v1.x);
  64616. h = v1.z - cd * v1.x; // v1 belongs to the slope
  64617. // facet equations :
  64618. // we compute each facet normal vector
  64619. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  64620. // we compute the value d by applying the equation to v1 which belongs to the plane
  64621. // then we store the facet equation in a Vector4
  64622. v2.subtractToRef(v1, v1v2);
  64623. v3.subtractToRef(v1, v1v3);
  64624. v4.subtractToRef(v1, v1v4);
  64625. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  64626. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  64627. norm1.normalize();
  64628. norm2.normalize();
  64629. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  64630. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  64631. var quad = this._heightQuads[row * subdivisionsX + col];
  64632. quad.slope.copyFromFloats(cd, h);
  64633. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  64634. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  64635. }
  64636. }
  64637. return this;
  64638. };
  64639. /**
  64640. * Serializes this ground mesh
  64641. * @param serializationObject object to write serialization to
  64642. */
  64643. GroundMesh.prototype.serialize = function (serializationObject) {
  64644. _super.prototype.serialize.call(this, serializationObject);
  64645. serializationObject.subdivisionsX = this._subdivisionsX;
  64646. serializationObject.subdivisionsY = this._subdivisionsY;
  64647. serializationObject.minX = this._minX;
  64648. serializationObject.maxX = this._maxX;
  64649. serializationObject.minZ = this._minZ;
  64650. serializationObject.maxZ = this._maxZ;
  64651. serializationObject.width = this._width;
  64652. serializationObject.height = this._height;
  64653. };
  64654. /**
  64655. * Parses a serialized ground mesh
  64656. * @param parsedMesh the serialized mesh
  64657. * @param scene the scene to create the ground mesh in
  64658. * @returns the created ground mesh
  64659. */
  64660. GroundMesh.Parse = function (parsedMesh, scene) {
  64661. var result = new GroundMesh(parsedMesh.name, scene);
  64662. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  64663. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  64664. result._minX = parsedMesh.minX;
  64665. result._maxX = parsedMesh.maxX;
  64666. result._minZ = parsedMesh.minZ;
  64667. result._maxZ = parsedMesh.maxZ;
  64668. result._width = parsedMesh.width;
  64669. result._height = parsedMesh.height;
  64670. return result;
  64671. };
  64672. return GroundMesh;
  64673. }(BABYLON.Mesh));
  64674. BABYLON.GroundMesh = GroundMesh;
  64675. })(BABYLON || (BABYLON = {}));
  64676. //# sourceMappingURL=babylon.groundMesh.js.map
  64677. var BABYLON;
  64678. (function (BABYLON) {
  64679. /**
  64680. * Creates an instance based on a source mesh.
  64681. */
  64682. var InstancedMesh = /** @class */ (function (_super) {
  64683. __extends(InstancedMesh, _super);
  64684. function InstancedMesh(name, source) {
  64685. var _this = _super.call(this, name, source.getScene()) || this;
  64686. /** @hidden */
  64687. _this._indexInSourceMeshInstanceArray = -1;
  64688. source.addInstance(_this);
  64689. _this._sourceMesh = source;
  64690. _this.position.copyFrom(source.position);
  64691. _this.rotation.copyFrom(source.rotation);
  64692. _this.scaling.copyFrom(source.scaling);
  64693. if (source.rotationQuaternion) {
  64694. _this.rotationQuaternion = source.rotationQuaternion.clone();
  64695. }
  64696. _this.infiniteDistance = source.infiniteDistance;
  64697. _this.setPivotMatrix(source.getPivotMatrix());
  64698. _this.refreshBoundingInfo();
  64699. _this._syncSubMeshes();
  64700. return _this;
  64701. }
  64702. /**
  64703. * Returns the string "InstancedMesh".
  64704. */
  64705. InstancedMesh.prototype.getClassName = function () {
  64706. return "InstancedMesh";
  64707. };
  64708. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  64709. // Methods
  64710. /**
  64711. * If the source mesh receives shadows
  64712. */
  64713. get: function () {
  64714. return this._sourceMesh.receiveShadows;
  64715. },
  64716. enumerable: true,
  64717. configurable: true
  64718. });
  64719. Object.defineProperty(InstancedMesh.prototype, "material", {
  64720. /**
  64721. * The material of the source mesh
  64722. */
  64723. get: function () {
  64724. return this._sourceMesh.material;
  64725. },
  64726. enumerable: true,
  64727. configurable: true
  64728. });
  64729. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  64730. /**
  64731. * Visibility of the source mesh
  64732. */
  64733. get: function () {
  64734. return this._sourceMesh.visibility;
  64735. },
  64736. enumerable: true,
  64737. configurable: true
  64738. });
  64739. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  64740. /**
  64741. * Skeleton of the source mesh
  64742. */
  64743. get: function () {
  64744. return this._sourceMesh.skeleton;
  64745. },
  64746. enumerable: true,
  64747. configurable: true
  64748. });
  64749. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  64750. /**
  64751. * Rendering ground id of the source mesh
  64752. */
  64753. get: function () {
  64754. return this._sourceMesh.renderingGroupId;
  64755. },
  64756. set: function (value) {
  64757. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  64758. return;
  64759. }
  64760. //no-op with warning
  64761. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  64762. },
  64763. enumerable: true,
  64764. configurable: true
  64765. });
  64766. /**
  64767. * Returns the total number of vertices (integer).
  64768. */
  64769. InstancedMesh.prototype.getTotalVertices = function () {
  64770. return this._sourceMesh.getTotalVertices();
  64771. };
  64772. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  64773. /**
  64774. * The source mesh of the instance
  64775. */
  64776. get: function () {
  64777. return this._sourceMesh;
  64778. },
  64779. enumerable: true,
  64780. configurable: true
  64781. });
  64782. /**
  64783. * Is this node ready to be used/rendered
  64784. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  64785. * @return {boolean} is it ready
  64786. */
  64787. InstancedMesh.prototype.isReady = function (completeCheck) {
  64788. if (completeCheck === void 0) { completeCheck = false; }
  64789. return this._sourceMesh.isReady(completeCheck, true);
  64790. };
  64791. /**
  64792. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  64793. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  64794. * @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.
  64795. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  64796. */
  64797. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  64798. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  64799. };
  64800. /**
  64801. * Sets the vertex data of the mesh geometry for the requested `kind`.
  64802. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  64803. * The `data` are either a numeric array either a Float32Array.
  64804. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  64805. * 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).
  64806. * Note that a new underlying VertexBuffer object is created each call.
  64807. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  64808. *
  64809. * Possible `kind` values :
  64810. * - BABYLON.VertexBuffer.PositionKind
  64811. * - BABYLON.VertexBuffer.UVKind
  64812. * - BABYLON.VertexBuffer.UV2Kind
  64813. * - BABYLON.VertexBuffer.UV3Kind
  64814. * - BABYLON.VertexBuffer.UV4Kind
  64815. * - BABYLON.VertexBuffer.UV5Kind
  64816. * - BABYLON.VertexBuffer.UV6Kind
  64817. * - BABYLON.VertexBuffer.ColorKind
  64818. * - BABYLON.VertexBuffer.MatricesIndicesKind
  64819. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  64820. * - BABYLON.VertexBuffer.MatricesWeightsKind
  64821. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  64822. *
  64823. * Returns the Mesh.
  64824. */
  64825. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  64826. if (this.sourceMesh) {
  64827. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  64828. }
  64829. return this.sourceMesh;
  64830. };
  64831. /**
  64832. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  64833. * If the mesh has no geometry, it is simply returned as it is.
  64834. * The `data` are either a numeric array either a Float32Array.
  64835. * No new underlying VertexBuffer object is created.
  64836. * 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.
  64837. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  64838. *
  64839. * Possible `kind` values :
  64840. * - BABYLON.VertexBuffer.PositionKind
  64841. * - BABYLON.VertexBuffer.UVKind
  64842. * - BABYLON.VertexBuffer.UV2Kind
  64843. * - BABYLON.VertexBuffer.UV3Kind
  64844. * - BABYLON.VertexBuffer.UV4Kind
  64845. * - BABYLON.VertexBuffer.UV5Kind
  64846. * - BABYLON.VertexBuffer.UV6Kind
  64847. * - BABYLON.VertexBuffer.ColorKind
  64848. * - BABYLON.VertexBuffer.MatricesIndicesKind
  64849. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  64850. * - BABYLON.VertexBuffer.MatricesWeightsKind
  64851. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  64852. *
  64853. * Returns the Mesh.
  64854. */
  64855. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  64856. if (this.sourceMesh) {
  64857. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  64858. }
  64859. return this.sourceMesh;
  64860. };
  64861. /**
  64862. * Sets the mesh indices.
  64863. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  64864. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  64865. * This method creates a new index buffer each call.
  64866. * Returns the Mesh.
  64867. */
  64868. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  64869. if (totalVertices === void 0) { totalVertices = null; }
  64870. if (this.sourceMesh) {
  64871. this.sourceMesh.setIndices(indices, totalVertices);
  64872. }
  64873. return this.sourceMesh;
  64874. };
  64875. /**
  64876. * Boolean : True if the mesh owns the requested kind of data.
  64877. */
  64878. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  64879. return this._sourceMesh.isVerticesDataPresent(kind);
  64880. };
  64881. /**
  64882. * Returns an array of indices (IndicesArray).
  64883. */
  64884. InstancedMesh.prototype.getIndices = function () {
  64885. return this._sourceMesh.getIndices();
  64886. };
  64887. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  64888. get: function () {
  64889. return this._sourceMesh._positions;
  64890. },
  64891. enumerable: true,
  64892. configurable: true
  64893. });
  64894. /**
  64895. * reconstructs and updates the BoundingInfo of the mesh.
  64896. * @returns the mesh.
  64897. */
  64898. InstancedMesh.prototype.refreshBoundingInfo = function () {
  64899. var meshBB = this._sourceMesh.getBoundingInfo();
  64900. if (this._boundingInfo) {
  64901. this._boundingInfo.reConstruct(meshBB.minimum, meshBB.maximum);
  64902. }
  64903. else {
  64904. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum, meshBB.maximum);
  64905. }
  64906. this._updateBoundingInfo();
  64907. return this;
  64908. };
  64909. /** @hidden */
  64910. InstancedMesh.prototype._preActivate = function () {
  64911. if (this._currentLOD) {
  64912. this._currentLOD._preActivate();
  64913. }
  64914. return this;
  64915. };
  64916. /** @hidden */
  64917. InstancedMesh.prototype._activate = function (renderId) {
  64918. if (this._currentLOD) {
  64919. this._currentLOD._registerInstanceForRenderId(this, renderId);
  64920. }
  64921. return this;
  64922. };
  64923. /**
  64924. * Returns the current associated LOD AbstractMesh.
  64925. */
  64926. InstancedMesh.prototype.getLOD = function (camera) {
  64927. if (!camera) {
  64928. return this;
  64929. }
  64930. var boundingInfo = this.getBoundingInfo();
  64931. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  64932. if (this._currentLOD === this.sourceMesh) {
  64933. return this;
  64934. }
  64935. return this._currentLOD;
  64936. };
  64937. /** @hidden */
  64938. InstancedMesh.prototype._syncSubMeshes = function () {
  64939. this.releaseSubMeshes();
  64940. if (this._sourceMesh.subMeshes) {
  64941. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  64942. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  64943. }
  64944. }
  64945. return this;
  64946. };
  64947. /** @hidden */
  64948. InstancedMesh.prototype._generatePointsArray = function () {
  64949. return this._sourceMesh._generatePointsArray();
  64950. };
  64951. /**
  64952. * Creates a new InstancedMesh from the current mesh.
  64953. * - name (string) : the cloned mesh name
  64954. * - newParent (optional Node) : the optional Node to parent the clone to.
  64955. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  64956. *
  64957. * Returns the clone.
  64958. */
  64959. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  64960. var result = this._sourceMesh.createInstance(name);
  64961. // Deep copy
  64962. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  64963. // Bounding info
  64964. this.refreshBoundingInfo();
  64965. // Parent
  64966. if (newParent) {
  64967. result.parent = newParent;
  64968. }
  64969. if (!doNotCloneChildren) {
  64970. // Children
  64971. for (var index = 0; index < this.getScene().meshes.length; index++) {
  64972. var mesh = this.getScene().meshes[index];
  64973. if (mesh.parent === this) {
  64974. mesh.clone(mesh.name, result);
  64975. }
  64976. }
  64977. }
  64978. result.computeWorldMatrix(true);
  64979. return result;
  64980. };
  64981. /**
  64982. * Disposes the InstancedMesh.
  64983. * Returns nothing.
  64984. */
  64985. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  64986. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  64987. // Remove from mesh
  64988. this._sourceMesh.removeInstance(this);
  64989. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  64990. };
  64991. return InstancedMesh;
  64992. }(BABYLON.AbstractMesh));
  64993. BABYLON.InstancedMesh = InstancedMesh;
  64994. })(BABYLON || (BABYLON = {}));
  64995. //# sourceMappingURL=babylon.instancedMesh.js.map
  64996. var BABYLON;
  64997. (function (BABYLON) {
  64998. /**
  64999. * Line mesh
  65000. * @see https://doc.babylonjs.com/babylon101/parametric_shapes
  65001. */
  65002. var LinesMesh = /** @class */ (function (_super) {
  65003. __extends(LinesMesh, _super);
  65004. /**
  65005. * Creates a new LinesMesh
  65006. * @param name defines the name
  65007. * @param scene defines the hosting scene
  65008. * @param parent defines the parent mesh if any
  65009. * @param source defines the optional source LinesMesh used to clone data from
  65010. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  65011. * When false, achieved by calling a clone(), also passing False.
  65012. * This will make creation of children, recursive.
  65013. * @param useVertexColor defines if this LinesMesh supports vertex color
  65014. * @param useVertexAlpha defines if this LinesMesh supports vertex alpha
  65015. */
  65016. function LinesMesh(name, scene, parent, source, doNotCloneChildren,
  65017. /**
  65018. * If vertex color should be applied to the mesh
  65019. */
  65020. useVertexColor,
  65021. /**
  65022. * If vertex alpha should be applied to the mesh
  65023. */
  65024. useVertexAlpha) {
  65025. if (scene === void 0) { scene = null; }
  65026. if (parent === void 0) { parent = null; }
  65027. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  65028. _this.useVertexColor = useVertexColor;
  65029. _this.useVertexAlpha = useVertexAlpha;
  65030. /**
  65031. * Color of the line (Default: White)
  65032. */
  65033. _this.color = new BABYLON.Color3(1, 1, 1);
  65034. /**
  65035. * Alpha of the line (Default: 1)
  65036. */
  65037. _this.alpha = 1;
  65038. if (source) {
  65039. _this.color = source.color.clone();
  65040. _this.alpha = source.alpha;
  65041. _this.useVertexColor = source.useVertexColor;
  65042. _this.useVertexAlpha = source.useVertexAlpha;
  65043. }
  65044. _this._intersectionThreshold = 0.1;
  65045. var defines = [];
  65046. var options = {
  65047. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  65048. uniforms: ["world", "viewProjection"],
  65049. needAlphaBlending: true,
  65050. defines: defines
  65051. };
  65052. if (useVertexAlpha === false) {
  65053. options.needAlphaBlending = false;
  65054. }
  65055. if (!useVertexColor) {
  65056. options.uniforms.push("color");
  65057. }
  65058. else {
  65059. options.defines.push("#define VERTEXCOLOR");
  65060. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  65061. }
  65062. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  65063. return _this;
  65064. }
  65065. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  65066. /**
  65067. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  65068. * This margin is expressed in world space coordinates, so its value may vary.
  65069. * Default value is 0.1
  65070. * @returns the intersection Threshold value.
  65071. */
  65072. get: function () {
  65073. return this._intersectionThreshold;
  65074. },
  65075. /**
  65076. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  65077. * This margin is expressed in world space coordinates, so its value may vary.
  65078. */
  65079. set: function (value) {
  65080. if (this._intersectionThreshold === value) {
  65081. return;
  65082. }
  65083. this._intersectionThreshold = value;
  65084. },
  65085. enumerable: true,
  65086. configurable: true
  65087. });
  65088. /**
  65089. * Returns the string "LineMesh"
  65090. */
  65091. LinesMesh.prototype.getClassName = function () {
  65092. return "LinesMesh";
  65093. };
  65094. Object.defineProperty(LinesMesh.prototype, "material", {
  65095. /**
  65096. * @hidden
  65097. */
  65098. get: function () {
  65099. return this._colorShader;
  65100. },
  65101. /**
  65102. * @hidden
  65103. */
  65104. set: function (value) {
  65105. // Do nothing
  65106. },
  65107. enumerable: true,
  65108. configurable: true
  65109. });
  65110. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  65111. /**
  65112. * @hidden
  65113. */
  65114. get: function () {
  65115. return false;
  65116. },
  65117. enumerable: true,
  65118. configurable: true
  65119. });
  65120. /** @hidden */
  65121. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  65122. if (!this._geometry) {
  65123. return this;
  65124. }
  65125. // VBOs
  65126. this._geometry._bind(this._colorShader.getEffect());
  65127. // Color
  65128. if (!this.useVertexColor) {
  65129. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  65130. }
  65131. return this;
  65132. };
  65133. /** @hidden */
  65134. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  65135. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  65136. return this;
  65137. }
  65138. var engine = this.getScene().getEngine();
  65139. // Draw order
  65140. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  65141. return this;
  65142. };
  65143. /**
  65144. * Disposes of the line mesh
  65145. * @param doNotRecurse If children should be disposed
  65146. */
  65147. LinesMesh.prototype.dispose = function (doNotRecurse) {
  65148. this._colorShader.dispose(false, false, true);
  65149. _super.prototype.dispose.call(this, doNotRecurse);
  65150. };
  65151. /**
  65152. * Returns a new LineMesh object cloned from the current one.
  65153. */
  65154. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  65155. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  65156. };
  65157. return LinesMesh;
  65158. }(BABYLON.Mesh));
  65159. BABYLON.LinesMesh = LinesMesh;
  65160. })(BABYLON || (BABYLON = {}));
  65161. //# sourceMappingURL=babylon.linesMesh.js.map
  65162. var BABYLON;
  65163. (function (BABYLON) {
  65164. /**
  65165. * This class implement a typical dictionary using a string as key and the generic type T as value.
  65166. * The underlying implementation relies on an associative array to ensure the best performances.
  65167. * The value can be anything including 'null' but except 'undefined'
  65168. */
  65169. var StringDictionary = /** @class */ (function () {
  65170. function StringDictionary() {
  65171. this._count = 0;
  65172. this._data = {};
  65173. }
  65174. /**
  65175. * This will clear this dictionary and copy the content from the 'source' one.
  65176. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  65177. * @param source the dictionary to take the content from and copy to this dictionary
  65178. */
  65179. StringDictionary.prototype.copyFrom = function (source) {
  65180. var _this = this;
  65181. this.clear();
  65182. source.forEach(function (t, v) { return _this.add(t, v); });
  65183. };
  65184. /**
  65185. * Get a value based from its key
  65186. * @param key the given key to get the matching value from
  65187. * @return the value if found, otherwise undefined is returned
  65188. */
  65189. StringDictionary.prototype.get = function (key) {
  65190. var val = this._data[key];
  65191. if (val !== undefined) {
  65192. return val;
  65193. }
  65194. return undefined;
  65195. };
  65196. /**
  65197. * Get a value from its key or add it if it doesn't exist.
  65198. * This method will ensure you that a given key/data will be present in the dictionary.
  65199. * @param key the given key to get the matching value from
  65200. * @param factory the factory that will create the value if the key is not present in the dictionary.
  65201. * The factory will only be invoked if there's no data for the given key.
  65202. * @return the value corresponding to the key.
  65203. */
  65204. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  65205. var val = this.get(key);
  65206. if (val !== undefined) {
  65207. return val;
  65208. }
  65209. val = factory(key);
  65210. if (val) {
  65211. this.add(key, val);
  65212. }
  65213. return val;
  65214. };
  65215. /**
  65216. * Get a value from its key if present in the dictionary otherwise add it
  65217. * @param key the key to get the value from
  65218. * @param val if there's no such key/value pair in the dictionary add it with this value
  65219. * @return the value corresponding to the key
  65220. */
  65221. StringDictionary.prototype.getOrAdd = function (key, val) {
  65222. var curVal = this.get(key);
  65223. if (curVal !== undefined) {
  65224. return curVal;
  65225. }
  65226. this.add(key, val);
  65227. return val;
  65228. };
  65229. /**
  65230. * Check if there's a given key in the dictionary
  65231. * @param key the key to check for
  65232. * @return true if the key is present, false otherwise
  65233. */
  65234. StringDictionary.prototype.contains = function (key) {
  65235. return this._data[key] !== undefined;
  65236. };
  65237. /**
  65238. * Add a new key and its corresponding value
  65239. * @param key the key to add
  65240. * @param value the value corresponding to the key
  65241. * @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
  65242. */
  65243. StringDictionary.prototype.add = function (key, value) {
  65244. if (this._data[key] !== undefined) {
  65245. return false;
  65246. }
  65247. this._data[key] = value;
  65248. ++this._count;
  65249. return true;
  65250. };
  65251. /**
  65252. * Update a specific value associated to a key
  65253. * @param key defines the key to use
  65254. * @param value defines the value to store
  65255. * @returns true if the value was updated (or false if the key was not found)
  65256. */
  65257. StringDictionary.prototype.set = function (key, value) {
  65258. if (this._data[key] === undefined) {
  65259. return false;
  65260. }
  65261. this._data[key] = value;
  65262. return true;
  65263. };
  65264. /**
  65265. * Get the element of the given key and remove it from the dictionary
  65266. * @param key defines the key to search
  65267. * @returns the value associated with the key or null if not found
  65268. */
  65269. StringDictionary.prototype.getAndRemove = function (key) {
  65270. var val = this.get(key);
  65271. if (val !== undefined) {
  65272. delete this._data[key];
  65273. --this._count;
  65274. return val;
  65275. }
  65276. return null;
  65277. };
  65278. /**
  65279. * Remove a key/value from the dictionary.
  65280. * @param key the key to remove
  65281. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  65282. */
  65283. StringDictionary.prototype.remove = function (key) {
  65284. if (this.contains(key)) {
  65285. delete this._data[key];
  65286. --this._count;
  65287. return true;
  65288. }
  65289. return false;
  65290. };
  65291. /**
  65292. * Clear the whole content of the dictionary
  65293. */
  65294. StringDictionary.prototype.clear = function () {
  65295. this._data = {};
  65296. this._count = 0;
  65297. };
  65298. Object.defineProperty(StringDictionary.prototype, "count", {
  65299. /**
  65300. * Gets the current count
  65301. */
  65302. get: function () {
  65303. return this._count;
  65304. },
  65305. enumerable: true,
  65306. configurable: true
  65307. });
  65308. /**
  65309. * Execute a callback on each key/val of the dictionary.
  65310. * Note that you can remove any element in this dictionary in the callback implementation
  65311. * @param callback the callback to execute on a given key/value pair
  65312. */
  65313. StringDictionary.prototype.forEach = function (callback) {
  65314. for (var cur in this._data) {
  65315. var val = this._data[cur];
  65316. callback(cur, val);
  65317. }
  65318. };
  65319. /**
  65320. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  65321. * If the callback returns null or undefined the method will iterate to the next key/value pair
  65322. * Note that you can remove any element in this dictionary in the callback implementation
  65323. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  65324. * @returns the first item
  65325. */
  65326. StringDictionary.prototype.first = function (callback) {
  65327. for (var cur in this._data) {
  65328. var val = this._data[cur];
  65329. var res = callback(cur, val);
  65330. if (res) {
  65331. return res;
  65332. }
  65333. }
  65334. return null;
  65335. };
  65336. return StringDictionary;
  65337. }());
  65338. BABYLON.StringDictionary = StringDictionary;
  65339. })(BABYLON || (BABYLON = {}));
  65340. //# sourceMappingURL=babylon.stringDictionary.js.map
  65341. var BABYLON;
  65342. (function (BABYLON) {
  65343. var Debug;
  65344. (function (Debug) {
  65345. /**
  65346. * Class used to render a debug view of a given skeleton
  65347. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  65348. */
  65349. var SkeletonViewer = /** @class */ (function () {
  65350. /**
  65351. * Creates a new SkeletonViewer
  65352. * @param skeleton defines the skeleton to render
  65353. * @param mesh defines the mesh attached to the skeleton
  65354. * @param scene defines the hosting scene
  65355. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  65356. * @param renderingGroupId defines the rendering group id to use with the viewer
  65357. */
  65358. function SkeletonViewer(
  65359. /** defines the skeleton to render */
  65360. skeleton,
  65361. /** defines the mesh attached to the skeleton */
  65362. mesh, scene,
  65363. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  65364. autoUpdateBonesMatrices,
  65365. /** defines the rendering group id to use with the viewer */
  65366. renderingGroupId) {
  65367. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  65368. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  65369. this.skeleton = skeleton;
  65370. this.mesh = mesh;
  65371. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  65372. this.renderingGroupId = renderingGroupId;
  65373. /** Gets or sets the color used to render the skeleton */
  65374. this.color = BABYLON.Color3.White();
  65375. this._debugLines = new Array();
  65376. this._isEnabled = false;
  65377. this._scene = scene;
  65378. this.update();
  65379. this._renderFunction = this.update.bind(this);
  65380. }
  65381. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  65382. get: function () {
  65383. return this._isEnabled;
  65384. },
  65385. /** Gets or sets a boolean indicating if the viewer is enabled */
  65386. set: function (value) {
  65387. if (this._isEnabled === value) {
  65388. return;
  65389. }
  65390. this._isEnabled = value;
  65391. if (value) {
  65392. this._scene.registerBeforeRender(this._renderFunction);
  65393. }
  65394. else {
  65395. this._scene.unregisterBeforeRender(this._renderFunction);
  65396. }
  65397. },
  65398. enumerable: true,
  65399. configurable: true
  65400. });
  65401. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  65402. if (x === void 0) { x = 0; }
  65403. if (y === void 0) { y = 0; }
  65404. if (z === void 0) { z = 0; }
  65405. var tmat = BABYLON.Tmp.Matrix[0];
  65406. var parentBone = bone.getParent();
  65407. tmat.copyFrom(bone.getLocalMatrix());
  65408. if (x !== 0 || y !== 0 || z !== 0) {
  65409. var tmat2 = BABYLON.Tmp.Matrix[1];
  65410. BABYLON.Matrix.IdentityToRef(tmat2);
  65411. tmat2.setTranslationFromFloats(x, y, z);
  65412. tmat2.multiplyToRef(tmat, tmat);
  65413. }
  65414. if (parentBone) {
  65415. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  65416. }
  65417. tmat.multiplyToRef(meshMat, tmat);
  65418. position.x = tmat.m[12];
  65419. position.y = tmat.m[13];
  65420. position.z = tmat.m[14];
  65421. };
  65422. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  65423. var len = bones.length;
  65424. var meshPos = this.mesh.position;
  65425. for (var i = 0; i < len; i++) {
  65426. var bone = bones[i];
  65427. var points = this._debugLines[i];
  65428. if (!points) {
  65429. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65430. this._debugLines[i] = points;
  65431. }
  65432. this._getBonePosition(points[0], bone, meshMat);
  65433. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  65434. points[0].subtractInPlace(meshPos);
  65435. points[1].subtractInPlace(meshPos);
  65436. }
  65437. };
  65438. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  65439. var len = bones.length;
  65440. var boneNum = 0;
  65441. var meshPos = this.mesh.position;
  65442. for (var i = len - 1; i >= 0; i--) {
  65443. var childBone = bones[i];
  65444. var parentBone = childBone.getParent();
  65445. if (!parentBone) {
  65446. continue;
  65447. }
  65448. var points = this._debugLines[boneNum];
  65449. if (!points) {
  65450. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65451. this._debugLines[boneNum] = points;
  65452. }
  65453. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  65454. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  65455. points[0].subtractInPlace(meshPos);
  65456. points[1].subtractInPlace(meshPos);
  65457. boneNum++;
  65458. }
  65459. };
  65460. /** Update the viewer to sync with current skeleton state */
  65461. SkeletonViewer.prototype.update = function () {
  65462. if (this.autoUpdateBonesMatrices) {
  65463. this.skeleton.computeAbsoluteTransforms();
  65464. }
  65465. if (this.skeleton.bones[0].length === undefined) {
  65466. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65467. }
  65468. else {
  65469. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65470. }
  65471. if (!this._debugMesh) {
  65472. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  65473. this._debugMesh.renderingGroupId = this.renderingGroupId;
  65474. }
  65475. else {
  65476. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  65477. }
  65478. this._debugMesh.position.copyFrom(this.mesh.position);
  65479. this._debugMesh.color = this.color;
  65480. };
  65481. /** Release associated resources */
  65482. SkeletonViewer.prototype.dispose = function () {
  65483. if (this._debugMesh) {
  65484. this.isEnabled = false;
  65485. this._debugMesh.dispose();
  65486. this._debugMesh = null;
  65487. }
  65488. };
  65489. return SkeletonViewer;
  65490. }());
  65491. Debug.SkeletonViewer = SkeletonViewer;
  65492. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65493. })(BABYLON || (BABYLON = {}));
  65494. //# sourceMappingURL=babylon.skeletonViewer.js.map
  65495. /**
  65496. * Module Debug contains the (visual) components to debug a scene correctly
  65497. */
  65498. var BABYLON;
  65499. (function (BABYLON) {
  65500. var Debug;
  65501. (function (Debug) {
  65502. /**
  65503. * The Axes viewer will show 3 axes in a specific point in space
  65504. */
  65505. var AxesViewer = /** @class */ (function () {
  65506. /**
  65507. * Creates a new AxesViewer
  65508. * @param scene defines the hosting scene
  65509. * @param scaleLines defines a number used to scale line length (1 by default)
  65510. */
  65511. function AxesViewer(scene, scaleLines) {
  65512. if (scaleLines === void 0) { scaleLines = 1; }
  65513. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65514. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65515. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65516. /**
  65517. * Gets or sets a number used to scale line length
  65518. */
  65519. this.scaleLines = 1;
  65520. this.scaleLines = scaleLines;
  65521. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  65522. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  65523. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  65524. this._xmesh.renderingGroupId = 2;
  65525. this._ymesh.renderingGroupId = 2;
  65526. this._zmesh.renderingGroupId = 2;
  65527. this._xmesh.material.checkReadyOnlyOnce = true;
  65528. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  65529. this._ymesh.material.checkReadyOnlyOnce = true;
  65530. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  65531. this._zmesh.material.checkReadyOnlyOnce = true;
  65532. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  65533. this.scene = scene;
  65534. }
  65535. /**
  65536. * Force the viewer to update
  65537. * @param position defines the position of the viewer
  65538. * @param xaxis defines the x axis of the viewer
  65539. * @param yaxis defines the y axis of the viewer
  65540. * @param zaxis defines the z axis of the viewer
  65541. */
  65542. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  65543. var scaleLines = this.scaleLines;
  65544. if (this._xmesh) {
  65545. this._xmesh.position.copyFrom(position);
  65546. }
  65547. if (this._ymesh) {
  65548. this._ymesh.position.copyFrom(position);
  65549. }
  65550. if (this._zmesh) {
  65551. this._zmesh.position.copyFrom(position);
  65552. }
  65553. var point2 = this._xline[1];
  65554. point2.x = xaxis.x * scaleLines;
  65555. point2.y = xaxis.y * scaleLines;
  65556. point2.z = xaxis.z * scaleLines;
  65557. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  65558. point2 = this._yline[1];
  65559. point2.x = yaxis.x * scaleLines;
  65560. point2.y = yaxis.y * scaleLines;
  65561. point2.z = yaxis.z * scaleLines;
  65562. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  65563. point2 = this._zline[1];
  65564. point2.x = zaxis.x * scaleLines;
  65565. point2.y = zaxis.y * scaleLines;
  65566. point2.z = zaxis.z * scaleLines;
  65567. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  65568. };
  65569. /** Releases resources */
  65570. AxesViewer.prototype.dispose = function () {
  65571. if (this._xmesh) {
  65572. this._xmesh.dispose();
  65573. }
  65574. if (this._ymesh) {
  65575. this._ymesh.dispose();
  65576. }
  65577. if (this._zmesh) {
  65578. this._zmesh.dispose();
  65579. }
  65580. this._xmesh = null;
  65581. this._ymesh = null;
  65582. this._zmesh = null;
  65583. this.scene = null;
  65584. };
  65585. return AxesViewer;
  65586. }());
  65587. Debug.AxesViewer = AxesViewer;
  65588. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65589. })(BABYLON || (BABYLON = {}));
  65590. //# sourceMappingURL=babylon.axesViewer.js.map
  65591. var BABYLON;
  65592. (function (BABYLON) {
  65593. var Debug;
  65594. (function (Debug) {
  65595. /**
  65596. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  65597. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  65598. */
  65599. var BoneAxesViewer = /** @class */ (function (_super) {
  65600. __extends(BoneAxesViewer, _super);
  65601. /**
  65602. * Creates a new BoneAxesViewer
  65603. * @param scene defines the hosting scene
  65604. * @param bone defines the target bone
  65605. * @param mesh defines the target mesh
  65606. * @param scaleLines defines a scaling factor for line length (1 by default)
  65607. */
  65608. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  65609. if (scaleLines === void 0) { scaleLines = 1; }
  65610. var _this = _super.call(this, scene, scaleLines) || this;
  65611. /** Gets current position */
  65612. _this.pos = BABYLON.Vector3.Zero();
  65613. /** Gets direction of X axis */
  65614. _this.xaxis = BABYLON.Vector3.Zero();
  65615. /** Gets direction of Y axis */
  65616. _this.yaxis = BABYLON.Vector3.Zero();
  65617. /** Gets direction of Z axis */
  65618. _this.zaxis = BABYLON.Vector3.Zero();
  65619. _this.mesh = mesh;
  65620. _this.bone = bone;
  65621. return _this;
  65622. }
  65623. /**
  65624. * Force the viewer to update
  65625. */
  65626. BoneAxesViewer.prototype.update = function () {
  65627. if (!this.mesh || !this.bone) {
  65628. return;
  65629. }
  65630. var bone = this.bone;
  65631. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  65632. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  65633. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  65634. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  65635. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  65636. };
  65637. /** Releases resources */
  65638. BoneAxesViewer.prototype.dispose = function () {
  65639. if (this.mesh) {
  65640. this.mesh = null;
  65641. this.bone = null;
  65642. _super.prototype.dispose.call(this);
  65643. }
  65644. };
  65645. return BoneAxesViewer;
  65646. }(Debug.AxesViewer));
  65647. Debug.BoneAxesViewer = BoneAxesViewer;
  65648. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65649. })(BABYLON || (BABYLON = {}));
  65650. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  65651. var BABYLON;
  65652. (function (BABYLON) {
  65653. /**
  65654. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  65655. * in order to better appreciate the issue one might have.
  65656. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  65657. */
  65658. var RayHelper = /** @class */ (function () {
  65659. /**
  65660. * Instantiate a new ray helper.
  65661. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  65662. * in order to better appreciate the issue one might have.
  65663. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  65664. * @param ray Defines the ray we are currently tryin to visualize
  65665. */
  65666. function RayHelper(ray) {
  65667. this.ray = ray;
  65668. }
  65669. /**
  65670. * Helper function to create a colored helper in a scene in one line.
  65671. * @param ray Defines the ray we are currently tryin to visualize
  65672. * @param scene Defines the scene the ray is used in
  65673. * @param color Defines the color we want to see the ray in
  65674. * @returns The newly created ray helper.
  65675. */
  65676. RayHelper.CreateAndShow = function (ray, scene, color) {
  65677. var helper = new RayHelper(ray);
  65678. helper.show(scene, color);
  65679. return helper;
  65680. };
  65681. /**
  65682. * Shows the ray we are willing to debug.
  65683. * @param scene Defines the scene the ray needs to be rendered in
  65684. * @param color Defines the color the ray needs to be rendered in
  65685. */
  65686. RayHelper.prototype.show = function (scene, color) {
  65687. if (!this._renderFunction && this.ray) {
  65688. var ray = this.ray;
  65689. this._renderFunction = this._render.bind(this);
  65690. this._scene = scene;
  65691. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  65692. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  65693. if (this._renderFunction) {
  65694. this._scene.registerBeforeRender(this._renderFunction);
  65695. }
  65696. }
  65697. if (color && this._renderLine) {
  65698. this._renderLine.color.copyFrom(color);
  65699. }
  65700. };
  65701. /**
  65702. * Hides the ray we are debugging.
  65703. */
  65704. RayHelper.prototype.hide = function () {
  65705. if (this._renderFunction && this._scene) {
  65706. this._scene.unregisterBeforeRender(this._renderFunction);
  65707. this._scene = null;
  65708. this._renderFunction = null;
  65709. if (this._renderLine) {
  65710. this._renderLine.dispose();
  65711. this._renderLine = null;
  65712. }
  65713. this._renderPoints = [];
  65714. }
  65715. };
  65716. RayHelper.prototype._render = function () {
  65717. var ray = this.ray;
  65718. if (!ray) {
  65719. return;
  65720. }
  65721. var point = this._renderPoints[1];
  65722. var len = Math.min(ray.length, 1000000);
  65723. point.copyFrom(ray.direction);
  65724. point.scaleInPlace(len);
  65725. point.addInPlace(ray.origin);
  65726. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  65727. };
  65728. /**
  65729. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  65730. * @param mesh Defines the mesh we want the helper attached to
  65731. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  65732. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  65733. * @param length Defines the length of the ray
  65734. */
  65735. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  65736. this._attachedToMesh = mesh;
  65737. var ray = this.ray;
  65738. if (!ray) {
  65739. return;
  65740. }
  65741. if (!ray.direction) {
  65742. ray.direction = BABYLON.Vector3.Zero();
  65743. }
  65744. if (!ray.origin) {
  65745. ray.origin = BABYLON.Vector3.Zero();
  65746. }
  65747. if (length) {
  65748. ray.length = length;
  65749. }
  65750. if (!meshSpaceOrigin) {
  65751. meshSpaceOrigin = BABYLON.Vector3.Zero();
  65752. }
  65753. if (!meshSpaceDirection) {
  65754. // -1 so that this will work with Mesh.lookAt
  65755. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  65756. }
  65757. if (!this._meshSpaceDirection) {
  65758. this._meshSpaceDirection = meshSpaceDirection.clone();
  65759. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  65760. }
  65761. else {
  65762. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  65763. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  65764. }
  65765. if (!this._updateToMeshFunction) {
  65766. this._updateToMeshFunction = this._updateToMesh.bind(this);
  65767. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  65768. }
  65769. this._updateToMesh();
  65770. };
  65771. /**
  65772. * Detach the ray helper from the mesh it has previously been attached to.
  65773. */
  65774. RayHelper.prototype.detachFromMesh = function () {
  65775. if (this._attachedToMesh) {
  65776. if (this._updateToMeshFunction) {
  65777. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  65778. }
  65779. this._attachedToMesh = null;
  65780. this._updateToMeshFunction = null;
  65781. }
  65782. };
  65783. RayHelper.prototype._updateToMesh = function () {
  65784. var ray = this.ray;
  65785. if (!this._attachedToMesh || !ray) {
  65786. return;
  65787. }
  65788. if (this._attachedToMesh._isDisposed) {
  65789. this.detachFromMesh();
  65790. return;
  65791. }
  65792. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  65793. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  65794. };
  65795. /**
  65796. * Dispose the helper and release its associated resources.
  65797. */
  65798. RayHelper.prototype.dispose = function () {
  65799. this.hide();
  65800. this.detachFromMesh();
  65801. this.ray = null;
  65802. };
  65803. return RayHelper;
  65804. }());
  65805. BABYLON.RayHelper = RayHelper;
  65806. })(BABYLON || (BABYLON = {}));
  65807. //# sourceMappingURL=babylon.rayHelper.js.map
  65808. var BABYLON;
  65809. (function (BABYLON) {
  65810. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  65811. get: function () {
  65812. if (!this._debugLayer) {
  65813. this._debugLayer = new DebugLayer(this);
  65814. }
  65815. return this._debugLayer;
  65816. },
  65817. enumerable: true,
  65818. configurable: true
  65819. });
  65820. /**
  65821. * The debug layer (aka Inspector) is the go to tool in order to better understand
  65822. * what is happening in your scene
  65823. * @see http://doc.babylonjs.com/features/playground_debuglayer
  65824. */
  65825. var DebugLayer = /** @class */ (function () {
  65826. /**
  65827. * Instantiates a new debug layer.
  65828. * The debug layer (aka Inspector) is the go to tool in order to better understand
  65829. * what is happening in your scene
  65830. * @see http://doc.babylonjs.com/features/playground_debuglayer
  65831. * @param scene Defines the scene to inspect
  65832. */
  65833. function DebugLayer(scene) {
  65834. var _this = this;
  65835. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  65836. /**
  65837. * Observable triggered when a property is changed through the inspector.
  65838. */
  65839. this.onPropertyChangedObservable = new BABYLON.Observable();
  65840. this._scene = scene;
  65841. this._scene.onDisposeObservable.add(function () {
  65842. // Debug layer
  65843. if (_this._scene._debugLayer) {
  65844. _this._scene._debugLayer.hide();
  65845. }
  65846. });
  65847. }
  65848. /** Creates the inspector window. */
  65849. DebugLayer.prototype._createInspector = function (config) {
  65850. if (config === void 0) { config = {}; }
  65851. var popup = config.popup || false;
  65852. var initialTab = config.initialTab || 0;
  65853. var parentElement = config.parentElement || null;
  65854. if (!this._inspector) {
  65855. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  65856. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  65857. } // else nothing to do as instance is already created
  65858. };
  65859. /**
  65860. * Get if the inspector is visible or not.
  65861. * @returns true if visible otherwise, false
  65862. */
  65863. DebugLayer.prototype.isVisible = function () {
  65864. if (!this._inspector) {
  65865. return false;
  65866. }
  65867. return true;
  65868. };
  65869. /**
  65870. * Hide the inspector and close its window.
  65871. */
  65872. DebugLayer.prototype.hide = function () {
  65873. if (this._inspector) {
  65874. try {
  65875. this._inspector.dispose();
  65876. }
  65877. catch (e) {
  65878. // If the inspector has been removed directly from the inspector tool
  65879. }
  65880. this.onPropertyChangedObservable.clear();
  65881. this._inspector = null;
  65882. }
  65883. };
  65884. /**
  65885. *
  65886. * Launch the debugLayer.
  65887. *
  65888. * initialTab:
  65889. * | Value | Tab Name |
  65890. * | --- | --- |
  65891. * | 0 | Scene |
  65892. * | 1 | Console |
  65893. * | 2 | Stats |
  65894. * | 3 | Textures |
  65895. * | 4 | Mesh |
  65896. * | 5 | Light |
  65897. * | 6 | Material |
  65898. * | 7 | GLTF |
  65899. * | 8 | GUI |
  65900. * | 9 | Physics |
  65901. * | 10 | Camera |
  65902. * | 11 | Audio |
  65903. *
  65904. * @param config Define the configuration of the inspector
  65905. */
  65906. DebugLayer.prototype.show = function (config) {
  65907. if (config === void 0) { config = {}; }
  65908. if (typeof this.BJSINSPECTOR == 'undefined') {
  65909. // Load inspector and add it to the DOM
  65910. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  65911. }
  65912. else {
  65913. // Otherwise creates the inspector
  65914. this._createInspector(config);
  65915. }
  65916. };
  65917. /**
  65918. * Gets the active tab
  65919. * @return the index of the active tab or -1 if the inspector is hidden
  65920. */
  65921. DebugLayer.prototype.getActiveTab = function () {
  65922. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  65923. };
  65924. /**
  65925. * Define the url to get the inspector script from.
  65926. * By default it uses the babylonjs CDN.
  65927. * @ignoreNaming
  65928. */
  65929. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  65930. return DebugLayer;
  65931. }());
  65932. BABYLON.DebugLayer = DebugLayer;
  65933. })(BABYLON || (BABYLON = {}));
  65934. //# sourceMappingURL=babylon.debugLayer.js.map
  65935. var BABYLON;
  65936. (function (BABYLON) {
  65937. var Debug;
  65938. (function (Debug) {
  65939. /**
  65940. * Used to show the physics impostor around the specific mesh
  65941. */
  65942. var PhysicsViewer = /** @class */ (function () {
  65943. /**
  65944. * Creates a new PhysicsViewer
  65945. * @param scene defines the hosting scene
  65946. */
  65947. function PhysicsViewer(scene) {
  65948. /** @hidden */
  65949. this._impostors = [];
  65950. /** @hidden */
  65951. this._meshes = [];
  65952. /** @hidden */
  65953. this._numMeshes = 0;
  65954. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65955. var physicEngine = this._scene.getPhysicsEngine();
  65956. if (physicEngine) {
  65957. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  65958. }
  65959. }
  65960. /** @hidden */
  65961. PhysicsViewer.prototype._updateDebugMeshes = function () {
  65962. var plugin = this._physicsEnginePlugin;
  65963. for (var i = 0; i < this._numMeshes; i++) {
  65964. var impostor = this._impostors[i];
  65965. if (!impostor) {
  65966. continue;
  65967. }
  65968. if (impostor.isDisposed) {
  65969. this.hideImpostor(this._impostors[i--]);
  65970. }
  65971. else {
  65972. var mesh = this._meshes[i];
  65973. if (mesh && plugin) {
  65974. plugin.syncMeshWithImpostor(mesh, impostor);
  65975. }
  65976. }
  65977. }
  65978. };
  65979. /**
  65980. * Renders a specified physic impostor
  65981. * @param impostor defines the impostor to render
  65982. */
  65983. PhysicsViewer.prototype.showImpostor = function (impostor) {
  65984. if (!this._scene) {
  65985. return;
  65986. }
  65987. for (var i = 0; i < this._numMeshes; i++) {
  65988. if (this._impostors[i] == impostor) {
  65989. return;
  65990. }
  65991. }
  65992. var debugMesh = this._getDebugMesh(impostor, this._scene);
  65993. if (debugMesh) {
  65994. this._impostors[this._numMeshes] = impostor;
  65995. this._meshes[this._numMeshes] = debugMesh;
  65996. if (this._numMeshes === 0) {
  65997. this._renderFunction = this._updateDebugMeshes.bind(this);
  65998. this._scene.registerBeforeRender(this._renderFunction);
  65999. }
  66000. this._numMeshes++;
  66001. }
  66002. };
  66003. /**
  66004. * Hides a specified physic impostor
  66005. * @param impostor defines the impostor to hide
  66006. */
  66007. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  66008. if (!impostor || !this._scene) {
  66009. return;
  66010. }
  66011. var removed = false;
  66012. for (var i = 0; i < this._numMeshes; i++) {
  66013. if (this._impostors[i] == impostor) {
  66014. var mesh = this._meshes[i];
  66015. if (!mesh) {
  66016. continue;
  66017. }
  66018. this._scene.removeMesh(mesh);
  66019. mesh.dispose();
  66020. this._numMeshes--;
  66021. if (this._numMeshes > 0) {
  66022. this._meshes[i] = this._meshes[this._numMeshes];
  66023. this._impostors[i] = this._impostors[this._numMeshes];
  66024. this._meshes[this._numMeshes] = null;
  66025. this._impostors[this._numMeshes] = null;
  66026. }
  66027. else {
  66028. this._meshes[0] = null;
  66029. this._impostors[0] = null;
  66030. }
  66031. removed = true;
  66032. break;
  66033. }
  66034. }
  66035. if (removed && this._numMeshes === 0) {
  66036. this._scene.unregisterBeforeRender(this._renderFunction);
  66037. }
  66038. };
  66039. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  66040. if (!this._debugMaterial) {
  66041. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  66042. this._debugMaterial.wireframe = true;
  66043. }
  66044. return this._debugMaterial;
  66045. };
  66046. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  66047. if (!this._debugBoxMesh) {
  66048. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  66049. this._debugBoxMesh.renderingGroupId = 1;
  66050. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66051. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  66052. scene.removeMesh(this._debugBoxMesh);
  66053. }
  66054. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  66055. };
  66056. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  66057. if (!this._debugSphereMesh) {
  66058. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  66059. this._debugSphereMesh.renderingGroupId = 1;
  66060. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66061. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  66062. scene.removeMesh(this._debugSphereMesh);
  66063. }
  66064. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  66065. };
  66066. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  66067. var mesh = null;
  66068. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  66069. mesh = this._getDebugBoxMesh(scene);
  66070. impostor.getBoxSizeToRef(mesh.scaling);
  66071. }
  66072. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  66073. mesh = this._getDebugSphereMesh(scene);
  66074. var radius = impostor.getRadius();
  66075. mesh.scaling.x = radius * 2;
  66076. mesh.scaling.y = radius * 2;
  66077. mesh.scaling.z = radius * 2;
  66078. }
  66079. return mesh;
  66080. };
  66081. /** Releases all resources */
  66082. PhysicsViewer.prototype.dispose = function () {
  66083. for (var i = 0; i < this._numMeshes; i++) {
  66084. this.hideImpostor(this._impostors[i]);
  66085. }
  66086. if (this._debugBoxMesh) {
  66087. this._debugBoxMesh.dispose();
  66088. }
  66089. if (this._debugSphereMesh) {
  66090. this._debugSphereMesh.dispose();
  66091. }
  66092. if (this._debugMaterial) {
  66093. this._debugMaterial.dispose();
  66094. }
  66095. this._impostors.length = 0;
  66096. this._scene = null;
  66097. this._physicsEnginePlugin = null;
  66098. };
  66099. return PhysicsViewer;
  66100. }());
  66101. Debug.PhysicsViewer = PhysicsViewer;
  66102. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66103. })(BABYLON || (BABYLON = {}));
  66104. //# sourceMappingURL=babylon.physicsViewer.js.map
  66105. var BABYLON;
  66106. (function (BABYLON) {
  66107. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  66108. get: function () {
  66109. return this._forceShowBoundingBoxes || false;
  66110. },
  66111. set: function (value) {
  66112. this._forceShowBoundingBoxes = value;
  66113. // Lazyly creates a BB renderer if needed.
  66114. if (value) {
  66115. this.getBoundingBoxRenderer();
  66116. }
  66117. },
  66118. enumerable: true,
  66119. configurable: true
  66120. });
  66121. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  66122. if (!this._boundingBoxRenderer) {
  66123. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  66124. }
  66125. return this._boundingBoxRenderer;
  66126. };
  66127. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  66128. get: function () {
  66129. return this._showBoundingBox || false;
  66130. },
  66131. set: function (value) {
  66132. this._showBoundingBox = value;
  66133. // Lazyly creates a BB renderer if needed.
  66134. if (value) {
  66135. this.getScene().getBoundingBoxRenderer();
  66136. }
  66137. },
  66138. enumerable: true,
  66139. configurable: true
  66140. });
  66141. /**
  66142. * Component responsible of rendering the bounding box of the meshes in a scene.
  66143. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  66144. */
  66145. var BoundingBoxRenderer = /** @class */ (function () {
  66146. /**
  66147. * Instantiates a new bounding box renderer in a scene.
  66148. * @param scene the scene the renderer renders in
  66149. */
  66150. function BoundingBoxRenderer(scene) {
  66151. /**
  66152. * The component name helpfull to identify the component in the list of scene components.
  66153. */
  66154. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  66155. /**
  66156. * Color of the bounding box lines placed in front of an object
  66157. */
  66158. this.frontColor = new BABYLON.Color3(1, 1, 1);
  66159. /**
  66160. * Color of the bounding box lines placed behind an object
  66161. */
  66162. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  66163. /**
  66164. * Defines if the renderer should show the back lines or not
  66165. */
  66166. this.showBackLines = true;
  66167. /**
  66168. * @hidden
  66169. */
  66170. this.renderList = new BABYLON.SmartArray(32);
  66171. this._vertexBuffers = {};
  66172. this.scene = scene;
  66173. scene._addComponent(this);
  66174. }
  66175. /**
  66176. * Registers the component in a given scene
  66177. */
  66178. BoundingBoxRenderer.prototype.register = function () {
  66179. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  66180. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  66181. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  66182. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  66183. };
  66184. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  66185. if (mesh.showSubMeshesBoundingBox) {
  66186. var boundingInfo = subMesh.getBoundingInfo();
  66187. if (boundingInfo !== null && boundingInfo !== undefined) {
  66188. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  66189. this.renderList.push(boundingInfo.boundingBox);
  66190. }
  66191. }
  66192. };
  66193. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  66194. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  66195. var boundingInfo = sourceMesh.getBoundingInfo();
  66196. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  66197. this.renderList.push(boundingInfo.boundingBox);
  66198. }
  66199. };
  66200. BoundingBoxRenderer.prototype._prepareRessources = function () {
  66201. if (this._colorShader) {
  66202. return;
  66203. }
  66204. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  66205. attributes: [BABYLON.VertexBuffer.PositionKind],
  66206. uniforms: ["world", "viewProjection", "color"]
  66207. });
  66208. var engine = this.scene.getEngine();
  66209. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  66210. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  66211. this._createIndexBuffer();
  66212. };
  66213. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  66214. var engine = this.scene.getEngine();
  66215. 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]);
  66216. };
  66217. /**
  66218. * Rebuilds the elements related to this component in case of
  66219. * context lost for instance.
  66220. */
  66221. BoundingBoxRenderer.prototype.rebuild = function () {
  66222. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66223. if (vb) {
  66224. vb._rebuild();
  66225. }
  66226. this._createIndexBuffer();
  66227. };
  66228. /**
  66229. * @hidden
  66230. */
  66231. BoundingBoxRenderer.prototype.reset = function () {
  66232. this.renderList.reset();
  66233. };
  66234. /**
  66235. * Render the bounding boxes of a specific rendering group
  66236. * @param renderingGroupId defines the rendering group to render
  66237. */
  66238. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  66239. if (this.renderList.length === 0) {
  66240. return;
  66241. }
  66242. this._prepareRessources();
  66243. if (!this._colorShader.isReady()) {
  66244. return;
  66245. }
  66246. var engine = this.scene.getEngine();
  66247. engine.setDepthWrite(false);
  66248. this._colorShader._preBind();
  66249. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  66250. var boundingBox = this.renderList.data[boundingBoxIndex];
  66251. if (boundingBox._tag !== renderingGroupId) {
  66252. continue;
  66253. }
  66254. var min = boundingBox.minimum;
  66255. var max = boundingBox.maximum;
  66256. var diff = max.subtract(min);
  66257. var median = min.add(diff.scale(0.5));
  66258. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66259. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66260. .multiply(boundingBox.getWorldMatrix());
  66261. // VBOs
  66262. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66263. if (this.showBackLines) {
  66264. // Back
  66265. engine.setDepthFunctionToGreaterOrEqual();
  66266. this.scene.resetCachedMaterial();
  66267. this._colorShader.setColor4("color", this.backColor.toColor4());
  66268. this._colorShader.bind(worldMatrix);
  66269. // Draw order
  66270. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66271. }
  66272. // Front
  66273. engine.setDepthFunctionToLess();
  66274. this.scene.resetCachedMaterial();
  66275. this._colorShader.setColor4("color", this.frontColor.toColor4());
  66276. this._colorShader.bind(worldMatrix);
  66277. // Draw order
  66278. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66279. }
  66280. this._colorShader.unbind();
  66281. engine.setDepthFunctionToLessOrEqual();
  66282. engine.setDepthWrite(true);
  66283. };
  66284. /**
  66285. * In case of occlusion queries, we can render the occlusion bounding box through this method
  66286. * @param mesh Define the mesh to render the occlusion bounding box for
  66287. */
  66288. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  66289. this._prepareRessources();
  66290. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  66291. return;
  66292. }
  66293. var engine = this.scene.getEngine();
  66294. engine.setDepthWrite(false);
  66295. engine.setColorWrite(false);
  66296. this._colorShader._preBind();
  66297. var boundingBox = mesh._boundingInfo.boundingBox;
  66298. var min = boundingBox.minimum;
  66299. var max = boundingBox.maximum;
  66300. var diff = max.subtract(min);
  66301. var median = min.add(diff.scale(0.5));
  66302. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66303. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66304. .multiply(boundingBox.getWorldMatrix());
  66305. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66306. engine.setDepthFunctionToLess();
  66307. this.scene.resetCachedMaterial();
  66308. this._colorShader.bind(worldMatrix);
  66309. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66310. this._colorShader.unbind();
  66311. engine.setDepthFunctionToLessOrEqual();
  66312. engine.setDepthWrite(true);
  66313. engine.setColorWrite(true);
  66314. };
  66315. /**
  66316. * Dispose and release the resources attached to this renderer.
  66317. */
  66318. BoundingBoxRenderer.prototype.dispose = function () {
  66319. if (!this._colorShader) {
  66320. return;
  66321. }
  66322. this.renderList.dispose();
  66323. this._colorShader.dispose();
  66324. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66325. if (buffer) {
  66326. buffer.dispose();
  66327. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66328. }
  66329. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  66330. };
  66331. return BoundingBoxRenderer;
  66332. }());
  66333. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  66334. })(BABYLON || (BABYLON = {}));
  66335. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  66336. var BABYLON;
  66337. (function (BABYLON) {
  66338. BABYLON.Engine.prototype.createTransformFeedback = function () {
  66339. return this._gl.createTransformFeedback();
  66340. };
  66341. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  66342. this._gl.deleteTransformFeedback(value);
  66343. };
  66344. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  66345. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  66346. };
  66347. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  66348. if (usePoints === void 0) { usePoints = true; }
  66349. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  66350. };
  66351. BABYLON.Engine.prototype.endTransformFeedback = function () {
  66352. this._gl.endTransformFeedback();
  66353. };
  66354. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  66355. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  66356. };
  66357. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  66358. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  66359. };
  66360. })(BABYLON || (BABYLON = {}));
  66361. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  66362. var BABYLON;
  66363. (function (BABYLON) {
  66364. /**
  66365. * This represents a GPU particle system in Babylon
  66366. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  66367. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  66368. */
  66369. var GPUParticleSystem = /** @class */ (function (_super) {
  66370. __extends(GPUParticleSystem, _super);
  66371. /**
  66372. * Instantiates a GPU particle system.
  66373. * 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.
  66374. * @param name The name of the particle system
  66375. * @param options The options used to create the system
  66376. * @param scene The scene the particle system belongs to
  66377. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  66378. */
  66379. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  66380. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  66381. var _this = _super.call(this, name) || this;
  66382. /**
  66383. * The layer mask we are rendering the particles through.
  66384. */
  66385. _this.layerMask = 0x0FFFFFFF;
  66386. _this._accumulatedCount = 0;
  66387. _this._targetIndex = 0;
  66388. _this._currentRenderId = -1;
  66389. _this._started = false;
  66390. _this._stopped = false;
  66391. _this._timeDelta = 0;
  66392. _this._actualFrame = 0;
  66393. _this._rawTextureWidth = 256;
  66394. /**
  66395. * An event triggered when the system is disposed.
  66396. */
  66397. _this.onDisposeObservable = new BABYLON.Observable();
  66398. /**
  66399. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  66400. * to override the particles.
  66401. */
  66402. _this.forceDepthWrite = false;
  66403. _this._preWarmDone = false;
  66404. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66405. // Setup the default processing configuration to the scene.
  66406. _this._attachImageProcessingConfiguration(null);
  66407. _this._engine = _this._scene.getEngine();
  66408. if (!options.randomTextureSize) {
  66409. delete options.randomTextureSize;
  66410. }
  66411. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  66412. var optionsAsNumber = options;
  66413. if (isFinite(optionsAsNumber)) {
  66414. fullOptions.capacity = optionsAsNumber;
  66415. }
  66416. _this._capacity = fullOptions.capacity;
  66417. _this._activeCount = fullOptions.capacity;
  66418. _this._currentActiveCount = 0;
  66419. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  66420. _this._scene.particleSystems.push(_this);
  66421. _this._updateEffectOptions = {
  66422. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  66423. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  66424. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  66425. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  66426. uniformBuffersNames: [],
  66427. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  66428. defines: "",
  66429. fallbacks: null,
  66430. onCompiled: null,
  66431. onError: null,
  66432. indexParameters: null,
  66433. maxSimultaneousLights: 0,
  66434. transformFeedbackVaryings: []
  66435. };
  66436. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  66437. // Random data
  66438. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  66439. var d = [];
  66440. for (var i = 0; i < maxTextureSize; ++i) {
  66441. d.push(Math.random());
  66442. d.push(Math.random());
  66443. d.push(Math.random());
  66444. d.push(Math.random());
  66445. }
  66446. _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);
  66447. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66448. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66449. d = [];
  66450. for (var i = 0; i < maxTextureSize; ++i) {
  66451. d.push(Math.random());
  66452. d.push(Math.random());
  66453. d.push(Math.random());
  66454. d.push(Math.random());
  66455. }
  66456. _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);
  66457. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66458. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66459. _this._randomTextureSize = maxTextureSize;
  66460. return _this;
  66461. }
  66462. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  66463. /**
  66464. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  66465. */
  66466. get: function () {
  66467. if (!BABYLON.Engine.LastCreatedEngine) {
  66468. return false;
  66469. }
  66470. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  66471. },
  66472. enumerable: true,
  66473. configurable: true
  66474. });
  66475. /**
  66476. * Gets the maximum number of particles active at the same time.
  66477. * @returns The max number of active particles.
  66478. */
  66479. GPUParticleSystem.prototype.getCapacity = function () {
  66480. return this._capacity;
  66481. };
  66482. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  66483. /**
  66484. * Gets or set the number of active particles
  66485. */
  66486. get: function () {
  66487. return this._activeCount;
  66488. },
  66489. set: function (value) {
  66490. this._activeCount = Math.min(value, this._capacity);
  66491. },
  66492. enumerable: true,
  66493. configurable: true
  66494. });
  66495. /**
  66496. * Is this system ready to be used/rendered
  66497. * @return true if the system is ready
  66498. */
  66499. GPUParticleSystem.prototype.isReady = function () {
  66500. if (!this._updateEffect) {
  66501. this._recreateUpdateEffect();
  66502. this._recreateRenderEffect();
  66503. return false;
  66504. }
  66505. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  66506. return false;
  66507. }
  66508. return true;
  66509. };
  66510. /**
  66511. * Gets if the system has been started. (Note: this will still be true after stop is called)
  66512. * @returns True if it has been started, otherwise false.
  66513. */
  66514. GPUParticleSystem.prototype.isStarted = function () {
  66515. return this._started;
  66516. };
  66517. /**
  66518. * Starts the particle system and begins to emit
  66519. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  66520. */
  66521. GPUParticleSystem.prototype.start = function (delay) {
  66522. var _this = this;
  66523. if (delay === void 0) { delay = this.startDelay; }
  66524. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  66525. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  66526. }
  66527. if (delay) {
  66528. setTimeout(function () {
  66529. _this.start(0);
  66530. }, delay);
  66531. return;
  66532. }
  66533. this._started = true;
  66534. this._stopped = false;
  66535. this._preWarmDone = false;
  66536. // Animations
  66537. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  66538. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  66539. }
  66540. };
  66541. /**
  66542. * Stops the particle system.
  66543. */
  66544. GPUParticleSystem.prototype.stop = function () {
  66545. this._stopped = true;
  66546. };
  66547. /**
  66548. * Remove all active particles
  66549. */
  66550. GPUParticleSystem.prototype.reset = function () {
  66551. this._releaseBuffers();
  66552. this._releaseVAOs();
  66553. this._currentActiveCount = 0;
  66554. this._targetIndex = 0;
  66555. };
  66556. /**
  66557. * Returns the string "GPUParticleSystem"
  66558. * @returns a string containing the class name
  66559. */
  66560. GPUParticleSystem.prototype.getClassName = function () {
  66561. return "GPUParticleSystem";
  66562. };
  66563. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  66564. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  66565. this._releaseBuffers();
  66566. return this;
  66567. };
  66568. /**
  66569. * Adds a new color gradient
  66570. * @param gradient defines the gradient to use (between 0 and 1)
  66571. * @param color1 defines the color to affect to the specified gradient
  66572. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  66573. * @returns the current particle system
  66574. */
  66575. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  66576. if (!this._colorGradients) {
  66577. this._colorGradients = [];
  66578. }
  66579. var colorGradient = new BABYLON.ColorGradient();
  66580. colorGradient.gradient = gradient;
  66581. colorGradient.color1 = color1;
  66582. this._colorGradients.push(colorGradient);
  66583. this._colorGradients.sort(function (a, b) {
  66584. if (a.gradient < b.gradient) {
  66585. return -1;
  66586. }
  66587. else if (a.gradient > b.gradient) {
  66588. return 1;
  66589. }
  66590. return 0;
  66591. });
  66592. if (this._colorGradientsTexture) {
  66593. this._colorGradientsTexture.dispose();
  66594. this._colorGradientsTexture = null;
  66595. }
  66596. this._releaseBuffers();
  66597. return this;
  66598. };
  66599. /**
  66600. * Remove a specific color gradient
  66601. * @param gradient defines the gradient to remove
  66602. * @returns the current particle system
  66603. */
  66604. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  66605. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  66606. this._colorGradientsTexture = null;
  66607. return this;
  66608. };
  66609. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  66610. var valueGradient = new BABYLON.FactorGradient();
  66611. valueGradient.gradient = gradient;
  66612. valueGradient.factor1 = factor;
  66613. factorGradients.push(valueGradient);
  66614. factorGradients.sort(function (a, b) {
  66615. if (a.gradient < b.gradient) {
  66616. return -1;
  66617. }
  66618. else if (a.gradient > b.gradient) {
  66619. return 1;
  66620. }
  66621. return 0;
  66622. });
  66623. this._releaseBuffers();
  66624. };
  66625. /**
  66626. * Adds a new size gradient
  66627. * @param gradient defines the gradient to use (between 0 and 1)
  66628. * @param factor defines the size factor to affect to the specified gradient
  66629. * @returns the current particle system
  66630. */
  66631. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  66632. if (!this._sizeGradients) {
  66633. this._sizeGradients = [];
  66634. }
  66635. this._addFactorGradient(this._sizeGradients, gradient, factor);
  66636. if (this._sizeGradientsTexture) {
  66637. this._sizeGradientsTexture.dispose();
  66638. this._sizeGradientsTexture = null;
  66639. }
  66640. this._releaseBuffers();
  66641. return this;
  66642. };
  66643. /**
  66644. * Remove a specific size gradient
  66645. * @param gradient defines the gradient to remove
  66646. * @returns the current particle system
  66647. */
  66648. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  66649. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  66650. this._sizeGradientsTexture = null;
  66651. return this;
  66652. };
  66653. /**
  66654. * Adds a new angular speed gradient
  66655. * @param gradient defines the gradient to use (between 0 and 1)
  66656. * @param factor defines the angular speed to affect to the specified gradient
  66657. * @returns the current particle system
  66658. */
  66659. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  66660. if (!this._angularSpeedGradients) {
  66661. this._angularSpeedGradients = [];
  66662. }
  66663. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  66664. if (this._angularSpeedGradientsTexture) {
  66665. this._angularSpeedGradientsTexture.dispose();
  66666. this._angularSpeedGradientsTexture = null;
  66667. }
  66668. this._releaseBuffers();
  66669. return this;
  66670. };
  66671. /**
  66672. * Remove a specific angular speed gradient
  66673. * @param gradient defines the gradient to remove
  66674. * @returns the current particle system
  66675. */
  66676. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  66677. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  66678. this._angularSpeedGradientsTexture = null;
  66679. return this;
  66680. };
  66681. /**
  66682. * Adds a new velocity gradient
  66683. * @param gradient defines the gradient to use (between 0 and 1)
  66684. * @param factor defines the velocity to affect to the specified gradient
  66685. * @returns the current particle system
  66686. */
  66687. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  66688. if (!this._velocityGradients) {
  66689. this._velocityGradients = [];
  66690. }
  66691. this._addFactorGradient(this._velocityGradients, gradient, factor);
  66692. if (this._velocityGradientsTexture) {
  66693. this._velocityGradientsTexture.dispose();
  66694. this._velocityGradientsTexture = null;
  66695. }
  66696. this._releaseBuffers();
  66697. return this;
  66698. };
  66699. /**
  66700. * Remove a specific velocity gradient
  66701. * @param gradient defines the gradient to remove
  66702. * @returns the current particle system
  66703. */
  66704. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  66705. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  66706. this._velocityGradientsTexture = null;
  66707. return this;
  66708. };
  66709. /**
  66710. * Adds a new limit velocity gradient
  66711. * @param gradient defines the gradient to use (between 0 and 1)
  66712. * @param factor defines the limit velocity value to affect to the specified gradient
  66713. * @returns the current particle system
  66714. */
  66715. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  66716. if (!this._limitVelocityGradients) {
  66717. this._limitVelocityGradients = [];
  66718. }
  66719. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  66720. if (this._limitVelocityGradientsTexture) {
  66721. this._limitVelocityGradientsTexture.dispose();
  66722. this._limitVelocityGradientsTexture = null;
  66723. }
  66724. this._releaseBuffers();
  66725. return this;
  66726. };
  66727. /**
  66728. * Remove a specific limit velocity gradient
  66729. * @param gradient defines the gradient to remove
  66730. * @returns the current particle system
  66731. */
  66732. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  66733. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  66734. this._limitVelocityGradientsTexture = null;
  66735. return this;
  66736. };
  66737. /**
  66738. * Adds a new drag gradient
  66739. * @param gradient defines the gradient to use (between 0 and 1)
  66740. * @param factor defines the drag value to affect to the specified gradient
  66741. * @returns the current particle system
  66742. */
  66743. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  66744. if (!this._dragGradients) {
  66745. this._dragGradients = [];
  66746. }
  66747. this._addFactorGradient(this._dragGradients, gradient, factor);
  66748. if (this._dragGradientsTexture) {
  66749. this._dragGradientsTexture.dispose();
  66750. this._dragGradientsTexture = null;
  66751. }
  66752. this._releaseBuffers();
  66753. return this;
  66754. };
  66755. /**
  66756. * Remove a specific drag gradient
  66757. * @param gradient defines the gradient to remove
  66758. * @returns the current particle system
  66759. */
  66760. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  66761. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  66762. this._dragGradientsTexture = null;
  66763. return this;
  66764. };
  66765. /**
  66766. * Not supported by GPUParticleSystem
  66767. * @param gradient defines the gradient to use (between 0 and 1)
  66768. * @param factor defines the emit rate value to affect to the specified gradient
  66769. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  66770. * @returns the current particle system
  66771. */
  66772. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  66773. // Do nothing as emit rate is not supported by GPUParticleSystem
  66774. return this;
  66775. };
  66776. /**
  66777. * Not supported by GPUParticleSystem
  66778. * @param gradient defines the gradient to remove
  66779. * @returns the current particle system
  66780. */
  66781. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  66782. // Do nothing as emit rate is not supported by GPUParticleSystem
  66783. return this;
  66784. };
  66785. /**
  66786. * Not supported by GPUParticleSystem
  66787. * @param gradient defines the gradient to use (between 0 and 1)
  66788. * @param factor defines the start size value to affect to the specified gradient
  66789. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  66790. * @returns the current particle system
  66791. */
  66792. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  66793. // Do nothing as start size is not supported by GPUParticleSystem
  66794. return this;
  66795. };
  66796. /**
  66797. * Not supported by GPUParticleSystem
  66798. * @param gradient defines the gradient to remove
  66799. * @returns the current particle system
  66800. */
  66801. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  66802. // Do nothing as start size is not supported by GPUParticleSystem
  66803. return this;
  66804. };
  66805. /**
  66806. * Not supported by GPUParticleSystem
  66807. * @param gradient defines the gradient to use (between 0 and 1)
  66808. * @param min defines the color remap minimal range
  66809. * @param max defines the color remap maximal range
  66810. * @returns the current particle system
  66811. */
  66812. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  66813. // Do nothing as start size is not supported by GPUParticleSystem
  66814. return this;
  66815. };
  66816. /**
  66817. * Not supported by GPUParticleSystem
  66818. * @param gradient defines the gradient to remove
  66819. * @returns the current particle system
  66820. */
  66821. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  66822. // Do nothing as start size is not supported by GPUParticleSystem
  66823. return this;
  66824. };
  66825. /**
  66826. * Not supported by GPUParticleSystem
  66827. * @param gradient defines the gradient to use (between 0 and 1)
  66828. * @param min defines the alpha remap minimal range
  66829. * @param max defines the alpha remap maximal range
  66830. * @returns the current particle system
  66831. */
  66832. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  66833. // Do nothing as start size is not supported by GPUParticleSystem
  66834. return this;
  66835. };
  66836. /**
  66837. * Not supported by GPUParticleSystem
  66838. * @param gradient defines the gradient to remove
  66839. * @returns the current particle system
  66840. */
  66841. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  66842. // Do nothing as start size is not supported by GPUParticleSystem
  66843. return this;
  66844. };
  66845. /**
  66846. * Not supported by GPUParticleSystem
  66847. * @param gradient defines the gradient to use (between 0 and 1)
  66848. * @param color defines the color to affect to the specified gradient
  66849. * @returns the current particle system
  66850. */
  66851. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  66852. //Not supported by GPUParticleSystem
  66853. return this;
  66854. };
  66855. /**
  66856. * Not supported by GPUParticleSystem
  66857. * @param gradient defines the gradient to remove
  66858. * @returns the current particle system
  66859. */
  66860. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  66861. //Not supported by GPUParticleSystem
  66862. return this;
  66863. };
  66864. /**
  66865. * Not supported by GPUParticleSystem
  66866. * @returns the list of ramp gradients
  66867. */
  66868. GPUParticleSystem.prototype.getRampGradients = function () {
  66869. return null;
  66870. };
  66871. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  66872. /**
  66873. * Not supported by GPUParticleSystem
  66874. * Gets or sets a boolean indicating that ramp gradients must be used
  66875. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  66876. */
  66877. get: function () {
  66878. //Not supported by GPUParticleSystem
  66879. return false;
  66880. },
  66881. set: function (value) {
  66882. //Not supported by GPUParticleSystem
  66883. },
  66884. enumerable: true,
  66885. configurable: true
  66886. });
  66887. /**
  66888. * Not supported by GPUParticleSystem
  66889. * @param gradient defines the gradient to use (between 0 and 1)
  66890. * @param factor defines the life time factor to affect to the specified gradient
  66891. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  66892. * @returns the current particle system
  66893. */
  66894. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  66895. //Not supported by GPUParticleSystem
  66896. return this;
  66897. };
  66898. /**
  66899. * Not supported by GPUParticleSystem
  66900. * @param gradient defines the gradient to remove
  66901. * @returns the current particle system
  66902. */
  66903. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  66904. //Not supported by GPUParticleSystem
  66905. return this;
  66906. };
  66907. GPUParticleSystem.prototype._reset = function () {
  66908. this._releaseBuffers();
  66909. };
  66910. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  66911. var updateVertexBuffers = {};
  66912. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  66913. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  66914. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  66915. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  66916. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  66917. var offset = 12;
  66918. if (!this._colorGradientsTexture) {
  66919. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  66920. offset += 4;
  66921. }
  66922. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  66923. offset += 3;
  66924. if (!this._isBillboardBased) {
  66925. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  66926. offset += 3;
  66927. }
  66928. if (this._angularSpeedGradientsTexture) {
  66929. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  66930. offset += 1;
  66931. }
  66932. else {
  66933. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  66934. offset += 2;
  66935. }
  66936. if (this._isAnimationSheetEnabled) {
  66937. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  66938. offset += 1;
  66939. if (this.spriteRandomStartCell) {
  66940. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  66941. offset += 1;
  66942. }
  66943. }
  66944. if (this.noiseTexture) {
  66945. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  66946. offset += 3;
  66947. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  66948. offset += 3;
  66949. }
  66950. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  66951. this._engine.bindArrayBuffer(null);
  66952. return vao;
  66953. };
  66954. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  66955. var renderVertexBuffers = {};
  66956. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  66957. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  66958. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  66959. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  66960. var offset = 12;
  66961. if (!this._colorGradientsTexture) {
  66962. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  66963. offset += 4;
  66964. }
  66965. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  66966. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  66967. }
  66968. offset += 3; // Direction
  66969. if (!this._isBillboardBased) {
  66970. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  66971. offset += 3;
  66972. }
  66973. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  66974. if (this._angularSpeedGradientsTexture) {
  66975. offset++;
  66976. }
  66977. else {
  66978. offset += 2;
  66979. }
  66980. if (this._isAnimationSheetEnabled) {
  66981. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  66982. offset += 1;
  66983. if (this.spriteRandomStartCell) {
  66984. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  66985. offset += 1;
  66986. }
  66987. }
  66988. if (this.noiseTexture) {
  66989. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  66990. offset += 3;
  66991. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  66992. offset += 3;
  66993. }
  66994. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  66995. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  66996. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  66997. this._engine.bindArrayBuffer(null);
  66998. return vao;
  66999. };
  67000. GPUParticleSystem.prototype._initialize = function (force) {
  67001. if (force === void 0) { force = false; }
  67002. if (this._buffer0 && !force) {
  67003. return;
  67004. }
  67005. var engine = this._scene.getEngine();
  67006. var data = new Array();
  67007. this._attributesStrideSize = 21;
  67008. this._targetIndex = 0;
  67009. if (!this.isBillboardBased) {
  67010. this._attributesStrideSize += 3;
  67011. }
  67012. if (this._colorGradientsTexture) {
  67013. this._attributesStrideSize -= 4;
  67014. }
  67015. if (this._angularSpeedGradientsTexture) {
  67016. this._attributesStrideSize -= 1;
  67017. }
  67018. if (this._isAnimationSheetEnabled) {
  67019. this._attributesStrideSize += 1;
  67020. if (this.spriteRandomStartCell) {
  67021. this._attributesStrideSize += 1;
  67022. }
  67023. }
  67024. if (this.noiseTexture) {
  67025. this._attributesStrideSize += 6;
  67026. }
  67027. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  67028. // position
  67029. data.push(0.0);
  67030. data.push(0.0);
  67031. data.push(0.0);
  67032. // Age and life
  67033. data.push(0.0); // create the particle as a dead one to create a new one at start
  67034. data.push(0.0);
  67035. // Seed
  67036. data.push(Math.random());
  67037. data.push(Math.random());
  67038. data.push(Math.random());
  67039. data.push(Math.random());
  67040. // Size
  67041. data.push(0.0);
  67042. data.push(0.0);
  67043. data.push(0.0);
  67044. if (!this._colorGradientsTexture) {
  67045. // color
  67046. data.push(0.0);
  67047. data.push(0.0);
  67048. data.push(0.0);
  67049. data.push(0.0);
  67050. }
  67051. // direction
  67052. data.push(0.0);
  67053. data.push(0.0);
  67054. data.push(0.0);
  67055. if (!this.isBillboardBased) {
  67056. // initialDirection
  67057. data.push(0.0);
  67058. data.push(0.0);
  67059. data.push(0.0);
  67060. }
  67061. // angle
  67062. data.push(0.0);
  67063. if (!this._angularSpeedGradientsTexture) {
  67064. data.push(0.0);
  67065. }
  67066. if (this._isAnimationSheetEnabled) {
  67067. data.push(0.0);
  67068. if (this.spriteRandomStartCell) {
  67069. data.push(0.0);
  67070. }
  67071. }
  67072. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  67073. data.push(Math.random());
  67074. data.push(Math.random());
  67075. data.push(Math.random());
  67076. data.push(Math.random());
  67077. data.push(Math.random());
  67078. data.push(Math.random());
  67079. }
  67080. }
  67081. // Sprite data
  67082. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  67083. -0.5, 0.5, 0, 1,
  67084. -0.5, -0.5, 0, 0,
  67085. 0.5, -0.5, 1, 0]);
  67086. // Buffers
  67087. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  67088. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  67089. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  67090. // Update VAO
  67091. this._updateVAO = [];
  67092. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  67093. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  67094. // Render VAO
  67095. this._renderVAO = [];
  67096. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  67097. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  67098. // Links
  67099. this._sourceBuffer = this._buffer0;
  67100. this._targetBuffer = this._buffer1;
  67101. };
  67102. /** @hidden */
  67103. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  67104. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  67105. if (this._isBillboardBased) {
  67106. defines += "\n#define BILLBOARD";
  67107. }
  67108. if (this._colorGradientsTexture) {
  67109. defines += "\n#define COLORGRADIENTS";
  67110. }
  67111. if (this._sizeGradientsTexture) {
  67112. defines += "\n#define SIZEGRADIENTS";
  67113. }
  67114. if (this._angularSpeedGradientsTexture) {
  67115. defines += "\n#define ANGULARSPEEDGRADIENTS";
  67116. }
  67117. if (this._velocityGradientsTexture) {
  67118. defines += "\n#define VELOCITYGRADIENTS";
  67119. }
  67120. if (this._limitVelocityGradientsTexture) {
  67121. defines += "\n#define LIMITVELOCITYGRADIENTS";
  67122. }
  67123. if (this._dragGradientsTexture) {
  67124. defines += "\n#define DRAGGRADIENTS";
  67125. }
  67126. if (this.isAnimationSheetEnabled) {
  67127. defines += "\n#define ANIMATESHEET";
  67128. if (this.spriteRandomStartCell) {
  67129. defines += "\n#define ANIMATESHEETRANDOMSTART";
  67130. }
  67131. }
  67132. if (this.noiseTexture) {
  67133. defines += "\n#define NOISE";
  67134. }
  67135. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  67136. return;
  67137. }
  67138. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  67139. if (!this._colorGradientsTexture) {
  67140. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  67141. }
  67142. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  67143. if (!this._isBillboardBased) {
  67144. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  67145. }
  67146. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  67147. if (this.isAnimationSheetEnabled) {
  67148. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  67149. if (this.spriteRandomStartCell) {
  67150. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  67151. }
  67152. }
  67153. if (this.noiseTexture) {
  67154. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  67155. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  67156. }
  67157. this._updateEffectOptions.defines = defines;
  67158. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  67159. };
  67160. /** @hidden */
  67161. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  67162. var defines = "";
  67163. if (this._scene.clipPlane) {
  67164. defines = "\n#define CLIPPLANE";
  67165. }
  67166. if (this._scene.clipPlane2) {
  67167. defines = "\n#define CLIPPLANE2";
  67168. }
  67169. if (this._scene.clipPlane3) {
  67170. defines = "\n#define CLIPPLANE3";
  67171. }
  67172. if (this._scene.clipPlane4) {
  67173. defines = "\n#define CLIPPLANE4";
  67174. }
  67175. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  67176. defines = "\n#define BLENDMULTIPLYMODE";
  67177. }
  67178. if (this._isBillboardBased) {
  67179. defines += "\n#define BILLBOARD";
  67180. switch (this.billboardMode) {
  67181. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  67182. defines += "\n#define BILLBOARDY";
  67183. break;
  67184. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  67185. defines += "\n#define BILLBOARDSTRETCHED";
  67186. break;
  67187. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  67188. default:
  67189. break;
  67190. }
  67191. }
  67192. if (this._colorGradientsTexture) {
  67193. defines += "\n#define COLORGRADIENTS";
  67194. }
  67195. if (this.isAnimationSheetEnabled) {
  67196. defines += "\n#define ANIMATESHEET";
  67197. }
  67198. if (this._imageProcessingConfiguration) {
  67199. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  67200. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  67201. }
  67202. if (this._renderEffect && this._renderEffect.defines === defines) {
  67203. return;
  67204. }
  67205. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  67206. var samplers = ["textureSampler", "colorGradientSampler"];
  67207. if (BABYLON.ImageProcessingConfiguration) {
  67208. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  67209. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  67210. }
  67211. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  67212. };
  67213. /**
  67214. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  67215. * @param preWarm defines if we are in the pre-warmimg phase
  67216. */
  67217. GPUParticleSystem.prototype.animate = function (preWarm) {
  67218. if (preWarm === void 0) { preWarm = false; }
  67219. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  67220. this._actualFrame += this._timeDelta;
  67221. if (!this._stopped) {
  67222. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  67223. this.stop();
  67224. }
  67225. }
  67226. };
  67227. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  67228. var texture = this[textureName];
  67229. if (!factorGradients || !factorGradients.length || texture) {
  67230. return;
  67231. }
  67232. var data = new Float32Array(this._rawTextureWidth);
  67233. for (var x = 0; x < this._rawTextureWidth; x++) {
  67234. var ratio = x / this._rawTextureWidth;
  67235. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  67236. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  67237. });
  67238. }
  67239. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67240. };
  67241. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  67242. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  67243. };
  67244. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  67245. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  67246. };
  67247. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  67248. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  67249. };
  67250. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  67251. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  67252. };
  67253. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  67254. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  67255. };
  67256. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  67257. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  67258. return;
  67259. }
  67260. var data = new Uint8Array(this._rawTextureWidth * 4);
  67261. var tmpColor = BABYLON.Tmp.Color4[0];
  67262. for (var x = 0; x < this._rawTextureWidth; x++) {
  67263. var ratio = x / this._rawTextureWidth;
  67264. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  67265. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  67266. data[x * 4] = tmpColor.r * 255;
  67267. data[x * 4 + 1] = tmpColor.g * 255;
  67268. data[x * 4 + 2] = tmpColor.b * 255;
  67269. data[x * 4 + 3] = tmpColor.a * 255;
  67270. });
  67271. }
  67272. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67273. };
  67274. /**
  67275. * Renders the particle system in its current state
  67276. * @param preWarm defines if the system should only update the particles but not render them
  67277. * @returns the current number of particles
  67278. */
  67279. GPUParticleSystem.prototype.render = function (preWarm) {
  67280. if (preWarm === void 0) { preWarm = false; }
  67281. if (!this._started) {
  67282. return 0;
  67283. }
  67284. this._createColorGradientTexture();
  67285. this._createSizeGradientTexture();
  67286. this._createAngularSpeedGradientTexture();
  67287. this._createVelocityGradientTexture();
  67288. this._createLimitVelocityGradientTexture();
  67289. this._createDragGradientTexture();
  67290. this._recreateUpdateEffect();
  67291. this._recreateRenderEffect();
  67292. if (!this.isReady()) {
  67293. return 0;
  67294. }
  67295. if (!preWarm) {
  67296. if (!this._preWarmDone && this.preWarmCycles) {
  67297. for (var index = 0; index < this.preWarmCycles; index++) {
  67298. this.animate(true);
  67299. this.render(true);
  67300. }
  67301. this._preWarmDone = true;
  67302. }
  67303. if (this._currentRenderId === this._scene.getFrameId()) {
  67304. return 0;
  67305. }
  67306. this._currentRenderId = this._scene.getFrameId();
  67307. }
  67308. // Get everything ready to render
  67309. this._initialize();
  67310. this._accumulatedCount += this.emitRate * this._timeDelta;
  67311. if (this._accumulatedCount > 1) {
  67312. var intPart = this._accumulatedCount | 0;
  67313. this._accumulatedCount -= intPart;
  67314. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  67315. }
  67316. if (!this._currentActiveCount) {
  67317. return 0;
  67318. }
  67319. // Enable update effect
  67320. this._engine.enableEffect(this._updateEffect);
  67321. this._engine.setState(false);
  67322. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  67323. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  67324. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  67325. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  67326. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  67327. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  67328. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  67329. if (!this._colorGradientsTexture) {
  67330. this._updateEffect.setDirectColor4("color1", this.color1);
  67331. this._updateEffect.setDirectColor4("color2", this.color2);
  67332. }
  67333. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  67334. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  67335. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  67336. this._updateEffect.setVector3("gravity", this.gravity);
  67337. if (this._sizeGradientsTexture) {
  67338. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  67339. }
  67340. if (this._angularSpeedGradientsTexture) {
  67341. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  67342. }
  67343. if (this._velocityGradientsTexture) {
  67344. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  67345. }
  67346. if (this._limitVelocityGradientsTexture) {
  67347. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  67348. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  67349. }
  67350. if (this._dragGradientsTexture) {
  67351. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  67352. }
  67353. if (this.particleEmitterType) {
  67354. this.particleEmitterType.applyToShader(this._updateEffect);
  67355. }
  67356. if (this._isAnimationSheetEnabled) {
  67357. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  67358. }
  67359. if (this.noiseTexture) {
  67360. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  67361. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  67362. }
  67363. var emitterWM;
  67364. if (this.emitter.position) {
  67365. var emitterMesh = this.emitter;
  67366. emitterWM = emitterMesh.getWorldMatrix();
  67367. }
  67368. else {
  67369. var emitterPosition = this.emitter;
  67370. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  67371. }
  67372. this._updateEffect.setMatrix("emitterWM", emitterWM);
  67373. // Bind source VAO
  67374. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  67375. // Update
  67376. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  67377. this._engine.setRasterizerState(false);
  67378. this._engine.beginTransformFeedback(true);
  67379. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  67380. this._engine.endTransformFeedback();
  67381. this._engine.setRasterizerState(true);
  67382. this._engine.bindTransformFeedbackBuffer(null);
  67383. if (!preWarm) {
  67384. // Enable render effect
  67385. this._engine.enableEffect(this._renderEffect);
  67386. var viewMatrix = this._scene.getViewMatrix();
  67387. this._renderEffect.setMatrix("view", viewMatrix);
  67388. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  67389. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  67390. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  67391. if (this._colorGradientsTexture) {
  67392. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  67393. }
  67394. else {
  67395. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  67396. }
  67397. if (this._isAnimationSheetEnabled && this.particleTexture) {
  67398. var baseSize = this.particleTexture.getBaseSize();
  67399. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  67400. }
  67401. if (this._isBillboardBased) {
  67402. var camera = this._scene.activeCamera;
  67403. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  67404. }
  67405. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  67406. var invView = viewMatrix.clone();
  67407. invView.invert();
  67408. this._renderEffect.setMatrix("invView", invView);
  67409. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  67410. }
  67411. // image processing
  67412. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  67413. this._imageProcessingConfiguration.bind(this._renderEffect);
  67414. }
  67415. // Draw order
  67416. switch (this.blendMode) {
  67417. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  67418. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  67419. break;
  67420. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  67421. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  67422. break;
  67423. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  67424. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67425. break;
  67426. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  67427. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  67428. break;
  67429. }
  67430. if (this.forceDepthWrite) {
  67431. this._engine.setDepthWrite(true);
  67432. }
  67433. // Bind source VAO
  67434. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  67435. // Render
  67436. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  67437. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67438. }
  67439. // Switch VAOs
  67440. this._targetIndex++;
  67441. if (this._targetIndex === 2) {
  67442. this._targetIndex = 0;
  67443. }
  67444. // Switch buffers
  67445. var tmpBuffer = this._sourceBuffer;
  67446. this._sourceBuffer = this._targetBuffer;
  67447. this._targetBuffer = tmpBuffer;
  67448. return this._currentActiveCount;
  67449. };
  67450. /**
  67451. * Rebuilds the particle system
  67452. */
  67453. GPUParticleSystem.prototype.rebuild = function () {
  67454. this._initialize(true);
  67455. };
  67456. GPUParticleSystem.prototype._releaseBuffers = function () {
  67457. if (this._buffer0) {
  67458. this._buffer0.dispose();
  67459. this._buffer0 = null;
  67460. }
  67461. if (this._buffer1) {
  67462. this._buffer1.dispose();
  67463. this._buffer1 = null;
  67464. }
  67465. if (this._spriteBuffer) {
  67466. this._spriteBuffer.dispose();
  67467. this._spriteBuffer = null;
  67468. }
  67469. };
  67470. GPUParticleSystem.prototype._releaseVAOs = function () {
  67471. if (!this._updateVAO) {
  67472. return;
  67473. }
  67474. for (var index = 0; index < this._updateVAO.length; index++) {
  67475. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  67476. }
  67477. this._updateVAO = [];
  67478. for (var index = 0; index < this._renderVAO.length; index++) {
  67479. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  67480. }
  67481. this._renderVAO = [];
  67482. };
  67483. /**
  67484. * Disposes the particle system and free the associated resources
  67485. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  67486. */
  67487. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  67488. if (disposeTexture === void 0) { disposeTexture = true; }
  67489. var index = this._scene.particleSystems.indexOf(this);
  67490. if (index > -1) {
  67491. this._scene.particleSystems.splice(index, 1);
  67492. }
  67493. this._releaseBuffers();
  67494. this._releaseVAOs();
  67495. if (this._colorGradientsTexture) {
  67496. this._colorGradientsTexture.dispose();
  67497. this._colorGradientsTexture = null;
  67498. }
  67499. if (this._sizeGradientsTexture) {
  67500. this._sizeGradientsTexture.dispose();
  67501. this._sizeGradientsTexture = null;
  67502. }
  67503. if (this._angularSpeedGradientsTexture) {
  67504. this._angularSpeedGradientsTexture.dispose();
  67505. this._angularSpeedGradientsTexture = null;
  67506. }
  67507. if (this._velocityGradientsTexture) {
  67508. this._velocityGradientsTexture.dispose();
  67509. this._velocityGradientsTexture = null;
  67510. }
  67511. if (this._limitVelocityGradientsTexture) {
  67512. this._limitVelocityGradientsTexture.dispose();
  67513. this._limitVelocityGradientsTexture = null;
  67514. }
  67515. if (this._dragGradientsTexture) {
  67516. this._dragGradientsTexture.dispose();
  67517. this._dragGradientsTexture = null;
  67518. }
  67519. if (this._randomTexture) {
  67520. this._randomTexture.dispose();
  67521. this._randomTexture = null;
  67522. }
  67523. if (this._randomTexture2) {
  67524. this._randomTexture2.dispose();
  67525. this._randomTexture2 = null;
  67526. }
  67527. if (disposeTexture && this.particleTexture) {
  67528. this.particleTexture.dispose();
  67529. this.particleTexture = null;
  67530. }
  67531. if (disposeTexture && this.noiseTexture) {
  67532. this.noiseTexture.dispose();
  67533. this.noiseTexture = null;
  67534. }
  67535. // Callback
  67536. this.onDisposeObservable.notifyObservers(this);
  67537. this.onDisposeObservable.clear();
  67538. };
  67539. /**
  67540. * Clones the particle system.
  67541. * @param name The name of the cloned object
  67542. * @param newEmitter The new emitter to use
  67543. * @returns the cloned particle system
  67544. */
  67545. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  67546. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  67547. BABYLON.Tools.DeepCopy(this, result);
  67548. if (newEmitter === undefined) {
  67549. newEmitter = this.emitter;
  67550. }
  67551. result.emitter = newEmitter;
  67552. if (this.particleTexture) {
  67553. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  67554. }
  67555. return result;
  67556. };
  67557. /**
  67558. * Serializes the particle system to a JSON object.
  67559. * @returns the JSON object
  67560. */
  67561. GPUParticleSystem.prototype.serialize = function () {
  67562. var serializationObject = {};
  67563. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  67564. serializationObject.activeParticleCount = this.activeParticleCount;
  67565. return serializationObject;
  67566. };
  67567. /**
  67568. * Parses a JSON object to create a GPU particle system.
  67569. * @param parsedParticleSystem The JSON object to parse
  67570. * @param scene The scene to create the particle system in
  67571. * @param rootUrl The root url to use to load external dependencies like texture
  67572. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  67573. * @returns the parsed GPU particle system
  67574. */
  67575. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  67576. if (doNotStart === void 0) { doNotStart = false; }
  67577. var name = parsedParticleSystem.name;
  67578. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  67579. if (parsedParticleSystem.activeParticleCount) {
  67580. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  67581. }
  67582. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  67583. // Auto start
  67584. if (parsedParticleSystem.preventAutoStart) {
  67585. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  67586. }
  67587. if (!doNotStart && !particleSystem.preventAutoStart) {
  67588. particleSystem.start();
  67589. }
  67590. return particleSystem;
  67591. };
  67592. return GPUParticleSystem;
  67593. }(BABYLON.BaseParticleSystem));
  67594. BABYLON.GPUParticleSystem = GPUParticleSystem;
  67595. })(BABYLON || (BABYLON = {}));
  67596. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  67597. var BABYLON;
  67598. (function (BABYLON) {
  67599. /**
  67600. * Represents one particle of a solid particle system.
  67601. */
  67602. var SolidParticle = /** @class */ (function () {
  67603. /**
  67604. * Creates a Solid Particle object.
  67605. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  67606. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  67607. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  67608. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  67609. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  67610. * @param shapeId (integer) is the model shape identifier in the SPS.
  67611. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  67612. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  67613. */
  67614. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  67615. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  67616. /**
  67617. * particle global index
  67618. */
  67619. this.idx = 0;
  67620. /**
  67621. * The color of the particle
  67622. */
  67623. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  67624. /**
  67625. * The world space position of the particle.
  67626. */
  67627. this.position = BABYLON.Vector3.Zero();
  67628. /**
  67629. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  67630. */
  67631. this.rotation = BABYLON.Vector3.Zero();
  67632. /**
  67633. * The scaling of the particle.
  67634. */
  67635. this.scaling = BABYLON.Vector3.One();
  67636. /**
  67637. * The uvs of the particle.
  67638. */
  67639. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  67640. /**
  67641. * The current speed of the particle.
  67642. */
  67643. this.velocity = BABYLON.Vector3.Zero();
  67644. /**
  67645. * The pivot point in the particle local space.
  67646. */
  67647. this.pivot = BABYLON.Vector3.Zero();
  67648. /**
  67649. * Must the particle be translated from its pivot point in its local space ?
  67650. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  67651. * Default : false
  67652. */
  67653. this.translateFromPivot = false;
  67654. /**
  67655. * Is the particle active or not ?
  67656. */
  67657. this.alive = true;
  67658. /**
  67659. * Is the particle visible or not ?
  67660. */
  67661. this.isVisible = true;
  67662. /**
  67663. * Index of this particle in the global "positions" array (Internal use)
  67664. * @hidden
  67665. */
  67666. this._pos = 0;
  67667. /**
  67668. * @hidden Index of this particle in the global "indices" array (Internal use)
  67669. */
  67670. this._ind = 0;
  67671. /**
  67672. * ModelShape id of this particle
  67673. */
  67674. this.shapeId = 0;
  67675. /**
  67676. * Index of the particle in its shape id (Internal use)
  67677. */
  67678. this.idxInShape = 0;
  67679. /**
  67680. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  67681. */
  67682. this._stillInvisible = false;
  67683. /**
  67684. * @hidden Last computed particle rotation matrix
  67685. */
  67686. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  67687. /**
  67688. * Parent particle Id, if any.
  67689. * Default null.
  67690. */
  67691. this.parentId = null;
  67692. /**
  67693. * @hidden Internal global position in the SPS.
  67694. */
  67695. this._globalPosition = BABYLON.Vector3.Zero();
  67696. this.idx = particleIndex;
  67697. this._pos = positionIndex;
  67698. this._ind = indiceIndex;
  67699. this._model = model;
  67700. this.shapeId = shapeId;
  67701. this.idxInShape = idxInShape;
  67702. this._sps = sps;
  67703. if (modelBoundingInfo) {
  67704. this._modelBoundingInfo = modelBoundingInfo;
  67705. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  67706. }
  67707. }
  67708. Object.defineProperty(SolidParticle.prototype, "scale", {
  67709. /**
  67710. * Legacy support, changed scale to scaling
  67711. */
  67712. get: function () {
  67713. return this.scaling;
  67714. },
  67715. /**
  67716. * Legacy support, changed scale to scaling
  67717. */
  67718. set: function (scale) {
  67719. this.scaling = scale;
  67720. },
  67721. enumerable: true,
  67722. configurable: true
  67723. });
  67724. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  67725. /**
  67726. * Legacy support, changed quaternion to rotationQuaternion
  67727. */
  67728. get: function () {
  67729. return this.rotationQuaternion;
  67730. },
  67731. /**
  67732. * Legacy support, changed quaternion to rotationQuaternion
  67733. */
  67734. set: function (q) {
  67735. this.rotationQuaternion = q;
  67736. },
  67737. enumerable: true,
  67738. configurable: true
  67739. });
  67740. /**
  67741. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  67742. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  67743. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  67744. * @returns true if it intersects
  67745. */
  67746. SolidParticle.prototype.intersectsMesh = function (target) {
  67747. if (!this._boundingInfo || !target._boundingInfo) {
  67748. return false;
  67749. }
  67750. if (this._sps._bSphereOnly) {
  67751. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  67752. }
  67753. return this._boundingInfo.intersects(target._boundingInfo, false);
  67754. };
  67755. /**
  67756. * get the rotation matrix of the particle
  67757. * @hidden
  67758. */
  67759. SolidParticle.prototype.getRotationMatrix = function (m) {
  67760. var quaternion;
  67761. if (this.rotationQuaternion) {
  67762. quaternion = this.rotationQuaternion;
  67763. }
  67764. else {
  67765. quaternion = BABYLON.Tmp.Quaternion[0];
  67766. var rotation = this.rotation;
  67767. BABYLON.Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  67768. }
  67769. quaternion.toRotationMatrix(m);
  67770. };
  67771. return SolidParticle;
  67772. }());
  67773. BABYLON.SolidParticle = SolidParticle;
  67774. /**
  67775. * Represents the shape of the model used by one particle of a solid particle system.
  67776. * SPS internal tool, don't use it manually.
  67777. */
  67778. var ModelShape = /** @class */ (function () {
  67779. /**
  67780. * 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.
  67781. * SPS internal tool, don't use it manually.
  67782. * @hidden
  67783. */
  67784. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  67785. /**
  67786. * length of the shape in the model indices array (internal use)
  67787. * @hidden
  67788. */
  67789. this._indicesLength = 0;
  67790. this.shapeID = id;
  67791. this._shape = shape;
  67792. this._indicesLength = indicesLength;
  67793. this._shapeUV = shapeUV;
  67794. this._positionFunction = posFunction;
  67795. this._vertexFunction = vtxFunction;
  67796. }
  67797. return ModelShape;
  67798. }());
  67799. BABYLON.ModelShape = ModelShape;
  67800. /**
  67801. * Represents a Depth Sorted Particle in the solid particle system.
  67802. */
  67803. var DepthSortedParticle = /** @class */ (function () {
  67804. function DepthSortedParticle() {
  67805. /**
  67806. * Index of the particle in the "indices" array
  67807. */
  67808. this.ind = 0;
  67809. /**
  67810. * Length of the particle shape in the "indices" array
  67811. */
  67812. this.indicesLength = 0;
  67813. /**
  67814. * Squared distance from the particle to the camera
  67815. */
  67816. this.sqDistance = 0.0;
  67817. }
  67818. return DepthSortedParticle;
  67819. }());
  67820. BABYLON.DepthSortedParticle = DepthSortedParticle;
  67821. })(BABYLON || (BABYLON = {}));
  67822. //# sourceMappingURL=babylon.solidParticle.js.map
  67823. var BABYLON;
  67824. (function (BABYLON) {
  67825. var depthSortFunction = function (p1, p2) { return p2.sqDistance - p1.sqDistance; };
  67826. /**
  67827. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  67828. *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.
  67829. * The SPS is also a particle system. It provides some methods to manage the particles.
  67830. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  67831. *
  67832. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  67833. */
  67834. var SolidParticleSystem = /** @class */ (function () {
  67835. /**
  67836. * Creates a SPS (Solid Particle System) object.
  67837. * @param name (String) is the SPS name, this will be the underlying mesh name.
  67838. * @param scene (Scene) is the scene in which the SPS is added.
  67839. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  67840. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  67841. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  67842. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  67843. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  67844. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  67845. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  67846. */
  67847. function SolidParticleSystem(name, scene, options) {
  67848. /**
  67849. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  67850. * Example : var p = SPS.particles[i];
  67851. */
  67852. this.particles = new Array();
  67853. /**
  67854. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  67855. */
  67856. this.nbParticles = 0;
  67857. /**
  67858. * If the particles must ever face the camera (default false). Useful for planar particles.
  67859. */
  67860. this.billboard = false;
  67861. /**
  67862. * Recompute normals when adding a shape
  67863. */
  67864. this.recomputeNormals = true;
  67865. /**
  67866. * This a counter ofr your own usage. It's not set by any SPS functions.
  67867. */
  67868. this.counter = 0;
  67869. /**
  67870. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  67871. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  67872. */
  67873. this.vars = {};
  67874. /**
  67875. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  67876. * @hidden
  67877. */
  67878. this._bSphereOnly = false;
  67879. /**
  67880. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  67881. * @hidden
  67882. */
  67883. this._bSphereRadiusFactor = 1.0;
  67884. this._positions = new Array();
  67885. this._indices = new Array();
  67886. this._normals = new Array();
  67887. this._colors = new Array();
  67888. this._uvs = new Array();
  67889. this._index = 0; // indices index
  67890. this._updatable = true;
  67891. this._pickable = false;
  67892. this._isVisibilityBoxLocked = false;
  67893. this._alwaysVisible = false;
  67894. this._depthSort = false;
  67895. this._shapeCounter = 0;
  67896. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  67897. this._color = new BABYLON.Color4(0, 0, 0, 0);
  67898. this._computeParticleColor = true;
  67899. this._computeParticleTexture = true;
  67900. this._computeParticleRotation = true;
  67901. this._computeParticleVertex = false;
  67902. this._computeBoundingBox = false;
  67903. this._depthSortParticles = true;
  67904. this._mustUnrotateFixedNormals = false;
  67905. this._particlesIntersect = false;
  67906. this._needs32Bits = false;
  67907. this.name = name;
  67908. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67909. this._camera = scene.activeCamera;
  67910. this._pickable = options ? options.isPickable : false;
  67911. this._depthSort = options ? options.enableDepthSort : false;
  67912. this._particlesIntersect = options ? options.particleIntersection : false;
  67913. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  67914. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  67915. if (options && options.updatable !== undefined) {
  67916. this._updatable = options.updatable;
  67917. }
  67918. else {
  67919. this._updatable = true;
  67920. }
  67921. if (this._pickable) {
  67922. this.pickedParticles = [];
  67923. }
  67924. if (this._depthSort) {
  67925. this.depthSortedParticles = [];
  67926. }
  67927. }
  67928. /**
  67929. * Builds the SPS underlying mesh. Returns a standard Mesh.
  67930. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  67931. * @returns the created mesh
  67932. */
  67933. SolidParticleSystem.prototype.buildMesh = function () {
  67934. if (this.nbParticles === 0) {
  67935. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  67936. this.addShape(triangle, 1);
  67937. triangle.dispose();
  67938. }
  67939. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  67940. this._positions32 = new Float32Array(this._positions);
  67941. this._uvs32 = new Float32Array(this._uvs);
  67942. this._colors32 = new Float32Array(this._colors);
  67943. if (this.recomputeNormals) {
  67944. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  67945. }
  67946. this._normals32 = new Float32Array(this._normals);
  67947. this._fixedNormal32 = new Float32Array(this._normals);
  67948. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  67949. this._unrotateFixedNormals();
  67950. }
  67951. var vertexData = new BABYLON.VertexData();
  67952. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  67953. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  67954. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  67955. if (this._uvs32.length > 0) {
  67956. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  67957. }
  67958. if (this._colors32.length > 0) {
  67959. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  67960. }
  67961. var mesh = new BABYLON.Mesh(this.name, this._scene);
  67962. vertexData.applyToMesh(mesh, this._updatable);
  67963. this.mesh = mesh;
  67964. this.mesh.isPickable = this._pickable;
  67965. // free memory
  67966. if (!this._depthSort) {
  67967. this._indices = null;
  67968. }
  67969. this._positions = null;
  67970. this._normals = null;
  67971. this._uvs = null;
  67972. this._colors = null;
  67973. if (!this._updatable) {
  67974. this.particles.length = 0;
  67975. }
  67976. return mesh;
  67977. };
  67978. /**
  67979. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  67980. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  67981. * Thus the particles generated from `digest()` have their property `position` set yet.
  67982. * @param mesh ( Mesh ) is the mesh to be digested
  67983. * @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
  67984. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  67985. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  67986. * @returns the current SPS
  67987. */
  67988. SolidParticleSystem.prototype.digest = function (mesh, options) {
  67989. var size = (options && options.facetNb) || 1;
  67990. var number = (options && options.number) || 0;
  67991. var delta = (options && options.delta) || 0;
  67992. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67993. var meshInd = mesh.getIndices();
  67994. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67995. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67996. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67997. var f = 0; // facet counter
  67998. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  67999. // compute size from number
  68000. if (number) {
  68001. number = (number > totalFacets) ? totalFacets : number;
  68002. size = Math.round(totalFacets / number);
  68003. delta = 0;
  68004. }
  68005. else {
  68006. size = (size > totalFacets) ? totalFacets : size;
  68007. }
  68008. var facetPos = []; // submesh positions
  68009. var facetInd = []; // submesh indices
  68010. var facetUV = []; // submesh UV
  68011. var facetCol = []; // submesh colors
  68012. var barycenter = BABYLON.Vector3.Zero();
  68013. var sizeO = size;
  68014. while (f < totalFacets) {
  68015. size = sizeO + Math.floor((1 + delta) * Math.random());
  68016. if (f > totalFacets - size) {
  68017. size = totalFacets - f;
  68018. }
  68019. // reset temp arrays
  68020. facetPos.length = 0;
  68021. facetInd.length = 0;
  68022. facetUV.length = 0;
  68023. facetCol.length = 0;
  68024. // iterate over "size" facets
  68025. var fi = 0;
  68026. for (var j = f * 3; j < (f + size) * 3; j++) {
  68027. facetInd.push(fi);
  68028. var i = meshInd[j];
  68029. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  68030. if (meshUV) {
  68031. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  68032. }
  68033. if (meshCol) {
  68034. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  68035. }
  68036. fi++;
  68037. }
  68038. // create a model shape for each single particle
  68039. var idx = this.nbParticles;
  68040. var shape = this._posToShape(facetPos);
  68041. var shapeUV = this._uvsToShapeUV(facetUV);
  68042. // compute the barycenter of the shape
  68043. var v;
  68044. for (v = 0; v < shape.length; v++) {
  68045. barycenter.addInPlace(shape[v]);
  68046. }
  68047. barycenter.scaleInPlace(1 / shape.length);
  68048. // shift the shape from its barycenter to the origin
  68049. for (v = 0; v < shape.length; v++) {
  68050. shape[v].subtractInPlace(barycenter);
  68051. }
  68052. var bInfo;
  68053. if (this._particlesIntersect) {
  68054. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  68055. }
  68056. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  68057. // add the particle in the SPS
  68058. var currentPos = this._positions.length;
  68059. var currentInd = this._indices.length;
  68060. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  68061. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  68062. // initialize the particle position
  68063. this.particles[this.nbParticles].position.addInPlace(barycenter);
  68064. this._index += shape.length;
  68065. idx++;
  68066. this.nbParticles++;
  68067. this._shapeCounter++;
  68068. f += size;
  68069. }
  68070. return this;
  68071. };
  68072. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  68073. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  68074. var index = 0;
  68075. var idx = 0;
  68076. var tmpNormal = BABYLON.Tmp.Vector3[0];
  68077. var quaternion = BABYLON.Tmp.Quaternion[0];
  68078. var invertedRotMatrix = BABYLON.Tmp.Matrix[0];
  68079. for (var p = 0; p < this.particles.length; p++) {
  68080. var particle = this.particles[p];
  68081. var shape = particle._model._shape;
  68082. // computing the inverse of the rotation matrix from the quaternion
  68083. // is equivalent to computing the matrix of the inverse quaternion, i.e of the conjugate quaternion
  68084. if (particle.rotationQuaternion) {
  68085. particle.rotationQuaternion.conjugateToRef(quaternion);
  68086. }
  68087. else {
  68088. var rotation = particle.rotation;
  68089. BABYLON.Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  68090. quaternion.conjugateInPlace();
  68091. }
  68092. quaternion.toRotationMatrix(invertedRotMatrix);
  68093. for (var pt = 0; pt < shape.length; pt++) {
  68094. idx = index + pt * 3;
  68095. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], invertedRotMatrix, tmpNormal);
  68096. tmpNormal.toArray(this._fixedNormal32, idx);
  68097. }
  68098. index = idx + 3;
  68099. }
  68100. };
  68101. //reset copy
  68102. SolidParticleSystem.prototype._resetCopy = function () {
  68103. var copy = this._copy;
  68104. copy.position.setAll(0);
  68105. copy.rotation.setAll(0);
  68106. copy.rotationQuaternion = null;
  68107. copy.scaling.setAll(1);
  68108. copy.uvs.copyFromFloats(0.0, 0.0, 1.0, 1.0);
  68109. copy.color = null;
  68110. copy.translateFromPivot = false;
  68111. };
  68112. // _meshBuilder : inserts the shape model in the global SPS mesh
  68113. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  68114. var i;
  68115. var u = 0;
  68116. var c = 0;
  68117. var n = 0;
  68118. this._resetCopy();
  68119. var copy = this._copy;
  68120. if (options && options.positionFunction) { // call to custom positionFunction
  68121. options.positionFunction(copy, idx, idxInShape);
  68122. this._mustUnrotateFixedNormals = true;
  68123. }
  68124. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68125. var tmpVertex = BABYLON.Tmp.Vector3[0];
  68126. var tmpRotated = BABYLON.Tmp.Vector3[1];
  68127. var pivotBackTranslation = BABYLON.Tmp.Vector3[2];
  68128. var scaledPivot = BABYLON.Tmp.Vector3[3];
  68129. copy.getRotationMatrix(rotMatrix);
  68130. copy.pivot.multiplyToRef(copy.scaling, scaledPivot);
  68131. if (copy.translateFromPivot) {
  68132. pivotBackTranslation.setAll(0.0);
  68133. }
  68134. else {
  68135. pivotBackTranslation.copyFrom(scaledPivot);
  68136. }
  68137. for (i = 0; i < shape.length; i++) {
  68138. tmpVertex.copyFrom(shape[i]);
  68139. if (options && options.vertexFunction) {
  68140. options.vertexFunction(copy, tmpVertex, i);
  68141. }
  68142. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  68143. BABYLON.Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  68144. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position);
  68145. positions.push(tmpRotated.x, tmpRotated.y, tmpRotated.z);
  68146. if (meshUV) {
  68147. var copyUvs = copy.uvs;
  68148. uvs.push((copyUvs.z - copyUvs.x) * meshUV[u] + copyUvs.x, (copyUvs.w - copyUvs.y) * meshUV[u + 1] + copyUvs.y);
  68149. u += 2;
  68150. }
  68151. if (copy.color) {
  68152. this._color = copy.color;
  68153. }
  68154. else {
  68155. var color = this._color;
  68156. if (meshCol && meshCol[c] !== undefined) {
  68157. color.r = meshCol[c];
  68158. color.g = meshCol[c + 1];
  68159. color.b = meshCol[c + 2];
  68160. color.a = meshCol[c + 3];
  68161. }
  68162. else {
  68163. color.r = 1.0;
  68164. color.g = 1.0;
  68165. color.b = 1.0;
  68166. color.a = 1.0;
  68167. }
  68168. }
  68169. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  68170. c += 4;
  68171. if (!this.recomputeNormals && meshNor) {
  68172. tmpVertex.x = meshNor[n];
  68173. tmpVertex.y = meshNor[n + 1];
  68174. tmpVertex.z = meshNor[n + 2];
  68175. BABYLON.Vector3.TransformNormalToRef(tmpVertex, rotMatrix, tmpVertex);
  68176. normals.push(tmpVertex.x, tmpVertex.y, tmpVertex.z);
  68177. n += 3;
  68178. }
  68179. }
  68180. for (i = 0; i < meshInd.length; i++) {
  68181. var current_ind = p + meshInd[i];
  68182. indices.push(current_ind);
  68183. if (current_ind > 65535) {
  68184. this._needs32Bits = true;
  68185. }
  68186. }
  68187. if (this._pickable) {
  68188. var nbfaces = meshInd.length / 3;
  68189. for (i = 0; i < nbfaces; i++) {
  68190. this.pickedParticles.push({ idx: idx, faceId: i });
  68191. }
  68192. }
  68193. if (this._depthSort) {
  68194. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  68195. }
  68196. return copy;
  68197. };
  68198. // returns a shape array from positions array
  68199. SolidParticleSystem.prototype._posToShape = function (positions) {
  68200. var shape = [];
  68201. for (var i = 0; i < positions.length; i += 3) {
  68202. shape.push(BABYLON.Vector3.FromArray(positions, i));
  68203. }
  68204. return shape;
  68205. };
  68206. // returns a shapeUV array from a Vector4 uvs
  68207. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  68208. var shapeUV = [];
  68209. if (uvs) {
  68210. for (var i = 0; i < uvs.length; i++) {
  68211. shapeUV.push(uvs[i]);
  68212. }
  68213. }
  68214. return shapeUV;
  68215. };
  68216. // adds a new particle object in the particles array
  68217. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  68218. if (bInfo === void 0) { bInfo = null; }
  68219. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  68220. this.particles.push(sp);
  68221. return sp;
  68222. };
  68223. /**
  68224. * Adds some particles to the SPS from the model shape. Returns the shape id.
  68225. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  68226. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  68227. * @param nb (positive integer) the number of particles to be created from this model
  68228. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  68229. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  68230. * @returns the number of shapes in the system
  68231. */
  68232. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  68233. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68234. var meshInd = mesh.getIndices();
  68235. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68236. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68237. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68238. var bbInfo;
  68239. if (this._particlesIntersect) {
  68240. bbInfo = mesh.getBoundingInfo();
  68241. }
  68242. var shape = this._posToShape(meshPos);
  68243. var shapeUV = this._uvsToShapeUV(meshUV);
  68244. var posfunc = options ? options.positionFunction : null;
  68245. var vtxfunc = options ? options.vertexFunction : null;
  68246. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  68247. // particles
  68248. var sp;
  68249. var currentCopy;
  68250. var idx = this.nbParticles;
  68251. for (var i = 0; i < nb; i++) {
  68252. var currentPos = this._positions.length;
  68253. var currentInd = this._indices.length;
  68254. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  68255. if (this._updatable) {
  68256. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  68257. sp.position.copyFrom(currentCopy.position);
  68258. sp.rotation.copyFrom(currentCopy.rotation);
  68259. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  68260. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  68261. }
  68262. if (currentCopy.color && sp.color) {
  68263. sp.color.copyFrom(currentCopy.color);
  68264. }
  68265. sp.scaling.copyFrom(currentCopy.scaling);
  68266. sp.uvs.copyFrom(currentCopy.uvs);
  68267. }
  68268. this._index += shape.length;
  68269. idx++;
  68270. }
  68271. this.nbParticles += nb;
  68272. this._shapeCounter++;
  68273. return this._shapeCounter - 1;
  68274. };
  68275. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  68276. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  68277. this._resetCopy();
  68278. var copy = this._copy;
  68279. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  68280. particle._model._positionFunction(copy, particle.idx, particle.idxInShape);
  68281. }
  68282. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68283. var tmpVertex = BABYLON.Tmp.Vector3[0];
  68284. var tmpRotated = BABYLON.Tmp.Vector3[1];
  68285. var pivotBackTranslation = BABYLON.Tmp.Vector3[2];
  68286. var scaledPivot = BABYLON.Tmp.Vector3[3];
  68287. copy.getRotationMatrix(rotMatrix);
  68288. particle.pivot.multiplyToRef(particle.scaling, scaledPivot);
  68289. if (copy.translateFromPivot) {
  68290. pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  68291. }
  68292. else {
  68293. pivotBackTranslation.copyFrom(scaledPivot);
  68294. }
  68295. var shape = particle._model._shape;
  68296. for (var pt = 0; pt < shape.length; pt++) {
  68297. tmpVertex.copyFrom(shape[pt]);
  68298. if (particle._model._vertexFunction) {
  68299. particle._model._vertexFunction(copy, tmpVertex, pt); // recall to stored vertexFunction
  68300. }
  68301. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  68302. BABYLON.Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  68303. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position).toArray(this._positions32, particle._pos + pt * 3);
  68304. }
  68305. particle.position.setAll(0.0);
  68306. particle.rotation.setAll(0.0);
  68307. particle.rotationQuaternion = null;
  68308. particle.scaling.setAll(1.0);
  68309. particle.uvs.setAll(0.0);
  68310. particle.pivot.setAll(0.0);
  68311. particle.translateFromPivot = false;
  68312. particle.parentId = null;
  68313. };
  68314. /**
  68315. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  68316. * @returns the SPS.
  68317. */
  68318. SolidParticleSystem.prototype.rebuildMesh = function () {
  68319. for (var p = 0; p < this.particles.length; p++) {
  68320. this._rebuildParticle(this.particles[p]);
  68321. }
  68322. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  68323. return this;
  68324. };
  68325. /**
  68326. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  68327. * This method calls `updateParticle()` for each particle of the SPS.
  68328. * For an animated SPS, it is usually called within the render loop.
  68329. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  68330. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  68331. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  68332. * @returns the SPS.
  68333. */
  68334. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  68335. if (start === void 0) { start = 0; }
  68336. if (end === void 0) { end = this.nbParticles - 1; }
  68337. if (update === void 0) { update = true; }
  68338. if (!this._updatable) {
  68339. return this;
  68340. }
  68341. // custom beforeUpdate
  68342. this.beforeUpdateParticles(start, end, update);
  68343. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68344. var invertedMatrix = BABYLON.Tmp.Matrix[1];
  68345. var mesh = this.mesh;
  68346. var colors32 = this._colors32;
  68347. var positions32 = this._positions32;
  68348. var normals32 = this._normals32;
  68349. var uvs32 = this._uvs32;
  68350. var indices32 = this._indices32;
  68351. var indices = this._indices;
  68352. var fixedNormal32 = this._fixedNormal32;
  68353. var tempVectors = BABYLON.Tmp.Vector3;
  68354. var camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);
  68355. var camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);
  68356. var camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);
  68357. var minimum = tempVectors[8].setAll(Number.MAX_VALUE);
  68358. var maximum = tempVectors[9].setAll(-Number.MAX_VALUE);
  68359. var camInvertedPosition = tempVectors[10].setAll(0);
  68360. // cases when the World Matrix is to be computed first
  68361. if (this.billboard || this._depthSort) {
  68362. this.mesh.computeWorldMatrix(true);
  68363. this.mesh._worldMatrix.invertToRef(invertedMatrix);
  68364. }
  68365. // if the particles will always face the camera
  68366. if (this.billboard) {
  68367. // compute the camera position and un-rotate it by the current mesh rotation
  68368. var tmpVertex = tempVectors[0];
  68369. this._camera.getDirectionToRef(BABYLON.Axis.Z, tmpVertex);
  68370. BABYLON.Vector3.TransformNormalToRef(tmpVertex, invertedMatrix, camAxisZ);
  68371. camAxisZ.normalize();
  68372. // same for camera up vector extracted from the cam view matrix
  68373. var view = this._camera.getViewMatrix(true);
  68374. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], invertedMatrix, camAxisY);
  68375. BABYLON.Vector3.CrossToRef(camAxisY, camAxisZ, camAxisX);
  68376. camAxisY.normalize();
  68377. camAxisX.normalize();
  68378. }
  68379. // if depthSort, compute the camera global position in the mesh local system
  68380. if (this._depthSort) {
  68381. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, invertedMatrix, camInvertedPosition); // then un-rotate the camera
  68382. }
  68383. BABYLON.Matrix.IdentityToRef(rotMatrix);
  68384. var idx = 0; // current position index in the global array positions32
  68385. var index = 0; // position start index in the global array positions32 of the current particle
  68386. var colidx = 0; // current color index in the global array colors32
  68387. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  68388. var uvidx = 0; // current uv index in the global array uvs32
  68389. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  68390. var pt = 0; // current index in the particle model shape
  68391. if (this.mesh.isFacetDataEnabled) {
  68392. this._computeBoundingBox = true;
  68393. }
  68394. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  68395. if (this._computeBoundingBox) {
  68396. if (start != 0 || end != this.nbParticles - 1) { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  68397. var boundingInfo = this.mesh._boundingInfo;
  68398. if (boundingInfo) {
  68399. minimum.copyFrom(boundingInfo.minimum);
  68400. maximum.copyFrom(boundingInfo.maximum);
  68401. }
  68402. }
  68403. }
  68404. // particle loop
  68405. index = this.particles[start]._pos;
  68406. var vpos = (index / 3) | 0;
  68407. colorIndex = vpos * 4;
  68408. uvIndex = vpos * 2;
  68409. for (var p = start; p <= end; p++) {
  68410. var particle = this.particles[p];
  68411. // call to custom user function to update the particle properties
  68412. this.updateParticle(particle);
  68413. var shape = particle._model._shape;
  68414. var shapeUV = particle._model._shapeUV;
  68415. var particleRotationMatrix = particle._rotationMatrix;
  68416. var particlePosition = particle.position;
  68417. var particleRotation = particle.rotation;
  68418. var particleScaling = particle.scaling;
  68419. var particleGlobalPosition = particle._globalPosition;
  68420. // camera-particle distance for depth sorting
  68421. if (this._depthSort && this._depthSortParticles) {
  68422. var dsp = this.depthSortedParticles[p];
  68423. dsp.ind = particle._ind;
  68424. dsp.indicesLength = particle._model._indicesLength;
  68425. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(particle.position, camInvertedPosition);
  68426. }
  68427. // skip the computations for inactive or already invisible particles
  68428. if (!particle.alive || (particle._stillInvisible && !particle.isVisible)) {
  68429. // increment indexes for the next particle
  68430. pt = shape.length;
  68431. index += pt * 3;
  68432. colorIndex += pt * 4;
  68433. uvIndex += pt * 2;
  68434. continue;
  68435. }
  68436. if (particle.isVisible) {
  68437. particle._stillInvisible = false; // un-mark permanent invisibility
  68438. var scaledPivot = tempVectors[12];
  68439. particle.pivot.multiplyToRef(particleScaling, scaledPivot);
  68440. // particle rotation matrix
  68441. if (this.billboard) {
  68442. particleRotation.x = 0.0;
  68443. particleRotation.y = 0.0;
  68444. }
  68445. if (this._computeParticleRotation || this.billboard) {
  68446. particle.getRotationMatrix(rotMatrix);
  68447. }
  68448. var particleHasParent = (particle.parentId !== null);
  68449. if (particleHasParent) {
  68450. var parent_1 = this.particles[particle.parentId];
  68451. var parentRotationMatrix = parent_1._rotationMatrix;
  68452. var parentGlobalPosition = parent_1._globalPosition;
  68453. var rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];
  68454. var rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];
  68455. var rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];
  68456. particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;
  68457. particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;
  68458. particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;
  68459. if (this._computeParticleRotation || this.billboard) {
  68460. var rotMatrixValues = rotMatrix.m;
  68461. particleRotationMatrix[0] = rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];
  68462. particleRotationMatrix[1] = rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];
  68463. particleRotationMatrix[2] = rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];
  68464. particleRotationMatrix[3] = rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];
  68465. particleRotationMatrix[4] = rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];
  68466. particleRotationMatrix[5] = rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];
  68467. particleRotationMatrix[6] = rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];
  68468. particleRotationMatrix[7] = rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];
  68469. particleRotationMatrix[8] = rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];
  68470. }
  68471. }
  68472. else {
  68473. particleGlobalPosition.x = particlePosition.x;
  68474. particleGlobalPosition.y = particlePosition.y;
  68475. particleGlobalPosition.z = particlePosition.z;
  68476. if (this._computeParticleRotation || this.billboard) {
  68477. var rotMatrixValues = rotMatrix.m;
  68478. particleRotationMatrix[0] = rotMatrixValues[0];
  68479. particleRotationMatrix[1] = rotMatrixValues[1];
  68480. particleRotationMatrix[2] = rotMatrixValues[2];
  68481. particleRotationMatrix[3] = rotMatrixValues[4];
  68482. particleRotationMatrix[4] = rotMatrixValues[5];
  68483. particleRotationMatrix[5] = rotMatrixValues[6];
  68484. particleRotationMatrix[6] = rotMatrixValues[8];
  68485. particleRotationMatrix[7] = rotMatrixValues[9];
  68486. particleRotationMatrix[8] = rotMatrixValues[10];
  68487. }
  68488. }
  68489. var pivotBackTranslation = tempVectors[11];
  68490. if (particle.translateFromPivot) {
  68491. pivotBackTranslation.setAll(0.0);
  68492. }
  68493. else {
  68494. pivotBackTranslation.copyFrom(scaledPivot);
  68495. }
  68496. // particle vertex loop
  68497. for (pt = 0; pt < shape.length; pt++) {
  68498. idx = index + pt * 3;
  68499. colidx = colorIndex + pt * 4;
  68500. uvidx = uvIndex + pt * 2;
  68501. var tmpVertex = tempVectors[0];
  68502. tmpVertex.copyFrom(shape[pt]);
  68503. if (this._computeParticleVertex) {
  68504. this.updateParticleVertex(particle, tmpVertex, pt);
  68505. }
  68506. // positions
  68507. var vertexX = tmpVertex.x * particleScaling.x - scaledPivot.x;
  68508. var vertexY = tmpVertex.y * particleScaling.y - scaledPivot.y;
  68509. var vertexZ = tmpVertex.z * particleScaling.z - scaledPivot.z;
  68510. var rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];
  68511. var rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];
  68512. var rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];
  68513. rotatedX += pivotBackTranslation.x;
  68514. rotatedY += pivotBackTranslation.y;
  68515. rotatedZ += pivotBackTranslation.z;
  68516. var px = positions32[idx] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  68517. var py = positions32[idx + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  68518. var pz = positions32[idx + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  68519. if (this._computeBoundingBox) {
  68520. minimum.minimizeInPlaceFromFloats(px, py, pz);
  68521. maximum.maximizeInPlaceFromFloats(px, py, pz);
  68522. }
  68523. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  68524. if (!this._computeParticleVertex) {
  68525. var normalx = fixedNormal32[idx];
  68526. var normaly = fixedNormal32[idx + 1];
  68527. var normalz = fixedNormal32[idx + 2];
  68528. var rotatedx = normalx * particleRotationMatrix[0] + normaly * particleRotationMatrix[3] + normalz * particleRotationMatrix[6];
  68529. var rotatedy = normalx * particleRotationMatrix[1] + normaly * particleRotationMatrix[4] + normalz * particleRotationMatrix[7];
  68530. var rotatedz = normalx * particleRotationMatrix[2] + normaly * particleRotationMatrix[5] + normalz * particleRotationMatrix[8];
  68531. normals32[idx] = camAxisX.x * rotatedx + camAxisY.x * rotatedy + camAxisZ.x * rotatedz;
  68532. normals32[idx + 1] = camAxisX.y * rotatedx + camAxisY.y * rotatedy + camAxisZ.y * rotatedz;
  68533. normals32[idx + 2] = camAxisX.z * rotatedx + camAxisY.z * rotatedy + camAxisZ.z * rotatedz;
  68534. }
  68535. if (this._computeParticleColor && particle.color) {
  68536. var color = particle.color;
  68537. var colors32_1 = this._colors32;
  68538. colors32_1[colidx] = color.r;
  68539. colors32_1[colidx + 1] = color.g;
  68540. colors32_1[colidx + 2] = color.b;
  68541. colors32_1[colidx + 3] = color.a;
  68542. }
  68543. if (this._computeParticleTexture) {
  68544. var uvs = particle.uvs;
  68545. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  68546. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  68547. }
  68548. }
  68549. }
  68550. // particle just set invisible : scaled to zero and positioned at the origin
  68551. else {
  68552. particle._stillInvisible = true; // mark the particle as invisible
  68553. for (pt = 0; pt < shape.length; pt++) {
  68554. idx = index + pt * 3;
  68555. colidx = colorIndex + pt * 4;
  68556. uvidx = uvIndex + pt * 2;
  68557. positions32[idx] = positions32[idx + 1] = positions32[idx + 2] = 0;
  68558. normals32[idx] = normals32[idx + 1] = normals32[idx + 2] = 0;
  68559. if (this._computeParticleColor && particle.color) {
  68560. var color = particle.color;
  68561. colors32[colidx] = color.r;
  68562. colors32[colidx + 1] = color.g;
  68563. colors32[colidx + 2] = color.b;
  68564. colors32[colidx + 3] = color.a;
  68565. }
  68566. if (this._computeParticleTexture) {
  68567. var uvs = particle.uvs;
  68568. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  68569. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  68570. }
  68571. }
  68572. }
  68573. // if the particle intersections must be computed : update the bbInfo
  68574. if (this._particlesIntersect) {
  68575. var bInfo = particle._boundingInfo;
  68576. var bBox = bInfo.boundingBox;
  68577. var bSphere = bInfo.boundingSphere;
  68578. var modelBoundingInfo = particle._modelBoundingInfo;
  68579. if (!this._bSphereOnly) {
  68580. // place, scale and rotate the particle bbox within the SPS local system, then update it
  68581. var modelBoundingInfoVectors = modelBoundingInfo.boundingBox.vectors;
  68582. var tempMin = tempVectors[1];
  68583. var tempMax = tempVectors[2];
  68584. tempMin.setAll(Number.MAX_VALUE);
  68585. tempMax.setAll(-Number.MAX_VALUE);
  68586. for (var b = 0; b < 8; b++) {
  68587. var scaledX = modelBoundingInfoVectors[b].x * particleScaling.x;
  68588. var scaledY = modelBoundingInfoVectors[b].y * particleScaling.y;
  68589. var scaledZ = modelBoundingInfoVectors[b].z * particleScaling.z;
  68590. var rotatedX = scaledX * particleRotationMatrix[0] + scaledY * particleRotationMatrix[3] + scaledZ * particleRotationMatrix[6];
  68591. var rotatedY = scaledX * particleRotationMatrix[1] + scaledY * particleRotationMatrix[4] + scaledZ * particleRotationMatrix[7];
  68592. var rotatedZ = scaledX * particleRotationMatrix[2] + scaledY * particleRotationMatrix[5] + scaledZ * particleRotationMatrix[8];
  68593. var x = particlePosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  68594. var y = particlePosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  68595. var z = particlePosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  68596. tempMin.minimizeInPlaceFromFloats(x, y, z);
  68597. tempMax.maximizeInPlaceFromFloats(x, y, z);
  68598. }
  68599. bBox.reConstruct(tempMin, tempMax, mesh._worldMatrix);
  68600. }
  68601. // place and scale the particle bouding sphere in the SPS local system, then update it
  68602. var minBbox = modelBoundingInfo.minimum.multiplyToRef(particleScaling, tempVectors[1]);
  68603. var maxBbox = modelBoundingInfo.maximum.multiplyToRef(particleScaling, tempVectors[2]);
  68604. var bSphereCenter = maxBbox.addToRef(minBbox, tempVectors[3]).scaleInPlace(0.5);
  68605. var halfDiag = maxBbox.subtractToRef(minBbox, tempVectors[4]).scaleInPlace(0.5 * this._bSphereRadiusFactor);
  68606. var bSphereMinBbox = bSphereCenter.subtractToRef(halfDiag, tempVectors[1]);
  68607. var bSphereMaxBbox = bSphereCenter.addToRef(halfDiag, tempVectors[2]);
  68608. bSphere.reConstruct(bSphereMinBbox, bSphereMaxBbox, mesh._worldMatrix);
  68609. }
  68610. // increment indexes for the next particle
  68611. index = idx + 3;
  68612. colorIndex = colidx + 4;
  68613. uvIndex = uvidx + 2;
  68614. }
  68615. // if the VBO must be updated
  68616. if (update) {
  68617. if (this._computeParticleColor) {
  68618. mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors32, false, false);
  68619. }
  68620. if (this._computeParticleTexture) {
  68621. mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs32, false, false);
  68622. }
  68623. mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions32, false, false);
  68624. if (!mesh.areNormalsFrozen || mesh.isFacetDataEnabled) {
  68625. if (this._computeParticleVertex || mesh.isFacetDataEnabled) {
  68626. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  68627. var params = mesh.isFacetDataEnabled ? mesh.getFacetDataParameters() : null;
  68628. BABYLON.VertexData.ComputeNormals(positions32, indices32, normals32, params);
  68629. for (var i = 0; i < normals32.length; i++) {
  68630. fixedNormal32[i] = normals32[i];
  68631. }
  68632. }
  68633. if (!mesh.areNormalsFrozen) {
  68634. mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals32, false, false);
  68635. }
  68636. }
  68637. if (this._depthSort && this._depthSortParticles) {
  68638. var depthSortedParticles = this.depthSortedParticles;
  68639. depthSortedParticles.sort(depthSortFunction);
  68640. var dspl = depthSortedParticles.length;
  68641. var sid = 0;
  68642. for (var sorted = 0; sorted < dspl; sorted++) {
  68643. var lind = depthSortedParticles[sorted].indicesLength;
  68644. var sind = depthSortedParticles[sorted].ind;
  68645. for (var i = 0; i < lind; i++) {
  68646. indices32[sid] = indices[sind + i];
  68647. sid++;
  68648. }
  68649. }
  68650. mesh.updateIndices(indices32);
  68651. }
  68652. }
  68653. if (this._computeBoundingBox) {
  68654. if (mesh._boundingInfo) {
  68655. mesh._boundingInfo.reConstruct(minimum, maximum, mesh._worldMatrix);
  68656. }
  68657. else {
  68658. mesh._boundingInfo = new BABYLON.BoundingInfo(minimum, maximum, mesh._worldMatrix);
  68659. }
  68660. }
  68661. this.afterUpdateParticles(start, end, update);
  68662. return this;
  68663. };
  68664. /**
  68665. * Disposes the SPS.
  68666. */
  68667. SolidParticleSystem.prototype.dispose = function () {
  68668. this.mesh.dispose();
  68669. this.vars = null;
  68670. // drop references to internal big arrays for the GC
  68671. this._positions = null;
  68672. this._indices = null;
  68673. this._normals = null;
  68674. this._uvs = null;
  68675. this._colors = null;
  68676. this._indices32 = null;
  68677. this._positions32 = null;
  68678. this._normals32 = null;
  68679. this._fixedNormal32 = null;
  68680. this._uvs32 = null;
  68681. this._colors32 = null;
  68682. this.pickedParticles = null;
  68683. };
  68684. /**
  68685. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  68686. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68687. * @returns the SPS.
  68688. */
  68689. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  68690. if (!this._isVisibilityBoxLocked) {
  68691. this.mesh.refreshBoundingInfo();
  68692. }
  68693. return this;
  68694. };
  68695. /**
  68696. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  68697. * @param size the size (float) of the visibility box
  68698. * note : this doesn't lock the SPS mesh bounding box.
  68699. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68700. */
  68701. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  68702. var vis = size / 2;
  68703. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  68704. };
  68705. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  68706. /**
  68707. * Gets whether the SPS as always visible or not
  68708. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68709. */
  68710. get: function () {
  68711. return this._alwaysVisible;
  68712. },
  68713. /**
  68714. * Sets the SPS as always visible or not
  68715. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68716. */
  68717. set: function (val) {
  68718. this._alwaysVisible = val;
  68719. this.mesh.alwaysSelectAsActiveMesh = val;
  68720. },
  68721. enumerable: true,
  68722. configurable: true
  68723. });
  68724. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  68725. /**
  68726. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  68727. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68728. */
  68729. get: function () {
  68730. return this._isVisibilityBoxLocked;
  68731. },
  68732. /**
  68733. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  68734. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68735. */
  68736. set: function (val) {
  68737. this._isVisibilityBoxLocked = val;
  68738. var boundingInfo = this.mesh.getBoundingInfo();
  68739. boundingInfo.isLocked = val;
  68740. },
  68741. enumerable: true,
  68742. configurable: true
  68743. });
  68744. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  68745. /**
  68746. * Gets if `setParticles()` computes the particle rotations or not.
  68747. * Default value : true. The SPS is faster when it's set to false.
  68748. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  68749. */
  68750. get: function () {
  68751. return this._computeParticleRotation;
  68752. },
  68753. /**
  68754. * Tells to `setParticles()` to compute the particle rotations or not.
  68755. * Default value : true. The SPS is faster when it's set to false.
  68756. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  68757. */
  68758. set: function (val) {
  68759. this._computeParticleRotation = val;
  68760. },
  68761. enumerable: true,
  68762. configurable: true
  68763. });
  68764. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  68765. /**
  68766. * Gets if `setParticles()` computes the particle colors or not.
  68767. * Default value : true. The SPS is faster when it's set to false.
  68768. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  68769. */
  68770. get: function () {
  68771. return this._computeParticleColor;
  68772. },
  68773. /**
  68774. * Tells to `setParticles()` to compute the particle colors or not.
  68775. * Default value : true. The SPS is faster when it's set to false.
  68776. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  68777. */
  68778. set: function (val) {
  68779. this._computeParticleColor = val;
  68780. },
  68781. enumerable: true,
  68782. configurable: true
  68783. });
  68784. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  68785. /**
  68786. * Gets if `setParticles()` computes the particle textures or not.
  68787. * Default value : true. The SPS is faster when it's set to false.
  68788. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  68789. */
  68790. get: function () {
  68791. return this._computeParticleTexture;
  68792. },
  68793. set: function (val) {
  68794. this._computeParticleTexture = val;
  68795. },
  68796. enumerable: true,
  68797. configurable: true
  68798. });
  68799. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  68800. /**
  68801. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  68802. * Default value : false. The SPS is faster when it's set to false.
  68803. * Note : the particle custom vertex positions aren't stored values.
  68804. */
  68805. get: function () {
  68806. return this._computeParticleVertex;
  68807. },
  68808. /**
  68809. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  68810. * Default value : false. The SPS is faster when it's set to false.
  68811. * Note : the particle custom vertex positions aren't stored values.
  68812. */
  68813. set: function (val) {
  68814. this._computeParticleVertex = val;
  68815. },
  68816. enumerable: true,
  68817. configurable: true
  68818. });
  68819. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  68820. /**
  68821. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  68822. */
  68823. get: function () {
  68824. return this._computeBoundingBox;
  68825. },
  68826. /**
  68827. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  68828. */
  68829. set: function (val) {
  68830. this._computeBoundingBox = val;
  68831. },
  68832. enumerable: true,
  68833. configurable: true
  68834. });
  68835. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  68836. /**
  68837. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  68838. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  68839. * Default : `true`
  68840. */
  68841. get: function () {
  68842. return this._depthSortParticles;
  68843. },
  68844. /**
  68845. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  68846. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  68847. * Default : `true`
  68848. */
  68849. set: function (val) {
  68850. this._depthSortParticles = val;
  68851. },
  68852. enumerable: true,
  68853. configurable: true
  68854. });
  68855. // =======================================================================
  68856. // Particle behavior logic
  68857. // these following methods may be overwritten by the user to fit his needs
  68858. /**
  68859. * This function does nothing. It may be overwritten to set all the particle first values.
  68860. * The SPS doesn't call this function, you may have to call it by your own.
  68861. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  68862. */
  68863. SolidParticleSystem.prototype.initParticles = function () {
  68864. };
  68865. /**
  68866. * This function does nothing. It may be overwritten to recycle a particle.
  68867. * The SPS doesn't call this function, you may have to call it by your own.
  68868. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  68869. * @param particle The particle to recycle
  68870. * @returns the recycled particle
  68871. */
  68872. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  68873. return particle;
  68874. };
  68875. /**
  68876. * Updates a particle : this function should be overwritten by the user.
  68877. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  68878. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  68879. * @example : just set a particle position or velocity and recycle conditions
  68880. * @param particle The particle to update
  68881. * @returns the updated particle
  68882. */
  68883. SolidParticleSystem.prototype.updateParticle = function (particle) {
  68884. return particle;
  68885. };
  68886. /**
  68887. * Updates a vertex of a particle : it can be overwritten by the user.
  68888. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  68889. * @param particle the current particle
  68890. * @param vertex the current index of the current particle
  68891. * @param pt the index of the current vertex in the particle shape
  68892. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  68893. * @example : just set a vertex particle position
  68894. * @returns the updated vertex
  68895. */
  68896. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  68897. return vertex;
  68898. };
  68899. /**
  68900. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  68901. * This does nothing and may be overwritten by the user.
  68902. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68903. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68904. * @param update the boolean update value actually passed to setParticles()
  68905. */
  68906. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  68907. };
  68908. /**
  68909. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  68910. * This will be passed three parameters.
  68911. * This does nothing and may be overwritten by the user.
  68912. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68913. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68914. * @param update the boolean update value actually passed to setParticles()
  68915. */
  68916. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  68917. };
  68918. return SolidParticleSystem;
  68919. }());
  68920. BABYLON.SolidParticleSystem = SolidParticleSystem;
  68921. })(BABYLON || (BABYLON = {}));
  68922. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  68923. var BABYLON;
  68924. (function (BABYLON) {
  68925. /**
  68926. * Class containing static functions to help procedurally build meshes
  68927. */
  68928. var MeshBuilder = /** @class */ (function () {
  68929. function MeshBuilder() {
  68930. }
  68931. MeshBuilder.updateSideOrientation = function (orientation) {
  68932. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  68933. return BABYLON.Mesh.DOUBLESIDE;
  68934. }
  68935. if (orientation === undefined || orientation === null) {
  68936. return BABYLON.Mesh.FRONTSIDE;
  68937. }
  68938. return orientation;
  68939. };
  68940. /**
  68941. * Creates a box mesh
  68942. * * The parameter `size` sets the size (float) of each box side (default 1)
  68943. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  68944. * * 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)
  68945. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  68946. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68947. * * 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
  68948. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68949. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  68950. * @param name defines the name of the mesh
  68951. * @param options defines the options used to create the mesh
  68952. * @param scene defines the hosting scene
  68953. * @returns the box mesh
  68954. */
  68955. MeshBuilder.CreateBox = function (name, options, scene) {
  68956. if (scene === void 0) { scene = null; }
  68957. var box = new BABYLON.Mesh(name, scene);
  68958. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68959. box._originalBuilderSideOrientation = options.sideOrientation;
  68960. var vertexData = BABYLON.VertexData.CreateBox(options);
  68961. vertexData.applyToMesh(box, options.updatable);
  68962. return box;
  68963. };
  68964. /**
  68965. * Creates a sphere mesh
  68966. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  68967. * * 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`)
  68968. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  68969. * * 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
  68970. * * 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)
  68971. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68972. * * 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
  68973. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68974. * @param name defines the name of the mesh
  68975. * @param options defines the options used to create the mesh
  68976. * @param scene defines the hosting scene
  68977. * @returns the sphere mesh
  68978. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  68979. */
  68980. MeshBuilder.CreateSphere = function (name, options, scene) {
  68981. var sphere = new BABYLON.Mesh(name, scene);
  68982. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68983. sphere._originalBuilderSideOrientation = options.sideOrientation;
  68984. var vertexData = BABYLON.VertexData.CreateSphere(options);
  68985. vertexData.applyToMesh(sphere, options.updatable);
  68986. return sphere;
  68987. };
  68988. /**
  68989. * Creates a plane polygonal mesh. By default, this is a disc
  68990. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  68991. * * 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
  68992. * * 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
  68993. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68994. * * 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
  68995. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68996. * @param name defines the name of the mesh
  68997. * @param options defines the options used to create the mesh
  68998. * @param scene defines the hosting scene
  68999. * @returns the plane polygonal mesh
  69000. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  69001. */
  69002. MeshBuilder.CreateDisc = function (name, options, scene) {
  69003. if (scene === void 0) { scene = null; }
  69004. var disc = new BABYLON.Mesh(name, scene);
  69005. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69006. disc._originalBuilderSideOrientation = options.sideOrientation;
  69007. var vertexData = BABYLON.VertexData.CreateDisc(options);
  69008. vertexData.applyToMesh(disc, options.updatable);
  69009. return disc;
  69010. };
  69011. /**
  69012. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  69013. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  69014. * * 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`)
  69015. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  69016. * * 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
  69017. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69018. * * 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
  69019. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69020. * @param name defines the name of the mesh
  69021. * @param options defines the options used to create the mesh
  69022. * @param scene defines the hosting scene
  69023. * @returns the icosahedron mesh
  69024. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  69025. */
  69026. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  69027. var sphere = new BABYLON.Mesh(name, scene);
  69028. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69029. sphere._originalBuilderSideOrientation = options.sideOrientation;
  69030. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  69031. vertexData.applyToMesh(sphere, options.updatable);
  69032. return sphere;
  69033. };
  69034. /**
  69035. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  69036. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  69037. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  69038. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  69039. * * 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
  69040. * * 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
  69041. * * 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
  69042. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69043. * * 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
  69044. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69045. * * 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
  69046. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  69047. * * 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
  69048. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  69049. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69050. * @param name defines the name of the mesh
  69051. * @param options defines the options used to create the mesh
  69052. * @param scene defines the hosting scene
  69053. * @returns the ribbon mesh
  69054. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  69055. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69056. */
  69057. MeshBuilder.CreateRibbon = function (name, options, scene) {
  69058. if (scene === void 0) { scene = null; }
  69059. var pathArray = options.pathArray;
  69060. var closeArray = options.closeArray;
  69061. var closePath = options.closePath;
  69062. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69063. var instance = options.instance;
  69064. var updatable = options.updatable;
  69065. if (instance) { // existing ribbon instance update
  69066. // positionFunction : ribbon case
  69067. // only pathArray and sideOrientation parameters are taken into account for positions update
  69068. var minimum_1 = BABYLON.Tmp.Vector3[0].setAll(Number.MAX_VALUE);
  69069. var maximum_1 = BABYLON.Tmp.Vector3[1].setAll(-Number.MAX_VALUE);
  69070. var positionFunction = function (positions) {
  69071. var minlg = pathArray[0].length;
  69072. var mesh = instance;
  69073. var i = 0;
  69074. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  69075. for (var si = 1; si <= ns; ++si) {
  69076. for (var p = 0; p < pathArray.length; ++p) {
  69077. var path = pathArray[p];
  69078. var l = path.length;
  69079. minlg = (minlg < l) ? minlg : l;
  69080. for (var j = 0; j < minlg; ++j) {
  69081. var pathPoint = path[j];
  69082. positions[i] = pathPoint.x;
  69083. positions[i + 1] = pathPoint.y;
  69084. positions[i + 2] = pathPoint.z;
  69085. minimum_1.minimizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
  69086. maximum_1.maximizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
  69087. i += 3;
  69088. }
  69089. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  69090. var pathPoint = path[0];
  69091. positions[i] = pathPoint.x;
  69092. positions[i + 1] = pathPoint.y;
  69093. positions[i + 2] = pathPoint.z;
  69094. i += 3;
  69095. }
  69096. }
  69097. }
  69098. };
  69099. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69100. positionFunction(positions);
  69101. if (instance._boundingInfo) {
  69102. instance._boundingInfo.reConstruct(minimum_1, maximum_1, instance._worldMatrix);
  69103. }
  69104. else {
  69105. instance._boundingInfo = new BABYLON.BoundingInfo(minimum_1, maximum_1, instance._worldMatrix);
  69106. }
  69107. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  69108. if (options.colors) {
  69109. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69110. for (var c = 0, colorIndex = 0; c < options.colors.length; c++, colorIndex += 4) {
  69111. var color = options.colors[c];
  69112. colors[colorIndex] = color.r;
  69113. colors[colorIndex + 1] = color.g;
  69114. colors[colorIndex + 2] = color.b;
  69115. colors[colorIndex + 3] = color.a;
  69116. }
  69117. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  69118. }
  69119. if (options.uvs) {
  69120. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69121. for (var i = 0; i < options.uvs.length; i++) {
  69122. uvs[i * 2] = options.uvs[i].x;
  69123. uvs[i * 2 + 1] = options.uvs[i].y;
  69124. }
  69125. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  69126. }
  69127. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  69128. var indices = instance.getIndices();
  69129. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  69130. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  69131. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  69132. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  69133. var indexFirst = 0;
  69134. var indexLast = 0;
  69135. for (var p = 0; p < pathArray.length; p++) {
  69136. indexFirst = instance._creationDataStorage.idx[p] * 3;
  69137. if (p + 1 < pathArray.length) {
  69138. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  69139. }
  69140. else {
  69141. indexLast = normals.length - 3;
  69142. }
  69143. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  69144. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  69145. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  69146. normals[indexLast] = normals[indexFirst];
  69147. normals[indexLast + 1] = normals[indexFirst + 1];
  69148. normals[indexLast + 2] = normals[indexFirst + 2];
  69149. }
  69150. }
  69151. if (!(instance.areNormalsFrozen)) {
  69152. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  69153. }
  69154. }
  69155. return instance;
  69156. }
  69157. else { // new ribbon creation
  69158. var ribbon = new BABYLON.Mesh(name, scene);
  69159. ribbon._originalBuilderSideOrientation = sideOrientation;
  69160. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  69161. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  69162. if (closePath) {
  69163. ribbon._creationDataStorage.idx = vertexData._idx;
  69164. }
  69165. ribbon._creationDataStorage.closePath = closePath;
  69166. ribbon._creationDataStorage.closeArray = closeArray;
  69167. vertexData.applyToMesh(ribbon, updatable);
  69168. return ribbon;
  69169. }
  69170. };
  69171. /**
  69172. * Creates a cylinder or a cone mesh
  69173. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  69174. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  69175. * * 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.
  69176. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  69177. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  69178. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  69179. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  69180. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  69181. * * 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).
  69182. * * 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
  69183. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  69184. * * 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
  69185. * * 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.
  69186. * * If `enclose` is false, a ring surface is one element.
  69187. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  69188. * * 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
  69189. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69190. * * 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
  69191. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69192. * @param name defines the name of the mesh
  69193. * @param options defines the options used to create the mesh
  69194. * @param scene defines the hosting scene
  69195. * @returns the cylinder mesh
  69196. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  69197. */
  69198. MeshBuilder.CreateCylinder = function (name, options, scene) {
  69199. var cylinder = new BABYLON.Mesh(name, scene);
  69200. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69201. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  69202. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  69203. vertexData.applyToMesh(cylinder, options.updatable);
  69204. return cylinder;
  69205. };
  69206. /**
  69207. * Creates a torus mesh
  69208. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  69209. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  69210. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  69211. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69212. * * 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
  69213. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69214. * @param name defines the name of the mesh
  69215. * @param options defines the options used to create the mesh
  69216. * @param scene defines the hosting scene
  69217. * @returns the torus mesh
  69218. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  69219. */
  69220. MeshBuilder.CreateTorus = function (name, options, scene) {
  69221. var torus = new BABYLON.Mesh(name, scene);
  69222. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69223. torus._originalBuilderSideOrientation = options.sideOrientation;
  69224. var vertexData = BABYLON.VertexData.CreateTorus(options);
  69225. vertexData.applyToMesh(torus, options.updatable);
  69226. return torus;
  69227. };
  69228. /**
  69229. * Creates a torus knot mesh
  69230. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  69231. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  69232. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  69233. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  69234. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69235. * * 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
  69236. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69237. * @param name defines the name of the mesh
  69238. * @param options defines the options used to create the mesh
  69239. * @param scene defines the hosting scene
  69240. * @returns the torus knot mesh
  69241. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  69242. */
  69243. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  69244. var torusKnot = new BABYLON.Mesh(name, scene);
  69245. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69246. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  69247. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  69248. vertexData.applyToMesh(torusKnot, options.updatable);
  69249. return torusKnot;
  69250. };
  69251. /**
  69252. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  69253. * * 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
  69254. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  69255. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  69256. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  69257. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  69258. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  69259. * * 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
  69260. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  69261. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69262. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  69263. * @param name defines the name of the new line system
  69264. * @param options defines the options used to create the line system
  69265. * @param scene defines the hosting scene
  69266. * @returns a new line system mesh
  69267. */
  69268. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  69269. var instance = options.instance;
  69270. var lines = options.lines;
  69271. var colors = options.colors;
  69272. if (instance) { // lines update
  69273. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69274. var vertexColor;
  69275. var lineColors;
  69276. if (colors) {
  69277. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69278. }
  69279. var i = 0;
  69280. var c = 0;
  69281. for (var l = 0; l < lines.length; l++) {
  69282. var points = lines[l];
  69283. for (var p = 0; p < points.length; p++) {
  69284. positions[i] = points[p].x;
  69285. positions[i + 1] = points[p].y;
  69286. positions[i + 2] = points[p].z;
  69287. if (colors && vertexColor) {
  69288. lineColors = colors[l];
  69289. vertexColor[c] = lineColors[p].r;
  69290. vertexColor[c + 1] = lineColors[p].g;
  69291. vertexColor[c + 2] = lineColors[p].b;
  69292. vertexColor[c + 3] = lineColors[p].a;
  69293. c += 4;
  69294. }
  69295. i += 3;
  69296. }
  69297. }
  69298. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  69299. if (colors && vertexColor) {
  69300. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  69301. }
  69302. return instance;
  69303. }
  69304. // line system creation
  69305. var useVertexColor = (colors) ? true : false;
  69306. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  69307. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  69308. vertexData.applyToMesh(lineSystem, options.updatable);
  69309. return lineSystem;
  69310. };
  69311. /**
  69312. * Creates a line mesh
  69313. * 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
  69314. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  69315. * * The parameter `points` is an array successive Vector3
  69316. * * 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
  69317. * * The optional parameter `colors` is an array of successive Color4, one per line point
  69318. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  69319. * * When updating an instance, remember that only point positions can change, not the number of points
  69320. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69321. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  69322. * @param name defines the name of the new line system
  69323. * @param options defines the options used to create the line system
  69324. * @param scene defines the hosting scene
  69325. * @returns a new line mesh
  69326. */
  69327. MeshBuilder.CreateLines = function (name, options, scene) {
  69328. if (scene === void 0) { scene = null; }
  69329. var colors = (options.colors) ? [options.colors] : null;
  69330. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  69331. return lines;
  69332. };
  69333. /**
  69334. * Creates a dashed line mesh
  69335. * * 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
  69336. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  69337. * * The parameter `points` is an array successive Vector3
  69338. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  69339. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  69340. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  69341. * * 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
  69342. * * When updating an instance, remember that only point positions can change, not the number of points
  69343. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69344. * @param name defines the name of the mesh
  69345. * @param options defines the options used to create the mesh
  69346. * @param scene defines the hosting scene
  69347. * @returns the dashed line mesh
  69348. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  69349. */
  69350. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  69351. if (scene === void 0) { scene = null; }
  69352. var points = options.points;
  69353. var instance = options.instance;
  69354. var gapSize = options.gapSize || 1;
  69355. var dashSize = options.dashSize || 3;
  69356. if (instance) { // dashed lines update
  69357. var positionFunction = function (positions) {
  69358. var curvect = BABYLON.Vector3.Zero();
  69359. var nbSeg = positions.length / 6;
  69360. var lg = 0;
  69361. var nb = 0;
  69362. var shft = 0;
  69363. var dashshft = 0;
  69364. var curshft = 0;
  69365. var p = 0;
  69366. var i = 0;
  69367. var j = 0;
  69368. for (i = 0; i < points.length - 1; i++) {
  69369. points[i + 1].subtractToRef(points[i], curvect);
  69370. lg += curvect.length();
  69371. }
  69372. shft = lg / nbSeg;
  69373. var dashSize = instance._creationDataStorage.dashSize;
  69374. var gapSize = instance._creationDataStorage.gapSize;
  69375. dashshft = dashSize * shft / (dashSize + gapSize);
  69376. for (i = 0; i < points.length - 1; i++) {
  69377. points[i + 1].subtractToRef(points[i], curvect);
  69378. nb = Math.floor(curvect.length() / shft);
  69379. curvect.normalize();
  69380. j = 0;
  69381. while (j < nb && p < positions.length) {
  69382. curshft = shft * j;
  69383. positions[p] = points[i].x + curshft * curvect.x;
  69384. positions[p + 1] = points[i].y + curshft * curvect.y;
  69385. positions[p + 2] = points[i].z + curshft * curvect.z;
  69386. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  69387. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  69388. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  69389. p += 6;
  69390. j++;
  69391. }
  69392. }
  69393. while (p < positions.length) {
  69394. positions[p] = points[i].x;
  69395. positions[p + 1] = points[i].y;
  69396. positions[p + 2] = points[i].z;
  69397. p += 3;
  69398. }
  69399. };
  69400. instance.updateMeshPositions(positionFunction, false);
  69401. return instance;
  69402. }
  69403. // dashed lines creation
  69404. var dashedLines = new BABYLON.LinesMesh(name, scene);
  69405. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  69406. vertexData.applyToMesh(dashedLines, options.updatable);
  69407. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  69408. dashedLines._creationDataStorage.dashSize = dashSize;
  69409. dashedLines._creationDataStorage.gapSize = gapSize;
  69410. return dashedLines;
  69411. };
  69412. /**
  69413. * 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.
  69414. * * 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.
  69415. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  69416. * * 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.
  69417. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  69418. * * 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
  69419. * * 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
  69420. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  69421. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69422. * * 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
  69423. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  69424. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69425. * @param name defines the name of the mesh
  69426. * @param options defines the options used to create the mesh
  69427. * @param scene defines the hosting scene
  69428. * @returns the extruded shape mesh
  69429. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69430. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69431. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69432. */
  69433. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  69434. if (scene === void 0) { scene = null; }
  69435. var path = options.path;
  69436. var shape = options.shape;
  69437. var scale = options.scale || 1;
  69438. var rotation = options.rotation || 0;
  69439. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  69440. var updatable = options.updatable;
  69441. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69442. var instance = options.instance || null;
  69443. var invertUV = options.invertUV || false;
  69444. 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);
  69445. };
  69446. /**
  69447. * Creates an custom extruded shape mesh.
  69448. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  69449. * * 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.
  69450. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  69451. * * 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
  69452. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  69453. * * 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
  69454. * * It must returns a float value that will be the scale value applied to the shape on each path point
  69455. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  69456. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  69457. * * 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
  69458. * * 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
  69459. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  69460. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69461. * * 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
  69462. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69463. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69464. * @param name defines the name of the mesh
  69465. * @param options defines the options used to create the mesh
  69466. * @param scene defines the hosting scene
  69467. * @returns the custom extruded shape mesh
  69468. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  69469. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69470. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69471. */
  69472. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  69473. var path = options.path;
  69474. var shape = options.shape;
  69475. var scaleFunction = options.scaleFunction || (function () { return 1; });
  69476. var rotationFunction = options.rotationFunction || (function () { return 0; });
  69477. var ribbonCloseArray = options.ribbonCloseArray || false;
  69478. var ribbonClosePath = options.ribbonClosePath || false;
  69479. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  69480. var updatable = options.updatable;
  69481. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69482. var instance = options.instance;
  69483. var invertUV = options.invertUV || false;
  69484. 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);
  69485. };
  69486. /**
  69487. * Creates lathe mesh.
  69488. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  69489. * * 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
  69490. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  69491. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  69492. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  69493. * * 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
  69494. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  69495. * * 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
  69496. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69497. * * 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
  69498. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69499. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69500. * @param name defines the name of the mesh
  69501. * @param options defines the options used to create the mesh
  69502. * @param scene defines the hosting scene
  69503. * @returns the lathe mesh
  69504. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  69505. */
  69506. MeshBuilder.CreateLathe = function (name, options, scene) {
  69507. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  69508. var closed = (options.closed === undefined) ? true : options.closed;
  69509. var shape = options.shape;
  69510. var radius = options.radius || 1;
  69511. var tessellation = options.tessellation || 64;
  69512. var clip = options.clip || 0;
  69513. var updatable = options.updatable;
  69514. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69515. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  69516. var pi2 = Math.PI * 2;
  69517. var paths = new Array();
  69518. var invertUV = options.invertUV || false;
  69519. var i = 0;
  69520. var p = 0;
  69521. var step = pi2 / tessellation * arc;
  69522. var rotated;
  69523. var path = new Array();
  69524. for (i = 0; i <= tessellation - clip; i++) {
  69525. var path = [];
  69526. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  69527. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  69528. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  69529. }
  69530. for (p = 0; p < shape.length; p++) {
  69531. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  69532. path.push(rotated);
  69533. }
  69534. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  69535. 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));
  69536. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  69537. }
  69538. paths.push(path);
  69539. }
  69540. // lathe ribbon
  69541. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  69542. return lathe;
  69543. };
  69544. /**
  69545. * Creates a plane mesh
  69546. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  69547. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  69548. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  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 mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69552. * @param name defines the name of the mesh
  69553. * @param options defines the options used to create the mesh
  69554. * @param scene defines the hosting scene
  69555. * @returns the plane mesh
  69556. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  69557. */
  69558. MeshBuilder.CreatePlane = function (name, options, scene) {
  69559. var plane = new BABYLON.Mesh(name, scene);
  69560. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69561. plane._originalBuilderSideOrientation = options.sideOrientation;
  69562. var vertexData = BABYLON.VertexData.CreatePlane(options);
  69563. vertexData.applyToMesh(plane, options.updatable);
  69564. if (options.sourcePlane) {
  69565. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  69566. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  69567. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  69568. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  69569. plane.rotate(vectorProduct, product);
  69570. }
  69571. }
  69572. return plane;
  69573. };
  69574. /**
  69575. * Creates a ground mesh
  69576. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  69577. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  69578. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69579. * @param name defines the name of the mesh
  69580. * @param options defines the options used to create the mesh
  69581. * @param scene defines the hosting scene
  69582. * @returns the ground mesh
  69583. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  69584. */
  69585. MeshBuilder.CreateGround = function (name, options, scene) {
  69586. var ground = new BABYLON.GroundMesh(name, scene);
  69587. ground._setReady(false);
  69588. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  69589. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  69590. ground._width = options.width || 1;
  69591. ground._height = options.height || 1;
  69592. ground._maxX = ground._width / 2;
  69593. ground._maxZ = ground._height / 2;
  69594. ground._minX = -ground._maxX;
  69595. ground._minZ = -ground._maxZ;
  69596. var vertexData = BABYLON.VertexData.CreateGround(options);
  69597. vertexData.applyToMesh(ground, options.updatable);
  69598. ground._setReady(true);
  69599. return ground;
  69600. };
  69601. /**
  69602. * Creates a tiled ground mesh
  69603. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  69604. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  69605. * * 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
  69606. * * 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
  69607. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69608. * @param name defines the name of the mesh
  69609. * @param options defines the options used to create the mesh
  69610. * @param scene defines the hosting scene
  69611. * @returns the tiled ground mesh
  69612. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  69613. */
  69614. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  69615. var tiledGround = new BABYLON.Mesh(name, scene);
  69616. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  69617. vertexData.applyToMesh(tiledGround, options.updatable);
  69618. return tiledGround;
  69619. };
  69620. /**
  69621. * Creates a ground mesh from a height map
  69622. * * The parameter `url` sets the URL of the height map image resource.
  69623. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  69624. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  69625. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  69626. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  69627. * * 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.
  69628. * * 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).
  69629. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  69630. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69631. * @param name defines the name of the mesh
  69632. * @param url defines the url to the height map
  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/babylon101/height_map
  69637. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  69638. */
  69639. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  69640. var width = options.width || 10.0;
  69641. var height = options.height || 10.0;
  69642. var subdivisions = options.subdivisions || 1 | 0;
  69643. var minHeight = options.minHeight || 0.0;
  69644. var maxHeight = options.maxHeight || 1.0;
  69645. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  69646. var alphaFilter = options.alphaFilter || 0.0;
  69647. var updatable = options.updatable;
  69648. var onReady = options.onReady;
  69649. var ground = new BABYLON.GroundMesh(name, scene);
  69650. ground._subdivisionsX = subdivisions;
  69651. ground._subdivisionsY = subdivisions;
  69652. ground._width = width;
  69653. ground._height = height;
  69654. ground._maxX = ground._width / 2.0;
  69655. ground._maxZ = ground._height / 2.0;
  69656. ground._minX = -ground._maxX;
  69657. ground._minZ = -ground._maxZ;
  69658. ground._setReady(false);
  69659. var onload = function (img) {
  69660. // Getting height map data
  69661. var canvas = document.createElement("canvas");
  69662. var context = canvas.getContext("2d");
  69663. if (!context) {
  69664. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  69665. }
  69666. if (scene.isDisposed) {
  69667. return;
  69668. }
  69669. var bufferWidth = img.width;
  69670. var bufferHeight = img.height;
  69671. canvas.width = bufferWidth;
  69672. canvas.height = bufferHeight;
  69673. context.drawImage(img, 0, 0);
  69674. // Create VertexData from map data
  69675. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  69676. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  69677. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  69678. width: width, height: height,
  69679. subdivisions: subdivisions,
  69680. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  69681. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  69682. alphaFilter: alphaFilter
  69683. });
  69684. vertexData.applyToMesh(ground, updatable);
  69685. //execute ready callback, if set
  69686. if (onReady) {
  69687. onReady(ground);
  69688. }
  69689. ground._setReady(true);
  69690. };
  69691. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.offlineProvider);
  69692. return ground;
  69693. };
  69694. /**
  69695. * Creates a polygon mesh
  69696. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  69697. * * 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
  69698. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69699. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69700. * * 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)
  69701. * * Remember you can only change the shape positions, not their number when updating a polygon
  69702. * @param name defines the name of the mesh
  69703. * @param options defines the options used to create the mesh
  69704. * @param scene defines the hosting scene
  69705. * @returns the polygon mesh
  69706. */
  69707. MeshBuilder.CreatePolygon = function (name, options, scene) {
  69708. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69709. var shape = options.shape;
  69710. var holes = options.holes || [];
  69711. var depth = options.depth || 0;
  69712. var contours = [];
  69713. var hole = [];
  69714. for (var i = 0; i < shape.length; i++) {
  69715. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  69716. }
  69717. var epsilon = 0.00000001;
  69718. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  69719. contours.pop();
  69720. }
  69721. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  69722. for (var hNb = 0; hNb < holes.length; hNb++) {
  69723. hole = [];
  69724. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  69725. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  69726. }
  69727. polygonTriangulation.addHole(hole);
  69728. }
  69729. var polygon = polygonTriangulation.build(options.updatable, depth);
  69730. polygon._originalBuilderSideOrientation = options.sideOrientation;
  69731. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  69732. vertexData.applyToMesh(polygon, options.updatable);
  69733. return polygon;
  69734. };
  69735. /**
  69736. * Creates an extruded polygon mesh, with depth in the Y direction.
  69737. * * 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)
  69738. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  69739. * @param name defines the name of the mesh
  69740. * @param options defines the options used to create the mesh
  69741. * @param scene defines the hosting scene
  69742. * @returns the polygon mesh
  69743. */
  69744. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  69745. return MeshBuilder.CreatePolygon(name, options, scene);
  69746. };
  69747. /**
  69748. * Creates a tube mesh.
  69749. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  69750. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  69751. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  69752. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  69753. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  69754. * * 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)
  69755. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  69756. * * 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
  69757. * * 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
  69758. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69759. * * 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
  69760. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69761. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69762. * @param name defines the name of the mesh
  69763. * @param options defines the options used to create the mesh
  69764. * @param scene defines the hosting scene
  69765. * @returns the tube mesh
  69766. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69767. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  69768. */
  69769. MeshBuilder.CreateTube = function (name, options, scene) {
  69770. var path = options.path;
  69771. var instance = options.instance;
  69772. var radius = 1.0;
  69773. if (options.radius !== undefined) {
  69774. radius = options.radius;
  69775. }
  69776. else if (instance) {
  69777. radius = instance._creationDataStorage.radius;
  69778. }
  69779. var tessellation = options.tessellation || 64 | 0;
  69780. var radiusFunction = options.radiusFunction || null;
  69781. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  69782. var invertUV = options.invertUV || false;
  69783. var updatable = options.updatable;
  69784. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69785. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  69786. // tube geometry
  69787. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  69788. var tangents = path3D.getTangents();
  69789. var normals = path3D.getNormals();
  69790. var distances = path3D.getDistances();
  69791. var pi2 = Math.PI * 2;
  69792. var step = pi2 / tessellation * arc;
  69793. var returnRadius = function () { return radius; };
  69794. var radiusFunctionFinal = radiusFunction || returnRadius;
  69795. var circlePath;
  69796. var rad;
  69797. var normal;
  69798. var rotated;
  69799. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  69800. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  69801. for (var i = 0; i < path.length; i++) {
  69802. rad = radiusFunctionFinal(i, distances[i]); // current radius
  69803. circlePath = Array(); // current circle array
  69804. normal = normals[i]; // current normal
  69805. for (var t = 0; t < tessellation; t++) {
  69806. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  69807. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  69808. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  69809. rotated.scaleInPlace(rad).addInPlace(path[i]);
  69810. circlePath[t] = rotated;
  69811. }
  69812. circlePaths[index] = circlePath;
  69813. index++;
  69814. }
  69815. // cap
  69816. var capPath = function (nbPoints, pathIndex) {
  69817. var pointCap = Array();
  69818. for (var i = 0; i < nbPoints; i++) {
  69819. pointCap.push(path[pathIndex]);
  69820. }
  69821. return pointCap;
  69822. };
  69823. switch (cap) {
  69824. case BABYLON.Mesh.NO_CAP:
  69825. break;
  69826. case BABYLON.Mesh.CAP_START:
  69827. circlePaths[0] = capPath(tessellation, 0);
  69828. circlePaths[1] = circlePaths[2].slice(0);
  69829. break;
  69830. case BABYLON.Mesh.CAP_END:
  69831. circlePaths[index] = circlePaths[index - 1].slice(0);
  69832. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  69833. break;
  69834. case BABYLON.Mesh.CAP_ALL:
  69835. circlePaths[0] = capPath(tessellation, 0);
  69836. circlePaths[1] = circlePaths[2].slice(0);
  69837. circlePaths[index] = circlePaths[index - 1].slice(0);
  69838. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  69839. break;
  69840. default:
  69841. break;
  69842. }
  69843. return circlePaths;
  69844. };
  69845. var path3D;
  69846. var pathArray;
  69847. if (instance) { // tube update
  69848. var storage = instance._creationDataStorage;
  69849. var arc = options.arc || storage.arc;
  69850. path3D = storage.path3D.update(path);
  69851. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  69852. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  69853. // Update mode, no need to recreate the storage.
  69854. storage.path3D = path3D;
  69855. storage.pathArray = pathArray;
  69856. storage.arc = arc;
  69857. storage.radius = radius;
  69858. return instance;
  69859. }
  69860. // tube creation
  69861. path3D = new BABYLON.Path3D(path);
  69862. var newPathArray = new Array();
  69863. cap = (cap < 0 || cap > 3) ? 0 : cap;
  69864. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  69865. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  69866. tube._creationDataStorage.pathArray = pathArray;
  69867. tube._creationDataStorage.path3D = path3D;
  69868. tube._creationDataStorage.tessellation = tessellation;
  69869. tube._creationDataStorage.cap = cap;
  69870. tube._creationDataStorage.arc = options.arc;
  69871. tube._creationDataStorage.radius = radius;
  69872. return tube;
  69873. };
  69874. /**
  69875. * Creates a polyhedron mesh
  69876. * * 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
  69877. * * The parameter `size` (positive float, default 1) sets the polygon size
  69878. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  69879. * * 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`
  69880. * * 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
  69881. * * 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)`)
  69882. * * 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
  69883. * * 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
  69884. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69885. * * 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
  69886. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69887. * @param name defines the name of the mesh
  69888. * @param options defines the options used to create the mesh
  69889. * @param scene defines the hosting scene
  69890. * @returns the polyhedron mesh
  69891. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  69892. */
  69893. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  69894. var polyhedron = new BABYLON.Mesh(name, scene);
  69895. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69896. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  69897. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  69898. vertexData.applyToMesh(polyhedron, options.updatable);
  69899. return polyhedron;
  69900. };
  69901. /**
  69902. * Creates a decal mesh.
  69903. * 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
  69904. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  69905. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  69906. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  69907. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  69908. * @param name defines the name of the mesh
  69909. * @param sourceMesh defines the mesh where the decal must be applied
  69910. * @param options defines the options used to create the mesh
  69911. * @param scene defines the hosting scene
  69912. * @returns the decal mesh
  69913. * @see http://doc.babylonjs.com/how_to/decals
  69914. */
  69915. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  69916. var indices = sourceMesh.getIndices();
  69917. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69918. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  69919. var position = options.position || BABYLON.Vector3.Zero();
  69920. var normal = options.normal || BABYLON.Vector3.Up();
  69921. var size = options.size || BABYLON.Vector3.One();
  69922. var angle = options.angle || 0;
  69923. // Getting correct rotation
  69924. if (!normal) {
  69925. var target = new BABYLON.Vector3(0, 0, 1);
  69926. var camera = sourceMesh.getScene().activeCamera;
  69927. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  69928. normal = camera.globalPosition.subtract(cameraWorldTarget);
  69929. }
  69930. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  69931. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  69932. var pitch = Math.atan2(normal.y, len);
  69933. // Matrix
  69934. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  69935. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  69936. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  69937. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  69938. var vertexData = new BABYLON.VertexData();
  69939. vertexData.indices = [];
  69940. vertexData.positions = [];
  69941. vertexData.normals = [];
  69942. vertexData.uvs = [];
  69943. var currentVertexDataIndex = 0;
  69944. var extractDecalVector3 = function (indexId) {
  69945. var result = new BABYLON.PositionNormalVertex();
  69946. if (!indices || !positions || !normals) {
  69947. return result;
  69948. }
  69949. var vertexId = indices[indexId];
  69950. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  69951. // Send vector to decal local world
  69952. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  69953. // Get normal
  69954. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  69955. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  69956. return result;
  69957. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  69958. var clip = function (vertices, axis) {
  69959. if (vertices.length === 0) {
  69960. return vertices;
  69961. }
  69962. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  69963. var clipVertices = function (v0, v1) {
  69964. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  69965. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  69966. };
  69967. var result = new Array();
  69968. for (var index = 0; index < vertices.length; index += 3) {
  69969. var v1Out;
  69970. var v2Out;
  69971. var v3Out;
  69972. var total = 0;
  69973. var nV1 = null;
  69974. var nV2 = null;
  69975. var nV3 = null;
  69976. var nV4 = null;
  69977. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  69978. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  69979. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  69980. v1Out = d1 > 0;
  69981. v2Out = d2 > 0;
  69982. v3Out = d3 > 0;
  69983. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  69984. switch (total) {
  69985. case 0:
  69986. result.push(vertices[index]);
  69987. result.push(vertices[index + 1]);
  69988. result.push(vertices[index + 2]);
  69989. break;
  69990. case 1:
  69991. if (v1Out) {
  69992. nV1 = vertices[index + 1];
  69993. nV2 = vertices[index + 2];
  69994. nV3 = clipVertices(vertices[index], nV1);
  69995. nV4 = clipVertices(vertices[index], nV2);
  69996. }
  69997. if (v2Out) {
  69998. nV1 = vertices[index];
  69999. nV2 = vertices[index + 2];
  70000. nV3 = clipVertices(vertices[index + 1], nV1);
  70001. nV4 = clipVertices(vertices[index + 1], nV2);
  70002. result.push(nV3);
  70003. result.push(nV2.clone());
  70004. result.push(nV1.clone());
  70005. result.push(nV2.clone());
  70006. result.push(nV3.clone());
  70007. result.push(nV4);
  70008. break;
  70009. }
  70010. if (v3Out) {
  70011. nV1 = vertices[index];
  70012. nV2 = vertices[index + 1];
  70013. nV3 = clipVertices(vertices[index + 2], nV1);
  70014. nV4 = clipVertices(vertices[index + 2], nV2);
  70015. }
  70016. if (nV1 && nV2 && nV3 && nV4) {
  70017. result.push(nV1.clone());
  70018. result.push(nV2.clone());
  70019. result.push(nV3);
  70020. result.push(nV4);
  70021. result.push(nV3.clone());
  70022. result.push(nV2.clone());
  70023. }
  70024. break;
  70025. case 2:
  70026. if (!v1Out) {
  70027. nV1 = vertices[index].clone();
  70028. nV2 = clipVertices(nV1, vertices[index + 1]);
  70029. nV3 = clipVertices(nV1, vertices[index + 2]);
  70030. result.push(nV1);
  70031. result.push(nV2);
  70032. result.push(nV3);
  70033. }
  70034. if (!v2Out) {
  70035. nV1 = vertices[index + 1].clone();
  70036. nV2 = clipVertices(nV1, vertices[index + 2]);
  70037. nV3 = clipVertices(nV1, vertices[index]);
  70038. result.push(nV1);
  70039. result.push(nV2);
  70040. result.push(nV3);
  70041. }
  70042. if (!v3Out) {
  70043. nV1 = vertices[index + 2].clone();
  70044. nV2 = clipVertices(nV1, vertices[index]);
  70045. nV3 = clipVertices(nV1, vertices[index + 1]);
  70046. result.push(nV1);
  70047. result.push(nV2);
  70048. result.push(nV3);
  70049. }
  70050. break;
  70051. case 3:
  70052. break;
  70053. }
  70054. }
  70055. return result;
  70056. };
  70057. for (var index = 0; index < indices.length; index += 3) {
  70058. var faceVertices = new Array();
  70059. faceVertices.push(extractDecalVector3(index));
  70060. faceVertices.push(extractDecalVector3(index + 1));
  70061. faceVertices.push(extractDecalVector3(index + 2));
  70062. // Clip
  70063. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  70064. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  70065. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  70066. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  70067. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  70068. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  70069. if (faceVertices.length === 0) {
  70070. continue;
  70071. }
  70072. // Add UVs and get back to world
  70073. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  70074. var vertex = faceVertices[vIndex];
  70075. //TODO check for Int32Array | Uint32Array | Uint16Array
  70076. vertexData.indices.push(currentVertexDataIndex);
  70077. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  70078. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  70079. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  70080. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  70081. currentVertexDataIndex++;
  70082. }
  70083. }
  70084. // Return mesh
  70085. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  70086. vertexData.applyToMesh(decal);
  70087. decal.position = position.clone();
  70088. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  70089. return decal;
  70090. };
  70091. // Privates
  70092. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  70093. // extrusion geometry
  70094. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  70095. var tangents = path3D.getTangents();
  70096. var normals = path3D.getNormals();
  70097. var binormals = path3D.getBinormals();
  70098. var distances = path3D.getDistances();
  70099. var angle = 0;
  70100. var returnScale = function () { return scale !== null ? scale : 1; };
  70101. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  70102. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  70103. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  70104. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  70105. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  70106. for (var i = 0; i < curve.length; i++) {
  70107. var shapePath = new Array();
  70108. var angleStep = rotate(i, distances[i]);
  70109. var scaleRatio = scl(i, distances[i]);
  70110. for (var p = 0; p < shape.length; p++) {
  70111. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  70112. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  70113. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  70114. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  70115. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  70116. shapePath[p] = rotated;
  70117. }
  70118. shapePaths[index] = shapePath;
  70119. angle += angleStep;
  70120. index++;
  70121. }
  70122. // cap
  70123. var capPath = function (shapePath) {
  70124. var pointCap = Array();
  70125. var barycenter = BABYLON.Vector3.Zero();
  70126. var i;
  70127. for (i = 0; i < shapePath.length; i++) {
  70128. barycenter.addInPlace(shapePath[i]);
  70129. }
  70130. barycenter.scaleInPlace(1.0 / shapePath.length);
  70131. for (i = 0; i < shapePath.length; i++) {
  70132. pointCap.push(barycenter);
  70133. }
  70134. return pointCap;
  70135. };
  70136. switch (cap) {
  70137. case BABYLON.Mesh.NO_CAP:
  70138. break;
  70139. case BABYLON.Mesh.CAP_START:
  70140. shapePaths[0] = capPath(shapePaths[2]);
  70141. shapePaths[1] = shapePaths[2];
  70142. break;
  70143. case BABYLON.Mesh.CAP_END:
  70144. shapePaths[index] = shapePaths[index - 1];
  70145. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  70146. break;
  70147. case BABYLON.Mesh.CAP_ALL:
  70148. shapePaths[0] = capPath(shapePaths[2]);
  70149. shapePaths[1] = shapePaths[2];
  70150. shapePaths[index] = shapePaths[index - 1];
  70151. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  70152. break;
  70153. default:
  70154. break;
  70155. }
  70156. return shapePaths;
  70157. };
  70158. var path3D;
  70159. var pathArray;
  70160. if (instance) { // instance update
  70161. var storage = instance._creationDataStorage;
  70162. path3D = storage.path3D.update(curve);
  70163. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  70164. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  70165. return instance;
  70166. }
  70167. // extruded shape creation
  70168. path3D = new BABYLON.Path3D(curve);
  70169. var newShapePaths = new Array();
  70170. cap = (cap < 0 || cap > 3) ? 0 : cap;
  70171. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  70172. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  70173. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  70174. extrudedGeneric._creationDataStorage.path3D = path3D;
  70175. extrudedGeneric._creationDataStorage.cap = cap;
  70176. return extrudedGeneric;
  70177. };
  70178. return MeshBuilder;
  70179. }());
  70180. BABYLON.MeshBuilder = MeshBuilder;
  70181. })(BABYLON || (BABYLON = {}));
  70182. //# sourceMappingURL=babylon.meshBuilder.js.map
  70183. var BABYLON;
  70184. (function (BABYLON) {
  70185. /**
  70186. * Draco compression (https://google.github.io/draco/)
  70187. *
  70188. * This class wraps the Draco module.
  70189. *
  70190. * **Encoder**
  70191. *
  70192. * The encoder is not currently implemented.
  70193. *
  70194. * **Decoder**
  70195. *
  70196. * 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.
  70197. *
  70198. * To update the configuration, use the following code:
  70199. * ```javascript
  70200. * BABYLON.DracoCompression.Configuration = {
  70201. * decoder: {
  70202. * wasmUrl: "<url to the WebAssembly library>",
  70203. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  70204. * fallbackUrl: "<url to the fallback JavaScript library>",
  70205. * }
  70206. * };
  70207. * ```
  70208. *
  70209. * 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.
  70210. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  70211. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  70212. *
  70213. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  70214. * ```javascript
  70215. * var dracoCompression = new BABYLON.DracoCompression();
  70216. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  70217. * [BABYLON.VertexBuffer.PositionKind]: 0
  70218. * });
  70219. * ```
  70220. *
  70221. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  70222. */
  70223. var DracoCompression = /** @class */ (function () {
  70224. /**
  70225. * Constructor
  70226. */
  70227. function DracoCompression() {
  70228. }
  70229. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  70230. /**
  70231. * Returns true if the decoder is available.
  70232. */
  70233. get: function () {
  70234. if (typeof DracoDecoderModule !== "undefined") {
  70235. return true;
  70236. }
  70237. var decoder = DracoCompression.Configuration.decoder;
  70238. if (decoder) {
  70239. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  70240. return true;
  70241. }
  70242. if (decoder.fallbackUrl) {
  70243. return true;
  70244. }
  70245. }
  70246. return false;
  70247. },
  70248. enumerable: true,
  70249. configurable: true
  70250. });
  70251. /**
  70252. * Stop all async operations and release resources.
  70253. */
  70254. DracoCompression.prototype.dispose = function () {
  70255. };
  70256. /**
  70257. * Decode Draco compressed mesh data to vertex data.
  70258. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  70259. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  70260. * @returns A promise that resolves with the decoded vertex data
  70261. */
  70262. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  70263. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  70264. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  70265. var module = wrappedModule.module;
  70266. var vertexData = new BABYLON.VertexData();
  70267. var buffer = new module.DecoderBuffer();
  70268. buffer.Init(dataView, dataView.byteLength);
  70269. var decoder = new module.Decoder();
  70270. var geometry;
  70271. var status;
  70272. try {
  70273. var type = decoder.GetEncodedGeometryType(buffer);
  70274. switch (type) {
  70275. case module.TRIANGULAR_MESH:
  70276. geometry = new module.Mesh();
  70277. status = decoder.DecodeBufferToMesh(buffer, geometry);
  70278. break;
  70279. case module.POINT_CLOUD:
  70280. geometry = new module.PointCloud();
  70281. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  70282. break;
  70283. default:
  70284. throw new Error("Invalid geometry type " + type);
  70285. }
  70286. if (!status.ok() || !geometry.ptr) {
  70287. throw new Error(status.error_msg());
  70288. }
  70289. var numPoints = geometry.num_points();
  70290. if (type === module.TRIANGULAR_MESH) {
  70291. var numFaces = geometry.num_faces();
  70292. var faceIndices = new module.DracoInt32Array();
  70293. try {
  70294. var indices = new Uint32Array(numFaces * 3);
  70295. for (var i = 0; i < numFaces; i++) {
  70296. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  70297. var offset = i * 3;
  70298. indices[offset + 0] = faceIndices.GetValue(0);
  70299. indices[offset + 1] = faceIndices.GetValue(1);
  70300. indices[offset + 2] = faceIndices.GetValue(2);
  70301. }
  70302. vertexData.indices = indices;
  70303. }
  70304. finally {
  70305. module.destroy(faceIndices);
  70306. }
  70307. }
  70308. for (var kind in attributes) {
  70309. var uniqueId = attributes[kind];
  70310. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  70311. var dracoData = new module.DracoFloat32Array();
  70312. try {
  70313. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  70314. var babylonData = new Float32Array(numPoints * attribute.num_components());
  70315. for (var i = 0; i < babylonData.length; i++) {
  70316. babylonData[i] = dracoData.GetValue(i);
  70317. }
  70318. vertexData.set(babylonData, kind);
  70319. }
  70320. finally {
  70321. module.destroy(dracoData);
  70322. }
  70323. }
  70324. }
  70325. finally {
  70326. if (geometry) {
  70327. module.destroy(geometry);
  70328. }
  70329. module.destroy(decoder);
  70330. module.destroy(buffer);
  70331. }
  70332. return vertexData;
  70333. });
  70334. };
  70335. DracoCompression._GetDecoderModule = function () {
  70336. if (!DracoCompression._DecoderModulePromise) {
  70337. var promise = null;
  70338. var config_1 = {};
  70339. if (typeof DracoDecoderModule !== "undefined") {
  70340. promise = Promise.resolve();
  70341. }
  70342. else {
  70343. var decoder = DracoCompression.Configuration.decoder;
  70344. if (decoder) {
  70345. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  70346. promise = Promise.all([
  70347. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  70348. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  70349. config_1.wasmBinary = data;
  70350. })
  70351. ]);
  70352. }
  70353. else if (decoder.fallbackUrl) {
  70354. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  70355. }
  70356. }
  70357. }
  70358. if (!promise) {
  70359. throw new Error("Draco decoder module is not available");
  70360. }
  70361. DracoCompression._DecoderModulePromise = promise.then(function () {
  70362. return new Promise(function (resolve) {
  70363. config_1.onModuleLoaded = function (decoderModule) {
  70364. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  70365. resolve({ module: decoderModule });
  70366. };
  70367. DracoDecoderModule(config_1);
  70368. });
  70369. });
  70370. }
  70371. return DracoCompression._DecoderModulePromise;
  70372. };
  70373. DracoCompression._LoadScriptAsync = function (url) {
  70374. return new Promise(function (resolve, reject) {
  70375. BABYLON.Tools.LoadScript(url, function () {
  70376. resolve();
  70377. }, function (message) {
  70378. reject(new Error(message));
  70379. });
  70380. });
  70381. };
  70382. DracoCompression._LoadFileAsync = function (url) {
  70383. return new Promise(function (resolve, reject) {
  70384. BABYLON.Tools.LoadFile(url, function (data) {
  70385. resolve(data);
  70386. }, undefined, undefined, true, function (request, exception) {
  70387. reject(exception);
  70388. });
  70389. });
  70390. };
  70391. /**
  70392. * The configuration. Defaults to the following urls:
  70393. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  70394. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  70395. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  70396. */
  70397. DracoCompression.Configuration = {
  70398. decoder: {
  70399. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  70400. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  70401. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  70402. }
  70403. };
  70404. return DracoCompression;
  70405. }());
  70406. BABYLON.DracoCompression = DracoCompression;
  70407. })(BABYLON || (BABYLON = {}));
  70408. //# sourceMappingURL=babylon.dracoCompression.js.map
  70409. var BABYLON;
  70410. (function (BABYLON) {
  70411. // Sets the default audio engine to Babylon.js
  70412. BABYLON.Engine.AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); };
  70413. /**
  70414. * This represents the default audio engine used in babylon.
  70415. * It is responsible to play, synchronize and analyse sounds throughout the application.
  70416. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70417. */
  70418. var AudioEngine = /** @class */ (function () {
  70419. /**
  70420. * Instantiates a new audio engine.
  70421. *
  70422. * There should be only one per page as some browsers restrict the number
  70423. * of audio contexts you can create.
  70424. * @param hostElement defines the host element where to display the mute icon if necessary
  70425. */
  70426. function AudioEngine(hostElement) {
  70427. if (hostElement === void 0) { hostElement = null; }
  70428. var _this = this;
  70429. this._audioContext = null;
  70430. this._audioContextInitialized = false;
  70431. this._muteButton = null;
  70432. /**
  70433. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  70434. */
  70435. this.canUseWebAudio = false;
  70436. /**
  70437. * Defines if Babylon should emit a warning if WebAudio is not supported.
  70438. * @ignoreNaming
  70439. */
  70440. this.WarnedWebAudioUnsupported = false;
  70441. /**
  70442. * Gets whether or not mp3 are supported by your browser.
  70443. */
  70444. this.isMP3supported = false;
  70445. /**
  70446. * Gets whether or not ogg are supported by your browser.
  70447. */
  70448. this.isOGGsupported = false;
  70449. /**
  70450. * Gets whether audio has been unlocked on the device.
  70451. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  70452. * a user interaction has happened.
  70453. */
  70454. this.unlocked = true;
  70455. /**
  70456. * Defines if the audio engine relies on a custom unlocked button.
  70457. * In this case, the embedded button will not be displayed.
  70458. */
  70459. this.useCustomUnlockedButton = false;
  70460. /**
  70461. * Event raised when audio has been unlocked on the browser.
  70462. */
  70463. this.onAudioUnlockedObservable = new BABYLON.Observable();
  70464. /**
  70465. * Event raised when audio has been locked on the browser.
  70466. */
  70467. this.onAudioLockedObservable = new BABYLON.Observable();
  70468. this._tryToRun = false;
  70469. this._onResize = function () {
  70470. _this._moveButtonToTopLeft();
  70471. };
  70472. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  70473. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  70474. this.canUseWebAudio = true;
  70475. }
  70476. var audioElem = document.createElement('audio');
  70477. this._hostElement = hostElement;
  70478. try {
  70479. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  70480. this.isMP3supported = true;
  70481. }
  70482. }
  70483. catch (e) {
  70484. // protect error during capability check.
  70485. }
  70486. try {
  70487. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  70488. this.isOGGsupported = true;
  70489. }
  70490. }
  70491. catch (e) {
  70492. // protect error during capability check.
  70493. }
  70494. }
  70495. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  70496. /**
  70497. * Gets the current AudioContext if available.
  70498. */
  70499. get: function () {
  70500. if (!this._audioContextInitialized) {
  70501. this._initializeAudioContext();
  70502. }
  70503. else {
  70504. if (!this.unlocked && !this._muteButton) {
  70505. this._displayMuteButton();
  70506. }
  70507. }
  70508. return this._audioContext;
  70509. },
  70510. enumerable: true,
  70511. configurable: true
  70512. });
  70513. /**
  70514. * Flags the audio engine in Locked state.
  70515. * This happens due to new browser policies preventing audio to autoplay.
  70516. */
  70517. AudioEngine.prototype.lock = function () {
  70518. this._triggerSuspendedState();
  70519. };
  70520. /**
  70521. * Unlocks the audio engine once a user action has been done on the dom.
  70522. * This is helpful to resume play once browser policies have been satisfied.
  70523. */
  70524. AudioEngine.prototype.unlock = function () {
  70525. this._triggerRunningState();
  70526. };
  70527. AudioEngine.prototype._resumeAudioContext = function () {
  70528. var result;
  70529. if (this._audioContext.resume) {
  70530. result = this._audioContext.resume();
  70531. }
  70532. return result || Promise.resolve();
  70533. };
  70534. AudioEngine.prototype._initializeAudioContext = function () {
  70535. try {
  70536. if (this.canUseWebAudio) {
  70537. this._audioContext = new AudioContext();
  70538. // create a global volume gain node
  70539. this.masterGain = this._audioContext.createGain();
  70540. this.masterGain.gain.value = 1;
  70541. this.masterGain.connect(this._audioContext.destination);
  70542. this._audioContextInitialized = true;
  70543. if (this._audioContext.state === "running") {
  70544. // Do not wait for the promise to unlock.
  70545. this._triggerRunningState();
  70546. }
  70547. }
  70548. }
  70549. catch (e) {
  70550. this.canUseWebAudio = false;
  70551. BABYLON.Tools.Error("Web Audio: " + e.message);
  70552. }
  70553. };
  70554. AudioEngine.prototype._triggerRunningState = function () {
  70555. var _this = this;
  70556. if (this._tryToRun) {
  70557. return;
  70558. }
  70559. this._tryToRun = true;
  70560. this._resumeAudioContext()
  70561. .then(function () {
  70562. _this._tryToRun = false;
  70563. if (_this._muteButton) {
  70564. _this._hideMuteButton();
  70565. }
  70566. }).catch(function () {
  70567. _this._tryToRun = false;
  70568. _this.unlocked = false;
  70569. });
  70570. // Notify users that the audio stack is unlocked/unmuted
  70571. this.unlocked = true;
  70572. this.onAudioUnlockedObservable.notifyObservers(this);
  70573. };
  70574. AudioEngine.prototype._triggerSuspendedState = function () {
  70575. this.unlocked = false;
  70576. this.onAudioLockedObservable.notifyObservers(this);
  70577. this._displayMuteButton();
  70578. };
  70579. AudioEngine.prototype._displayMuteButton = function () {
  70580. var _this = this;
  70581. if (this.useCustomUnlockedButton) {
  70582. return;
  70583. }
  70584. this._muteButton = document.createElement("BUTTON");
  70585. this._muteButton.className = "babylonUnmuteIcon";
  70586. this._muteButton.id = "babylonUnmuteIconBtn";
  70587. this._muteButton.title = "Unmute";
  70588. 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) }";
  70589. var style = document.createElement('style');
  70590. style.appendChild(document.createTextNode(css));
  70591. document.getElementsByTagName('head')[0].appendChild(style);
  70592. document.body.appendChild(this._muteButton);
  70593. this._moveButtonToTopLeft();
  70594. this._muteButton.addEventListener('touchend', function () {
  70595. _this._triggerRunningState();
  70596. }, true);
  70597. this._muteButton.addEventListener('click', function () {
  70598. _this._triggerRunningState();
  70599. }, true);
  70600. window.addEventListener("resize", this._onResize);
  70601. };
  70602. AudioEngine.prototype._moveButtonToTopLeft = function () {
  70603. if (this._hostElement && this._muteButton) {
  70604. this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
  70605. this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
  70606. }
  70607. };
  70608. AudioEngine.prototype._hideMuteButton = function () {
  70609. if (this._muteButton) {
  70610. document.body.removeChild(this._muteButton);
  70611. this._muteButton = null;
  70612. }
  70613. };
  70614. /**
  70615. * Destroy and release the resources associated with the audio ccontext.
  70616. */
  70617. AudioEngine.prototype.dispose = function () {
  70618. if (this.canUseWebAudio && this._audioContextInitialized) {
  70619. if (this._connectedAnalyser && this._audioContext) {
  70620. this._connectedAnalyser.stopDebugCanvas();
  70621. this._connectedAnalyser.dispose();
  70622. this.masterGain.disconnect();
  70623. this.masterGain.connect(this._audioContext.destination);
  70624. this._connectedAnalyser = null;
  70625. }
  70626. this.masterGain.gain.value = 1;
  70627. }
  70628. this.WarnedWebAudioUnsupported = false;
  70629. this._hideMuteButton();
  70630. window.removeEventListener("resize", this._onResize);
  70631. this.onAudioUnlockedObservable.clear();
  70632. this.onAudioLockedObservable.clear();
  70633. };
  70634. /**
  70635. * Gets the global volume sets on the master gain.
  70636. * @returns the global volume if set or -1 otherwise
  70637. */
  70638. AudioEngine.prototype.getGlobalVolume = function () {
  70639. if (this.canUseWebAudio && this._audioContextInitialized) {
  70640. return this.masterGain.gain.value;
  70641. }
  70642. else {
  70643. return -1;
  70644. }
  70645. };
  70646. /**
  70647. * Sets the global volume of your experience (sets on the master gain).
  70648. * @param newVolume Defines the new global volume of the application
  70649. */
  70650. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  70651. if (this.canUseWebAudio && this._audioContextInitialized) {
  70652. this.masterGain.gain.value = newVolume;
  70653. }
  70654. };
  70655. /**
  70656. * Connect the audio engine to an audio analyser allowing some amazing
  70657. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  70658. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  70659. * @param analyser The analyser to connect to the engine
  70660. */
  70661. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  70662. if (this._connectedAnalyser) {
  70663. this._connectedAnalyser.stopDebugCanvas();
  70664. }
  70665. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  70666. this._connectedAnalyser = analyser;
  70667. this.masterGain.disconnect();
  70668. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  70669. }
  70670. };
  70671. return AudioEngine;
  70672. }());
  70673. BABYLON.AudioEngine = AudioEngine;
  70674. })(BABYLON || (BABYLON = {}));
  70675. //# sourceMappingURL=babylon.audioEngine.js.map
  70676. var BABYLON;
  70677. (function (BABYLON) {
  70678. /**
  70679. * Defines a sound that can be played in the application.
  70680. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  70681. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70682. */
  70683. var Sound = /** @class */ (function () {
  70684. /**
  70685. * Create a sound and attach it to a scene
  70686. * @param name Name of your sound
  70687. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  70688. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  70689. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  70690. */
  70691. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  70692. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  70693. var _this = this;
  70694. /**
  70695. * Does the sound autoplay once loaded.
  70696. */
  70697. this.autoplay = false;
  70698. /**
  70699. * Does the sound loop after it finishes playing once.
  70700. */
  70701. this.loop = false;
  70702. /**
  70703. * Does the sound use a custom attenuation curve to simulate the falloff
  70704. * happening when the source gets further away from the camera.
  70705. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  70706. */
  70707. this.useCustomAttenuation = false;
  70708. /**
  70709. * Is this sound currently played.
  70710. */
  70711. this.isPlaying = false;
  70712. /**
  70713. * Is this sound currently paused.
  70714. */
  70715. this.isPaused = false;
  70716. /**
  70717. * Does this sound enables spatial sound.
  70718. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70719. */
  70720. this.spatialSound = false;
  70721. /**
  70722. * Define the reference distance the sound should be heard perfectly.
  70723. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70724. */
  70725. this.refDistance = 1;
  70726. /**
  70727. * Define the roll off factor of spatial sounds.
  70728. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70729. */
  70730. this.rolloffFactor = 1;
  70731. /**
  70732. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  70733. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70734. */
  70735. this.maxDistance = 100;
  70736. /**
  70737. * Define the distance attenuation model the sound will follow.
  70738. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70739. */
  70740. this.distanceModel = "linear";
  70741. /**
  70742. * Observable event when the current playing sound finishes.
  70743. */
  70744. this.onEndedObservable = new BABYLON.Observable();
  70745. this._panningModel = "equalpower";
  70746. this._playbackRate = 1;
  70747. this._streaming = false;
  70748. this._startTime = 0;
  70749. this._startOffset = 0;
  70750. this._position = BABYLON.Vector3.Zero();
  70751. /** @hidden */
  70752. this._positionInEmitterSpace = false;
  70753. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  70754. this._volume = 1;
  70755. this._isReadyToPlay = false;
  70756. this._isDirectional = false;
  70757. // Used if you'd like to create a directional sound.
  70758. // If not set, the sound will be omnidirectional
  70759. this._coneInnerAngle = 360;
  70760. this._coneOuterAngle = 360;
  70761. this._coneOuterGain = 0;
  70762. this._isOutputConnected = false;
  70763. this._urlType = "Unknown";
  70764. this.name = name;
  70765. this._scene = scene;
  70766. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70767. if (!compo) {
  70768. compo = new BABYLON.AudioSceneComponent(scene);
  70769. scene._addComponent(compo);
  70770. }
  70771. this._readyToPlayCallback = readyToPlayCallback;
  70772. // Default custom attenuation function is a linear attenuation
  70773. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  70774. if (currentDistance < maxDistance) {
  70775. return currentVolume * (1 - currentDistance / maxDistance);
  70776. }
  70777. else {
  70778. return 0;
  70779. }
  70780. };
  70781. if (options) {
  70782. this.autoplay = options.autoplay || false;
  70783. this.loop = options.loop || false;
  70784. // if volume === 0, we need another way to check this option
  70785. if (options.volume !== undefined) {
  70786. this._volume = options.volume;
  70787. }
  70788. this.spatialSound = options.spatialSound || false;
  70789. this.maxDistance = options.maxDistance || 100;
  70790. this.useCustomAttenuation = options.useCustomAttenuation || false;
  70791. this.rolloffFactor = options.rolloffFactor || 1;
  70792. this.refDistance = options.refDistance || 1;
  70793. this.distanceModel = options.distanceModel || "linear";
  70794. this._playbackRate = options.playbackRate || 1;
  70795. this._streaming = options.streaming || false;
  70796. }
  70797. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70798. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  70799. this._soundGain.gain.value = this._volume;
  70800. this._inputAudioNode = this._soundGain;
  70801. this._outputAudioNode = this._soundGain;
  70802. if (this.spatialSound) {
  70803. this._createSpatialParameters();
  70804. }
  70805. this._scene.mainSoundTrack.AddSound(this);
  70806. var validParameter = true;
  70807. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  70808. if (urlOrArrayBuffer) {
  70809. try {
  70810. if (typeof (urlOrArrayBuffer) === "string") {
  70811. this._urlType = "String";
  70812. }
  70813. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  70814. this._urlType = "ArrayBuffer";
  70815. }
  70816. else if (urlOrArrayBuffer instanceof MediaStream) {
  70817. this._urlType = "MediaStream";
  70818. }
  70819. else if (Array.isArray(urlOrArrayBuffer)) {
  70820. this._urlType = "Array";
  70821. }
  70822. var urls = [];
  70823. var codecSupportedFound = false;
  70824. switch (this._urlType) {
  70825. case "MediaStream":
  70826. this._streaming = true;
  70827. this._isReadyToPlay = true;
  70828. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  70829. if (this.autoplay) {
  70830. this.play();
  70831. }
  70832. if (this._readyToPlayCallback) {
  70833. this._readyToPlayCallback();
  70834. }
  70835. break;
  70836. case "ArrayBuffer":
  70837. if (urlOrArrayBuffer.byteLength > 0) {
  70838. codecSupportedFound = true;
  70839. this._soundLoaded(urlOrArrayBuffer);
  70840. }
  70841. break;
  70842. case "String":
  70843. urls.push(urlOrArrayBuffer);
  70844. case "Array":
  70845. if (urls.length === 0) {
  70846. urls = urlOrArrayBuffer;
  70847. }
  70848. // If we found a supported format, we load it immediately and stop the loop
  70849. for (var i = 0; i < urls.length; i++) {
  70850. var url = urls[i];
  70851. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  70852. codecSupportedFound = true;
  70853. }
  70854. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  70855. codecSupportedFound = true;
  70856. }
  70857. if (url.indexOf(".wav", url.length - 4) !== -1) {
  70858. codecSupportedFound = true;
  70859. }
  70860. if (url.indexOf("blob:") !== -1) {
  70861. codecSupportedFound = true;
  70862. }
  70863. if (codecSupportedFound) {
  70864. // Loading sound using XHR2
  70865. if (!this._streaming) {
  70866. this._scene._loadFile(url, function (data) {
  70867. _this._soundLoaded(data);
  70868. }, undefined, true, true, function (exception) {
  70869. if (exception) {
  70870. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  70871. }
  70872. BABYLON.Tools.Error("Sound creation aborted.");
  70873. _this._scene.mainSoundTrack.RemoveSound(_this);
  70874. });
  70875. }
  70876. // Streaming sound using HTML5 Audio tag
  70877. else {
  70878. this._htmlAudioElement = new Audio(url);
  70879. this._htmlAudioElement.controls = false;
  70880. this._htmlAudioElement.loop = this.loop;
  70881. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  70882. this._htmlAudioElement.preload = "auto";
  70883. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  70884. _this._isReadyToPlay = true;
  70885. if (_this.autoplay) {
  70886. _this.play();
  70887. }
  70888. if (_this._readyToPlayCallback) {
  70889. _this._readyToPlayCallback();
  70890. }
  70891. });
  70892. document.body.appendChild(this._htmlAudioElement);
  70893. this._htmlAudioElement.load();
  70894. }
  70895. break;
  70896. }
  70897. }
  70898. break;
  70899. default:
  70900. validParameter = false;
  70901. break;
  70902. }
  70903. if (!validParameter) {
  70904. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  70905. }
  70906. else {
  70907. if (!codecSupportedFound) {
  70908. this._isReadyToPlay = true;
  70909. // Simulating a ready to play event to avoid breaking code path
  70910. if (this._readyToPlayCallback) {
  70911. window.setTimeout(function () {
  70912. if (_this._readyToPlayCallback) {
  70913. _this._readyToPlayCallback();
  70914. }
  70915. }, 1000);
  70916. }
  70917. }
  70918. }
  70919. }
  70920. catch (ex) {
  70921. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  70922. this._scene.mainSoundTrack.RemoveSound(this);
  70923. }
  70924. }
  70925. }
  70926. else {
  70927. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  70928. this._scene.mainSoundTrack.AddSound(this);
  70929. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  70930. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  70931. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  70932. }
  70933. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  70934. if (this._readyToPlayCallback) {
  70935. window.setTimeout(function () {
  70936. if (_this._readyToPlayCallback) {
  70937. _this._readyToPlayCallback();
  70938. }
  70939. }, 1000);
  70940. }
  70941. }
  70942. }
  70943. /**
  70944. * Release the sound and its associated resources
  70945. */
  70946. Sound.prototype.dispose = function () {
  70947. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70948. if (this.isPlaying) {
  70949. this.stop();
  70950. }
  70951. this._isReadyToPlay = false;
  70952. if (this.soundTrackId === -1) {
  70953. this._scene.mainSoundTrack.RemoveSound(this);
  70954. }
  70955. else if (this._scene.soundTracks) {
  70956. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  70957. }
  70958. if (this._soundGain) {
  70959. this._soundGain.disconnect();
  70960. this._soundGain = null;
  70961. }
  70962. if (this._soundPanner) {
  70963. this._soundPanner.disconnect();
  70964. this._soundPanner = null;
  70965. }
  70966. if (this._soundSource) {
  70967. this._soundSource.disconnect();
  70968. this._soundSource = null;
  70969. }
  70970. this._audioBuffer = null;
  70971. if (this._htmlAudioElement) {
  70972. this._htmlAudioElement.pause();
  70973. this._htmlAudioElement.src = "";
  70974. document.body.removeChild(this._htmlAudioElement);
  70975. }
  70976. if (this._streamingSource) {
  70977. this._streamingSource.disconnect();
  70978. }
  70979. if (this._connectedMesh && this._registerFunc) {
  70980. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70981. this._connectedMesh = null;
  70982. }
  70983. }
  70984. };
  70985. /**
  70986. * Gets if the sounds is ready to be played or not.
  70987. * @returns true if ready, otherwise false
  70988. */
  70989. Sound.prototype.isReady = function () {
  70990. return this._isReadyToPlay;
  70991. };
  70992. Sound.prototype._soundLoaded = function (audioData) {
  70993. var _this = this;
  70994. if (!BABYLON.Engine.audioEngine.audioContext) {
  70995. return;
  70996. }
  70997. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  70998. _this._audioBuffer = buffer;
  70999. _this._isReadyToPlay = true;
  71000. if (_this.autoplay) {
  71001. _this.play();
  71002. }
  71003. if (_this._readyToPlayCallback) {
  71004. _this._readyToPlayCallback();
  71005. }
  71006. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  71007. };
  71008. /**
  71009. * Sets the data of the sound from an audiobuffer
  71010. * @param audioBuffer The audioBuffer containing the data
  71011. */
  71012. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  71013. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71014. this._audioBuffer = audioBuffer;
  71015. this._isReadyToPlay = true;
  71016. }
  71017. };
  71018. /**
  71019. * Updates the current sounds options such as maxdistance, loop...
  71020. * @param options A JSON object containing values named as the object properties
  71021. */
  71022. Sound.prototype.updateOptions = function (options) {
  71023. if (options) {
  71024. this.loop = options.loop || this.loop;
  71025. this.maxDistance = options.maxDistance || this.maxDistance;
  71026. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  71027. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  71028. this.refDistance = options.refDistance || this.refDistance;
  71029. this.distanceModel = options.distanceModel || this.distanceModel;
  71030. this._playbackRate = options.playbackRate || this._playbackRate;
  71031. this._updateSpatialParameters();
  71032. if (this.isPlaying) {
  71033. if (this._streaming && this._htmlAudioElement) {
  71034. this._htmlAudioElement.playbackRate = this._playbackRate;
  71035. }
  71036. else {
  71037. if (this._soundSource) {
  71038. this._soundSource.playbackRate.value = this._playbackRate;
  71039. }
  71040. }
  71041. }
  71042. }
  71043. };
  71044. Sound.prototype._createSpatialParameters = function () {
  71045. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  71046. if (this._scene.headphone) {
  71047. this._panningModel = "HRTF";
  71048. }
  71049. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  71050. this._updateSpatialParameters();
  71051. this._soundPanner.connect(this._outputAudioNode);
  71052. this._inputAudioNode = this._soundPanner;
  71053. }
  71054. };
  71055. Sound.prototype._updateSpatialParameters = function () {
  71056. if (this.spatialSound && this._soundPanner) {
  71057. if (this.useCustomAttenuation) {
  71058. // Tricks to disable in a way embedded Web Audio attenuation
  71059. this._soundPanner.distanceModel = "linear";
  71060. this._soundPanner.maxDistance = Number.MAX_VALUE;
  71061. this._soundPanner.refDistance = 1;
  71062. this._soundPanner.rolloffFactor = 1;
  71063. this._soundPanner.panningModel = this._panningModel;
  71064. }
  71065. else {
  71066. this._soundPanner.distanceModel = this.distanceModel;
  71067. this._soundPanner.maxDistance = this.maxDistance;
  71068. this._soundPanner.refDistance = this.refDistance;
  71069. this._soundPanner.rolloffFactor = this.rolloffFactor;
  71070. this._soundPanner.panningModel = this._panningModel;
  71071. }
  71072. }
  71073. };
  71074. /**
  71075. * Switch the panning model to HRTF:
  71076. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  71077. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71078. */
  71079. Sound.prototype.switchPanningModelToHRTF = function () {
  71080. this._panningModel = "HRTF";
  71081. this._switchPanningModel();
  71082. };
  71083. /**
  71084. * Switch the panning model to Equal Power:
  71085. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  71086. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71087. */
  71088. Sound.prototype.switchPanningModelToEqualPower = function () {
  71089. this._panningModel = "equalpower";
  71090. this._switchPanningModel();
  71091. };
  71092. Sound.prototype._switchPanningModel = function () {
  71093. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71094. this._soundPanner.panningModel = this._panningModel;
  71095. }
  71096. };
  71097. /**
  71098. * Connect this sound to a sound track audio node like gain...
  71099. * @param soundTrackAudioNode the sound track audio node to connect to
  71100. */
  71101. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  71102. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71103. if (this._isOutputConnected) {
  71104. this._outputAudioNode.disconnect();
  71105. }
  71106. this._outputAudioNode.connect(soundTrackAudioNode);
  71107. this._isOutputConnected = true;
  71108. }
  71109. };
  71110. /**
  71111. * Transform this sound into a directional source
  71112. * @param coneInnerAngle Size of the inner cone in degree
  71113. * @param coneOuterAngle Size of the outer cone in degree
  71114. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  71115. */
  71116. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  71117. if (coneOuterAngle < coneInnerAngle) {
  71118. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  71119. return;
  71120. }
  71121. this._coneInnerAngle = coneInnerAngle;
  71122. this._coneOuterAngle = coneOuterAngle;
  71123. this._coneOuterGain = coneOuterGain;
  71124. this._isDirectional = true;
  71125. if (this.isPlaying && this.loop) {
  71126. this.stop();
  71127. this.play();
  71128. }
  71129. };
  71130. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  71131. /**
  71132. * Gets or sets the inner angle for the directional cone.
  71133. */
  71134. get: function () {
  71135. return this._coneInnerAngle;
  71136. },
  71137. /**
  71138. * Gets or sets the inner angle for the directional cone.
  71139. */
  71140. set: function (value) {
  71141. if (value != this._coneInnerAngle) {
  71142. if (this._coneOuterAngle < value) {
  71143. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  71144. return;
  71145. }
  71146. this._coneInnerAngle = value;
  71147. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71148. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  71149. }
  71150. }
  71151. },
  71152. enumerable: true,
  71153. configurable: true
  71154. });
  71155. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  71156. /**
  71157. * Gets or sets the outer angle for the directional cone.
  71158. */
  71159. get: function () {
  71160. return this._coneOuterAngle;
  71161. },
  71162. /**
  71163. * Gets or sets the outer angle for the directional cone.
  71164. */
  71165. set: function (value) {
  71166. if (value != this._coneOuterAngle) {
  71167. if (value < this._coneInnerAngle) {
  71168. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  71169. return;
  71170. }
  71171. this._coneOuterAngle = value;
  71172. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71173. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  71174. }
  71175. }
  71176. },
  71177. enumerable: true,
  71178. configurable: true
  71179. });
  71180. /**
  71181. * Sets the position of the emitter if spatial sound is enabled
  71182. * @param newPosition Defines the new posisiton
  71183. */
  71184. Sound.prototype.setPosition = function (newPosition) {
  71185. this._position = newPosition;
  71186. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  71187. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  71188. }
  71189. };
  71190. /**
  71191. * Sets the local direction of the emitter if spatial sound is enabled
  71192. * @param newLocalDirection Defines the new local direction
  71193. */
  71194. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  71195. this._localDirection = newLocalDirection;
  71196. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  71197. this._updateDirection();
  71198. }
  71199. };
  71200. Sound.prototype._updateDirection = function () {
  71201. if (!this._connectedMesh || !this._soundPanner) {
  71202. return;
  71203. }
  71204. var mat = this._connectedMesh.getWorldMatrix();
  71205. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  71206. direction.normalize();
  71207. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  71208. };
  71209. /** @hidden */
  71210. Sound.prototype.updateDistanceFromListener = function () {
  71211. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  71212. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  71213. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  71214. }
  71215. };
  71216. /**
  71217. * Sets a new custom attenuation function for the sound.
  71218. * @param callback Defines the function used for the attenuation
  71219. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  71220. */
  71221. Sound.prototype.setAttenuationFunction = function (callback) {
  71222. this._customAttenuationFunction = callback;
  71223. };
  71224. /**
  71225. * Play the sound
  71226. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  71227. * @param offset (optional) Start the sound setting it at a specific time
  71228. */
  71229. Sound.prototype.play = function (time, offset) {
  71230. var _this = this;
  71231. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  71232. try {
  71233. if (this._startOffset < 0) {
  71234. time = -this._startOffset;
  71235. this._startOffset = 0;
  71236. }
  71237. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  71238. if (!this._soundSource || !this._streamingSource) {
  71239. if (this.spatialSound && this._soundPanner) {
  71240. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  71241. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  71242. }
  71243. if (this._isDirectional) {
  71244. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  71245. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  71246. this._soundPanner.coneOuterGain = this._coneOuterGain;
  71247. if (this._connectedMesh) {
  71248. this._updateDirection();
  71249. }
  71250. else {
  71251. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  71252. }
  71253. }
  71254. }
  71255. }
  71256. if (this._streaming) {
  71257. if (!this._streamingSource) {
  71258. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  71259. this._htmlAudioElement.onended = function () { _this._onended(); };
  71260. this._htmlAudioElement.playbackRate = this._playbackRate;
  71261. }
  71262. this._streamingSource.disconnect();
  71263. this._streamingSource.connect(this._inputAudioNode);
  71264. if (this._htmlAudioElement) {
  71265. // required to manage properly the new suspended default state of Chrome
  71266. // When the option 'streaming: true' is used, we need first to wait for
  71267. // the audio engine to be unlocked by a user gesture before trying to play
  71268. // an HTML Audio elememt
  71269. var tryToPlay = function () {
  71270. if (BABYLON.Engine.audioEngine.unlocked) {
  71271. var playPromise = _this._htmlAudioElement.play();
  71272. // In browsers that don’t yet support this functionality,
  71273. // playPromise won’t be defined.
  71274. if (playPromise !== undefined) {
  71275. playPromise.catch(function (error) {
  71276. // Automatic playback failed.
  71277. // Waiting for the audio engine to be unlocked by user click on unmute
  71278. BABYLON.Engine.audioEngine.lock();
  71279. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  71280. });
  71281. }
  71282. }
  71283. else {
  71284. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  71285. }
  71286. };
  71287. tryToPlay();
  71288. }
  71289. }
  71290. else {
  71291. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  71292. this._soundSource.buffer = this._audioBuffer;
  71293. this._soundSource.connect(this._inputAudioNode);
  71294. this._soundSource.loop = this.loop;
  71295. this._soundSource.playbackRate.value = this._playbackRate;
  71296. this._soundSource.onended = function () { _this._onended(); };
  71297. if (this._soundSource.buffer) {
  71298. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  71299. }
  71300. }
  71301. this._startTime = startTime;
  71302. this.isPlaying = true;
  71303. this.isPaused = false;
  71304. }
  71305. catch (ex) {
  71306. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  71307. }
  71308. }
  71309. };
  71310. Sound.prototype._onended = function () {
  71311. this.isPlaying = false;
  71312. if (this.onended) {
  71313. this.onended();
  71314. }
  71315. this.onEndedObservable.notifyObservers(this);
  71316. };
  71317. /**
  71318. * Stop the sound
  71319. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  71320. */
  71321. Sound.prototype.stop = function (time) {
  71322. if (this.isPlaying) {
  71323. if (this._streaming) {
  71324. if (this._htmlAudioElement) {
  71325. this._htmlAudioElement.pause();
  71326. // Test needed for Firefox or it will generate an Invalid State Error
  71327. if (this._htmlAudioElement.currentTime > 0) {
  71328. this._htmlAudioElement.currentTime = 0;
  71329. }
  71330. }
  71331. else {
  71332. this._streamingSource.disconnect();
  71333. }
  71334. }
  71335. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  71336. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  71337. this._soundSource.stop(stopTime);
  71338. this._soundSource.onended = function () { };
  71339. if (!this.isPaused) {
  71340. this._startOffset = 0;
  71341. }
  71342. }
  71343. this.isPlaying = false;
  71344. }
  71345. };
  71346. /**
  71347. * Put the sound in pause
  71348. */
  71349. Sound.prototype.pause = function () {
  71350. if (this.isPlaying) {
  71351. this.isPaused = true;
  71352. if (this._streaming) {
  71353. if (this._htmlAudioElement) {
  71354. this._htmlAudioElement.pause();
  71355. }
  71356. else {
  71357. this._streamingSource.disconnect();
  71358. }
  71359. }
  71360. else if (BABYLON.Engine.audioEngine.audioContext) {
  71361. this.stop(0);
  71362. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  71363. }
  71364. }
  71365. };
  71366. /**
  71367. * Sets a dedicated volume for this sounds
  71368. * @param newVolume Define the new volume of the sound
  71369. * @param time Define in how long the sound should be at this value
  71370. */
  71371. Sound.prototype.setVolume = function (newVolume, time) {
  71372. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  71373. if (time && BABYLON.Engine.audioEngine.audioContext) {
  71374. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  71375. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  71376. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  71377. }
  71378. else {
  71379. this._soundGain.gain.value = newVolume;
  71380. }
  71381. }
  71382. this._volume = newVolume;
  71383. };
  71384. /**
  71385. * Set the sound play back rate
  71386. * @param newPlaybackRate Define the playback rate the sound should be played at
  71387. */
  71388. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  71389. this._playbackRate = newPlaybackRate;
  71390. if (this.isPlaying) {
  71391. if (this._streaming && this._htmlAudioElement) {
  71392. this._htmlAudioElement.playbackRate = this._playbackRate;
  71393. }
  71394. else if (this._soundSource) {
  71395. this._soundSource.playbackRate.value = this._playbackRate;
  71396. }
  71397. }
  71398. };
  71399. /**
  71400. * Gets the volume of the sound.
  71401. * @returns the volume of the sound
  71402. */
  71403. Sound.prototype.getVolume = function () {
  71404. return this._volume;
  71405. };
  71406. /**
  71407. * Attach the sound to a dedicated mesh
  71408. * @param meshToConnectTo The mesh to connect the sound with
  71409. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  71410. */
  71411. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  71412. var _this = this;
  71413. if (this._connectedMesh && this._registerFunc) {
  71414. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71415. this._registerFunc = null;
  71416. }
  71417. this._connectedMesh = meshToConnectTo;
  71418. if (!this.spatialSound) {
  71419. this.spatialSound = true;
  71420. this._createSpatialParameters();
  71421. if (this.isPlaying && this.loop) {
  71422. this.stop();
  71423. this.play();
  71424. }
  71425. }
  71426. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  71427. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  71428. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  71429. };
  71430. /**
  71431. * Detach the sound from the previously attached mesh
  71432. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  71433. */
  71434. Sound.prototype.detachFromMesh = function () {
  71435. if (this._connectedMesh && this._registerFunc) {
  71436. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71437. this._registerFunc = null;
  71438. this._connectedMesh = null;
  71439. }
  71440. };
  71441. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  71442. if (!node.getBoundingInfo) {
  71443. return;
  71444. }
  71445. var mesh = node;
  71446. if (this._positionInEmitterSpace) {
  71447. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  71448. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  71449. }
  71450. else {
  71451. var boundingInfo = mesh.getBoundingInfo();
  71452. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  71453. }
  71454. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  71455. this._updateDirection();
  71456. }
  71457. };
  71458. /**
  71459. * Clone the current sound in the scene.
  71460. * @returns the new sound clone
  71461. */
  71462. Sound.prototype.clone = function () {
  71463. var _this = this;
  71464. if (!this._streaming) {
  71465. var setBufferAndRun = function () {
  71466. if (_this._isReadyToPlay) {
  71467. clonedSound._audioBuffer = _this.getAudioBuffer();
  71468. clonedSound._isReadyToPlay = true;
  71469. if (clonedSound.autoplay) {
  71470. clonedSound.play();
  71471. }
  71472. }
  71473. else {
  71474. window.setTimeout(setBufferAndRun, 300);
  71475. }
  71476. };
  71477. var currentOptions = {
  71478. autoplay: this.autoplay, loop: this.loop,
  71479. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  71480. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  71481. refDistance: this.refDistance, distanceModel: this.distanceModel
  71482. };
  71483. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  71484. if (this.useCustomAttenuation) {
  71485. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  71486. }
  71487. clonedSound.setPosition(this._position);
  71488. clonedSound.setPlaybackRate(this._playbackRate);
  71489. setBufferAndRun();
  71490. return clonedSound;
  71491. }
  71492. // Can't clone a streaming sound
  71493. else {
  71494. return null;
  71495. }
  71496. };
  71497. /**
  71498. * Gets the current underlying audio buffer containing the data
  71499. * @returns the audio buffer
  71500. */
  71501. Sound.prototype.getAudioBuffer = function () {
  71502. return this._audioBuffer;
  71503. };
  71504. /**
  71505. * Serializes the Sound in a JSON representation
  71506. * @returns the JSON representation of the sound
  71507. */
  71508. Sound.prototype.serialize = function () {
  71509. var serializationObject = {
  71510. name: this.name,
  71511. url: this.name,
  71512. autoplay: this.autoplay,
  71513. loop: this.loop,
  71514. volume: this._volume,
  71515. spatialSound: this.spatialSound,
  71516. maxDistance: this.maxDistance,
  71517. rolloffFactor: this.rolloffFactor,
  71518. refDistance: this.refDistance,
  71519. distanceModel: this.distanceModel,
  71520. playbackRate: this._playbackRate,
  71521. panningModel: this._panningModel,
  71522. soundTrackId: this.soundTrackId
  71523. };
  71524. if (this.spatialSound) {
  71525. if (this._connectedMesh) {
  71526. serializationObject.connectedMeshId = this._connectedMesh.id;
  71527. }
  71528. serializationObject.position = this._position.asArray();
  71529. serializationObject.refDistance = this.refDistance;
  71530. serializationObject.distanceModel = this.distanceModel;
  71531. serializationObject.isDirectional = this._isDirectional;
  71532. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  71533. serializationObject.coneInnerAngle = this._coneInnerAngle;
  71534. serializationObject.coneOuterAngle = this._coneOuterAngle;
  71535. serializationObject.coneOuterGain = this._coneOuterGain;
  71536. }
  71537. return serializationObject;
  71538. };
  71539. /**
  71540. * Parse a JSON representation of a sound to innstantiate in a given scene
  71541. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  71542. * @param scene Define the scene the new parsed sound should be created in
  71543. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  71544. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  71545. * @returns the newly parsed sound
  71546. */
  71547. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  71548. var soundName = parsedSound.name;
  71549. var soundUrl;
  71550. if (parsedSound.url) {
  71551. soundUrl = rootUrl + parsedSound.url;
  71552. }
  71553. else {
  71554. soundUrl = rootUrl + soundName;
  71555. }
  71556. var options = {
  71557. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  71558. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  71559. rolloffFactor: parsedSound.rolloffFactor,
  71560. refDistance: parsedSound.refDistance,
  71561. distanceModel: parsedSound.distanceModel,
  71562. playbackRate: parsedSound.playbackRate
  71563. };
  71564. var newSound;
  71565. if (!sourceSound) {
  71566. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  71567. scene._addPendingData(newSound);
  71568. }
  71569. else {
  71570. var setBufferAndRun = function () {
  71571. if (sourceSound._isReadyToPlay) {
  71572. newSound._audioBuffer = sourceSound.getAudioBuffer();
  71573. newSound._isReadyToPlay = true;
  71574. if (newSound.autoplay) {
  71575. newSound.play();
  71576. }
  71577. }
  71578. else {
  71579. window.setTimeout(setBufferAndRun, 300);
  71580. }
  71581. };
  71582. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  71583. setBufferAndRun();
  71584. }
  71585. if (parsedSound.position) {
  71586. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  71587. newSound.setPosition(soundPosition);
  71588. }
  71589. if (parsedSound.isDirectional) {
  71590. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  71591. if (parsedSound.localDirectionToMesh) {
  71592. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  71593. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  71594. }
  71595. }
  71596. if (parsedSound.connectedMeshId) {
  71597. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  71598. if (connectedMesh) {
  71599. newSound.attachToMesh(connectedMesh);
  71600. }
  71601. }
  71602. return newSound;
  71603. };
  71604. return Sound;
  71605. }());
  71606. BABYLON.Sound = Sound;
  71607. })(BABYLON || (BABYLON = {}));
  71608. //# sourceMappingURL=babylon.sound.js.map
  71609. var BABYLON;
  71610. (function (BABYLON) {
  71611. /**
  71612. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  71613. * It will be also used in a future release to apply effects on a specific track.
  71614. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  71615. */
  71616. var SoundTrack = /** @class */ (function () {
  71617. /**
  71618. * Creates a new sound track.
  71619. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  71620. * @param scene Define the scene the sound track belongs to
  71621. * @param options
  71622. */
  71623. function SoundTrack(scene, options) {
  71624. if (options === void 0) { options = {}; }
  71625. /**
  71626. * The unique identifier of the sound track in the scene.
  71627. */
  71628. this.id = -1;
  71629. this._isMainTrack = false;
  71630. this._isInitialized = false;
  71631. this._scene = scene;
  71632. this.soundCollection = new Array();
  71633. this._options = options;
  71634. if (!this._isMainTrack && this._scene.soundTracks) {
  71635. this._scene.soundTracks.push(this);
  71636. this.id = this._scene.soundTracks.length - 1;
  71637. }
  71638. }
  71639. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  71640. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  71641. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  71642. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  71643. if (this._options) {
  71644. if (this._options.volume) {
  71645. this._outputAudioNode.gain.value = this._options.volume;
  71646. }
  71647. if (this._options.mainTrack) {
  71648. this._isMainTrack = this._options.mainTrack;
  71649. }
  71650. }
  71651. this._isInitialized = true;
  71652. }
  71653. };
  71654. /**
  71655. * Release the sound track and its associated resources
  71656. */
  71657. SoundTrack.prototype.dispose = function () {
  71658. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  71659. if (this._connectedAnalyser) {
  71660. this._connectedAnalyser.stopDebugCanvas();
  71661. }
  71662. while (this.soundCollection.length) {
  71663. this.soundCollection[0].dispose();
  71664. }
  71665. if (this._outputAudioNode) {
  71666. this._outputAudioNode.disconnect();
  71667. }
  71668. this._outputAudioNode = null;
  71669. }
  71670. };
  71671. /**
  71672. * Adds a sound to this sound track
  71673. * @param sound define the cound to add
  71674. * @ignoreNaming
  71675. */
  71676. SoundTrack.prototype.AddSound = function (sound) {
  71677. if (!this._isInitialized) {
  71678. this._initializeSoundTrackAudioGraph();
  71679. }
  71680. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71681. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  71682. }
  71683. if (sound.soundTrackId) {
  71684. if (sound.soundTrackId === -1) {
  71685. this._scene.mainSoundTrack.RemoveSound(sound);
  71686. }
  71687. else if (this._scene.soundTracks) {
  71688. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  71689. }
  71690. }
  71691. this.soundCollection.push(sound);
  71692. sound.soundTrackId = this.id;
  71693. };
  71694. /**
  71695. * Removes a sound to this sound track
  71696. * @param sound define the cound to remove
  71697. * @ignoreNaming
  71698. */
  71699. SoundTrack.prototype.RemoveSound = function (sound) {
  71700. var index = this.soundCollection.indexOf(sound);
  71701. if (index !== -1) {
  71702. this.soundCollection.splice(index, 1);
  71703. }
  71704. };
  71705. /**
  71706. * Set a global volume for the full sound track.
  71707. * @param newVolume Define the new volume of the sound track
  71708. */
  71709. SoundTrack.prototype.setVolume = function (newVolume) {
  71710. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71711. this._outputAudioNode.gain.value = newVolume;
  71712. }
  71713. };
  71714. /**
  71715. * Switch the panning model to HRTF:
  71716. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  71717. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71718. */
  71719. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  71720. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71721. for (var i = 0; i < this.soundCollection.length; i++) {
  71722. this.soundCollection[i].switchPanningModelToHRTF();
  71723. }
  71724. }
  71725. };
  71726. /**
  71727. * Switch the panning model to Equal Power:
  71728. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  71729. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71730. */
  71731. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  71732. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71733. for (var i = 0; i < this.soundCollection.length; i++) {
  71734. this.soundCollection[i].switchPanningModelToEqualPower();
  71735. }
  71736. }
  71737. };
  71738. /**
  71739. * Connect the sound track to an audio analyser allowing some amazing
  71740. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  71741. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  71742. * @param analyser The analyser to connect to the engine
  71743. */
  71744. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  71745. if (this._connectedAnalyser) {
  71746. this._connectedAnalyser.stopDebugCanvas();
  71747. }
  71748. this._connectedAnalyser = analyser;
  71749. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71750. this._outputAudioNode.disconnect();
  71751. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  71752. }
  71753. };
  71754. return SoundTrack;
  71755. }());
  71756. BABYLON.SoundTrack = SoundTrack;
  71757. })(BABYLON || (BABYLON = {}));
  71758. //# sourceMappingURL=babylon.soundtrack.js.map
  71759. var BABYLON;
  71760. (function (BABYLON) {
  71761. /**
  71762. * Class used to work with sound analyzer using fast fourier transform (FFT)
  71763. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  71764. */
  71765. var Analyser = /** @class */ (function () {
  71766. /**
  71767. * Creates a new analyser
  71768. * @param scene defines hosting scene
  71769. */
  71770. function Analyser(scene) {
  71771. /**
  71772. * Gets or sets the smoothing
  71773. * @ignorenaming
  71774. */
  71775. this.SMOOTHING = 0.75;
  71776. /**
  71777. * Gets or sets the FFT table size
  71778. * @ignorenaming
  71779. */
  71780. this.FFT_SIZE = 512;
  71781. /**
  71782. * Gets or sets the bar graph amplitude
  71783. * @ignorenaming
  71784. */
  71785. this.BARGRAPHAMPLITUDE = 256;
  71786. /**
  71787. * Gets or sets the position of the debug canvas
  71788. * @ignorenaming
  71789. */
  71790. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  71791. /**
  71792. * Gets or sets the debug canvas size
  71793. * @ignorenaming
  71794. */
  71795. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  71796. this._scene = scene;
  71797. this._audioEngine = BABYLON.Engine.audioEngine;
  71798. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  71799. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  71800. this._webAudioAnalyser.minDecibels = -140;
  71801. this._webAudioAnalyser.maxDecibels = 0;
  71802. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  71803. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  71804. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  71805. }
  71806. }
  71807. /**
  71808. * Get the number of data values you will have to play with for the visualization
  71809. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  71810. * @returns a number
  71811. */
  71812. Analyser.prototype.getFrequencyBinCount = function () {
  71813. if (this._audioEngine.canUseWebAudio) {
  71814. return this._webAudioAnalyser.frequencyBinCount;
  71815. }
  71816. else {
  71817. return 0;
  71818. }
  71819. };
  71820. /**
  71821. * Gets the current frequency data as a byte array
  71822. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  71823. * @returns a Uint8Array
  71824. */
  71825. Analyser.prototype.getByteFrequencyData = function () {
  71826. if (this._audioEngine.canUseWebAudio) {
  71827. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  71828. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  71829. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  71830. }
  71831. return this._byteFreqs;
  71832. };
  71833. /**
  71834. * Gets the current waveform as a byte array
  71835. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  71836. * @returns a Uint8Array
  71837. */
  71838. Analyser.prototype.getByteTimeDomainData = function () {
  71839. if (this._audioEngine.canUseWebAudio) {
  71840. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  71841. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  71842. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  71843. }
  71844. return this._byteTime;
  71845. };
  71846. /**
  71847. * Gets the current frequency data as a float array
  71848. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  71849. * @returns a Float32Array
  71850. */
  71851. Analyser.prototype.getFloatFrequencyData = function () {
  71852. if (this._audioEngine.canUseWebAudio) {
  71853. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  71854. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  71855. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  71856. }
  71857. return this._floatFreqs;
  71858. };
  71859. /**
  71860. * Renders the debug canvas
  71861. */
  71862. Analyser.prototype.drawDebugCanvas = function () {
  71863. var _this = this;
  71864. if (this._audioEngine.canUseWebAudio) {
  71865. if (!this._debugCanvas) {
  71866. this._debugCanvas = document.createElement("canvas");
  71867. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  71868. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  71869. this._debugCanvas.style.position = "absolute";
  71870. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  71871. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  71872. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  71873. document.body.appendChild(this._debugCanvas);
  71874. this._registerFunc = function () {
  71875. _this.drawDebugCanvas();
  71876. };
  71877. this._scene.registerBeforeRender(this._registerFunc);
  71878. }
  71879. if (this._registerFunc && this._debugCanvasContext) {
  71880. var workingArray = this.getByteFrequencyData();
  71881. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  71882. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  71883. // Draw the frequency domain chart.
  71884. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  71885. var value = workingArray[i];
  71886. var percent = value / this.BARGRAPHAMPLITUDE;
  71887. var height = this.DEBUGCANVASSIZE.height * percent;
  71888. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  71889. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  71890. var hue = i / this.getFrequencyBinCount() * 360;
  71891. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  71892. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  71893. }
  71894. }
  71895. }
  71896. };
  71897. /**
  71898. * Stops rendering the debug canvas and removes it
  71899. */
  71900. Analyser.prototype.stopDebugCanvas = function () {
  71901. if (this._debugCanvas) {
  71902. if (this._registerFunc) {
  71903. this._scene.unregisterBeforeRender(this._registerFunc);
  71904. this._registerFunc = null;
  71905. }
  71906. document.body.removeChild(this._debugCanvas);
  71907. this._debugCanvas = null;
  71908. this._debugCanvasContext = null;
  71909. }
  71910. };
  71911. /**
  71912. * Connects two audio nodes
  71913. * @param inputAudioNode defines first node to connect
  71914. * @param outputAudioNode defines second node to connect
  71915. */
  71916. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  71917. if (this._audioEngine.canUseWebAudio) {
  71918. inputAudioNode.connect(this._webAudioAnalyser);
  71919. this._webAudioAnalyser.connect(outputAudioNode);
  71920. }
  71921. };
  71922. /**
  71923. * Releases all associated resources
  71924. */
  71925. Analyser.prototype.dispose = function () {
  71926. if (this._audioEngine.canUseWebAudio) {
  71927. this._webAudioAnalyser.disconnect();
  71928. }
  71929. };
  71930. return Analyser;
  71931. }());
  71932. BABYLON.Analyser = Analyser;
  71933. })(BABYLON || (BABYLON = {}));
  71934. //# sourceMappingURL=babylon.analyser.js.map
  71935. var BABYLON;
  71936. (function (BABYLON) {
  71937. /**
  71938. * Wraps one or more Sound objects and selects one with random weight for playback.
  71939. */
  71940. var WeightedSound = /** @class */ (function () {
  71941. /**
  71942. * Creates a new WeightedSound from the list of sounds given.
  71943. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  71944. * @param sounds Array of Sounds that will be selected from.
  71945. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  71946. */
  71947. function WeightedSound(loop, sounds, weights) {
  71948. var _this = this;
  71949. /** When true a Sound will be selected and played when the current playing Sound completes. */
  71950. this.loop = false;
  71951. this._coneInnerAngle = 360;
  71952. this._coneOuterAngle = 360;
  71953. this._volume = 1;
  71954. /** A Sound is currently playing. */
  71955. this.isPlaying = false;
  71956. /** A Sound is currently paused. */
  71957. this.isPaused = false;
  71958. this._sounds = [];
  71959. this._weights = [];
  71960. if (sounds.length !== weights.length) {
  71961. throw new Error('Sounds length does not equal weights length');
  71962. }
  71963. this.loop = loop;
  71964. this._weights = weights;
  71965. // Normalize the weights
  71966. var weightSum = 0;
  71967. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  71968. var weight = weights_1[_i];
  71969. weightSum += weight;
  71970. }
  71971. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  71972. for (var i = 0; i < this._weights.length; i++) {
  71973. this._weights[i] *= invWeightSum;
  71974. }
  71975. this._sounds = sounds;
  71976. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  71977. var sound = _b[_a];
  71978. sound.onEndedObservable.add(function () { _this._onended(); });
  71979. }
  71980. }
  71981. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  71982. /**
  71983. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  71984. */
  71985. get: function () {
  71986. return this._coneInnerAngle;
  71987. },
  71988. /**
  71989. * The size of cone in degress for a directional sound in which there will be no attenuation.
  71990. */
  71991. set: function (value) {
  71992. if (value !== this._coneInnerAngle) {
  71993. if (this._coneOuterAngle < value) {
  71994. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  71995. return;
  71996. }
  71997. this._coneInnerAngle = value;
  71998. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  71999. var sound = _a[_i];
  72000. sound.directionalConeInnerAngle = value;
  72001. }
  72002. }
  72003. },
  72004. enumerable: true,
  72005. configurable: true
  72006. });
  72007. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  72008. /**
  72009. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  72010. * Listener angles between innerAngle and outerAngle will falloff linearly.
  72011. */
  72012. get: function () {
  72013. return this._coneOuterAngle;
  72014. },
  72015. /**
  72016. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  72017. * Listener angles between innerAngle and outerAngle will falloff linearly.
  72018. */
  72019. set: function (value) {
  72020. if (value !== this._coneOuterAngle) {
  72021. if (value < this._coneInnerAngle) {
  72022. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72023. return;
  72024. }
  72025. this._coneOuterAngle = value;
  72026. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72027. var sound = _a[_i];
  72028. sound.directionalConeOuterAngle = value;
  72029. }
  72030. }
  72031. },
  72032. enumerable: true,
  72033. configurable: true
  72034. });
  72035. Object.defineProperty(WeightedSound.prototype, "volume", {
  72036. /**
  72037. * Playback volume.
  72038. */
  72039. get: function () {
  72040. return this._volume;
  72041. },
  72042. /**
  72043. * Playback volume.
  72044. */
  72045. set: function (value) {
  72046. if (value !== this._volume) {
  72047. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72048. var sound = _a[_i];
  72049. sound.setVolume(value);
  72050. }
  72051. }
  72052. },
  72053. enumerable: true,
  72054. configurable: true
  72055. });
  72056. WeightedSound.prototype._onended = function () {
  72057. if (this._currentIndex !== undefined) {
  72058. this._sounds[this._currentIndex].autoplay = false;
  72059. }
  72060. if (this.loop && this.isPlaying) {
  72061. this.play();
  72062. }
  72063. else {
  72064. this.isPlaying = false;
  72065. }
  72066. };
  72067. /**
  72068. * Suspend playback
  72069. */
  72070. WeightedSound.prototype.pause = function () {
  72071. this.isPaused = true;
  72072. if (this._currentIndex !== undefined) {
  72073. this._sounds[this._currentIndex].pause();
  72074. }
  72075. };
  72076. /**
  72077. * Stop playback
  72078. */
  72079. WeightedSound.prototype.stop = function () {
  72080. this.isPlaying = false;
  72081. if (this._currentIndex !== undefined) {
  72082. this._sounds[this._currentIndex].stop();
  72083. }
  72084. };
  72085. /**
  72086. * Start playback.
  72087. * @param startOffset Position the clip head at a specific time in seconds.
  72088. */
  72089. WeightedSound.prototype.play = function (startOffset) {
  72090. if (!this.isPaused) {
  72091. this.stop();
  72092. var randomValue = Math.random();
  72093. var total = 0;
  72094. for (var i = 0; i < this._weights.length; i++) {
  72095. total += this._weights[i];
  72096. if (randomValue <= total) {
  72097. this._currentIndex = i;
  72098. break;
  72099. }
  72100. }
  72101. }
  72102. var sound = this._sounds[this._currentIndex];
  72103. if (sound.isReady()) {
  72104. sound.play(0, this.isPaused ? undefined : startOffset);
  72105. }
  72106. else {
  72107. sound.autoplay = true;
  72108. }
  72109. this.isPlaying = true;
  72110. this.isPaused = false;
  72111. };
  72112. return WeightedSound;
  72113. }());
  72114. BABYLON.WeightedSound = WeightedSound;
  72115. })(BABYLON || (BABYLON = {}));
  72116. //# sourceMappingURL=babylon.weightedsound.js.map
  72117. var BABYLON;
  72118. (function (BABYLON) {
  72119. // Adds the parser to the scene parsers.
  72120. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  72121. // TODO: add sound
  72122. var loadedSounds = [];
  72123. var loadedSound;
  72124. container.sounds = container.sounds || [];
  72125. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  72126. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  72127. var parsedSound = parsedData.sounds[index];
  72128. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72129. if (!parsedSound.url) {
  72130. parsedSound.url = parsedSound.name;
  72131. }
  72132. if (!loadedSounds[parsedSound.url]) {
  72133. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  72134. loadedSounds[parsedSound.url] = loadedSound;
  72135. container.sounds.push(loadedSound);
  72136. }
  72137. else {
  72138. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  72139. }
  72140. }
  72141. else {
  72142. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  72143. }
  72144. }
  72145. }
  72146. loadedSounds = [];
  72147. });
  72148. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  72149. get: function () {
  72150. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72151. if (!compo) {
  72152. compo = new AudioSceneComponent(this);
  72153. this._addComponent(compo);
  72154. }
  72155. if (!this._mainSoundTrack) {
  72156. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  72157. }
  72158. return this._mainSoundTrack;
  72159. },
  72160. enumerable: true,
  72161. configurable: true
  72162. });
  72163. BABYLON.Scene.prototype.getSoundByName = function (name) {
  72164. var index;
  72165. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  72166. if (this.mainSoundTrack.soundCollection[index].name === name) {
  72167. return this.mainSoundTrack.soundCollection[index];
  72168. }
  72169. }
  72170. if (this.soundTracks) {
  72171. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  72172. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  72173. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  72174. return this.soundTracks[sdIndex].soundCollection[index];
  72175. }
  72176. }
  72177. }
  72178. }
  72179. return null;
  72180. };
  72181. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  72182. get: function () {
  72183. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72184. if (!compo) {
  72185. compo = new AudioSceneComponent(this);
  72186. this._addComponent(compo);
  72187. }
  72188. return compo.audioEnabled;
  72189. },
  72190. set: function (value) {
  72191. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72192. if (!compo) {
  72193. compo = new AudioSceneComponent(this);
  72194. this._addComponent(compo);
  72195. }
  72196. if (value) {
  72197. compo.enableAudio();
  72198. }
  72199. else {
  72200. compo.disableAudio();
  72201. }
  72202. },
  72203. enumerable: true,
  72204. configurable: true
  72205. });
  72206. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  72207. get: function () {
  72208. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72209. if (!compo) {
  72210. compo = new AudioSceneComponent(this);
  72211. this._addComponent(compo);
  72212. }
  72213. return compo.headphone;
  72214. },
  72215. set: function (value) {
  72216. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72217. if (!compo) {
  72218. compo = new AudioSceneComponent(this);
  72219. this._addComponent(compo);
  72220. }
  72221. if (value) {
  72222. compo.switchAudioModeForHeadphones();
  72223. }
  72224. else {
  72225. compo.switchAudioModeForNormalSpeakers();
  72226. }
  72227. },
  72228. enumerable: true,
  72229. configurable: true
  72230. });
  72231. /**
  72232. * Defines the sound scene component responsible to manage any sounds
  72233. * in a given scene.
  72234. */
  72235. var AudioSceneComponent = /** @class */ (function () {
  72236. /**
  72237. * Creates a new instance of the component for the given scene
  72238. * @param scene Defines the scene to register the component in
  72239. */
  72240. function AudioSceneComponent(scene) {
  72241. /**
  72242. * The component name helpfull to identify the component in the list of scene components.
  72243. */
  72244. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  72245. this._audioEnabled = true;
  72246. this._headphone = false;
  72247. this.scene = scene;
  72248. scene.soundTracks = new Array();
  72249. scene.sounds = new Array();
  72250. }
  72251. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  72252. /**
  72253. * Gets whether audio is enabled or not.
  72254. * Please use related enable/disable method to switch state.
  72255. */
  72256. get: function () {
  72257. return this._audioEnabled;
  72258. },
  72259. enumerable: true,
  72260. configurable: true
  72261. });
  72262. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  72263. /**
  72264. * Gets whether audio is outputing to headphone or not.
  72265. * Please use the according Switch methods to change output.
  72266. */
  72267. get: function () {
  72268. return this._headphone;
  72269. },
  72270. enumerable: true,
  72271. configurable: true
  72272. });
  72273. /**
  72274. * Registers the component in a given scene
  72275. */
  72276. AudioSceneComponent.prototype.register = function () {
  72277. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  72278. };
  72279. /**
  72280. * Rebuilds the elements related to this component in case of
  72281. * context lost for instance.
  72282. */
  72283. AudioSceneComponent.prototype.rebuild = function () {
  72284. // Nothing to do here. (Not rendering related)
  72285. };
  72286. /**
  72287. * Serializes the component data to the specified json object
  72288. * @param serializationObject The object to serialize to
  72289. */
  72290. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  72291. serializationObject.sounds = [];
  72292. if (this.scene.soundTracks) {
  72293. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  72294. var soundtrack = this.scene.soundTracks[index];
  72295. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  72296. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  72297. }
  72298. }
  72299. }
  72300. };
  72301. /**
  72302. * Adds all the element from the container to the scene
  72303. * @param container the container holding the elements
  72304. */
  72305. AudioSceneComponent.prototype.addFromContainer = function (container) {
  72306. var _this = this;
  72307. if (!container.sounds) {
  72308. return;
  72309. }
  72310. container.sounds.forEach(function (sound) {
  72311. sound.play();
  72312. sound.autoplay = true;
  72313. _this.scene.mainSoundTrack.AddSound(sound);
  72314. });
  72315. };
  72316. /**
  72317. * Removes all the elements in the container from the scene
  72318. * @param container contains the elements to remove
  72319. */
  72320. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  72321. var _this = this;
  72322. if (!container.sounds) {
  72323. return;
  72324. }
  72325. container.sounds.forEach(function (sound) {
  72326. sound.stop();
  72327. sound.autoplay = false;
  72328. _this.scene.mainSoundTrack.RemoveSound(sound);
  72329. });
  72330. };
  72331. /**
  72332. * Disposes the component and the associated ressources.
  72333. */
  72334. AudioSceneComponent.prototype.dispose = function () {
  72335. var scene = this.scene;
  72336. if (scene._mainSoundTrack) {
  72337. scene.mainSoundTrack.dispose();
  72338. }
  72339. if (scene.soundTracks) {
  72340. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  72341. scene.soundTracks[scIndex].dispose();
  72342. }
  72343. }
  72344. };
  72345. /**
  72346. * Disables audio in the associated scene.
  72347. */
  72348. AudioSceneComponent.prototype.disableAudio = function () {
  72349. var scene = this.scene;
  72350. this._audioEnabled = false;
  72351. var i;
  72352. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72353. scene.mainSoundTrack.soundCollection[i].pause();
  72354. }
  72355. if (scene.soundTracks) {
  72356. for (i = 0; i < scene.soundTracks.length; i++) {
  72357. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72358. scene.soundTracks[i].soundCollection[j].pause();
  72359. }
  72360. }
  72361. }
  72362. };
  72363. /**
  72364. * Enables audio in the associated scene.
  72365. */
  72366. AudioSceneComponent.prototype.enableAudio = function () {
  72367. var scene = this.scene;
  72368. this._audioEnabled = true;
  72369. var i;
  72370. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72371. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  72372. scene.mainSoundTrack.soundCollection[i].play();
  72373. }
  72374. }
  72375. if (scene.soundTracks) {
  72376. for (i = 0; i < scene.soundTracks.length; i++) {
  72377. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72378. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  72379. scene.soundTracks[i].soundCollection[j].play();
  72380. }
  72381. }
  72382. }
  72383. }
  72384. };
  72385. /**
  72386. * Switch audio to headphone output.
  72387. */
  72388. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  72389. var scene = this.scene;
  72390. this._headphone = true;
  72391. scene.mainSoundTrack.switchPanningModelToHRTF();
  72392. if (scene.soundTracks) {
  72393. for (var i = 0; i < scene.soundTracks.length; i++) {
  72394. scene.soundTracks[i].switchPanningModelToHRTF();
  72395. }
  72396. }
  72397. };
  72398. /**
  72399. * Switch audio to normal speakers.
  72400. */
  72401. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  72402. var scene = this.scene;
  72403. this._headphone = false;
  72404. scene.mainSoundTrack.switchPanningModelToEqualPower();
  72405. if (scene.soundTracks) {
  72406. for (var i = 0; i < scene.soundTracks.length; i++) {
  72407. scene.soundTracks[i].switchPanningModelToEqualPower();
  72408. }
  72409. }
  72410. };
  72411. AudioSceneComponent.prototype._afterRender = function () {
  72412. var scene = this.scene;
  72413. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  72414. return;
  72415. }
  72416. var listeningCamera;
  72417. var audioEngine = BABYLON.Engine.audioEngine;
  72418. if (scene.activeCameras.length > 0) {
  72419. listeningCamera = scene.activeCameras[0];
  72420. }
  72421. else {
  72422. listeningCamera = scene.activeCamera;
  72423. }
  72424. if (listeningCamera && audioEngine.audioContext) {
  72425. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  72426. // for VR cameras
  72427. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  72428. listeningCamera = listeningCamera.rigCameras[0];
  72429. }
  72430. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  72431. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  72432. cameraDirection.normalize();
  72433. // To avoid some errors on GearVR
  72434. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  72435. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  72436. }
  72437. var i;
  72438. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72439. var sound = scene.mainSoundTrack.soundCollection[i];
  72440. if (sound.useCustomAttenuation) {
  72441. sound.updateDistanceFromListener();
  72442. }
  72443. }
  72444. if (scene.soundTracks) {
  72445. for (i = 0; i < scene.soundTracks.length; i++) {
  72446. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72447. sound = scene.soundTracks[i].soundCollection[j];
  72448. if (sound.useCustomAttenuation) {
  72449. sound.updateDistanceFromListener();
  72450. }
  72451. }
  72452. }
  72453. }
  72454. }
  72455. };
  72456. return AudioSceneComponent;
  72457. }());
  72458. BABYLON.AudioSceneComponent = AudioSceneComponent;
  72459. })(BABYLON || (BABYLON = {}));
  72460. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  72461. var BABYLON;
  72462. (function (BABYLON) {
  72463. /**
  72464. * This defines an action helpful to play a defined sound on a triggered action.
  72465. */
  72466. var PlaySoundAction = /** @class */ (function (_super) {
  72467. __extends(PlaySoundAction, _super);
  72468. /**
  72469. * Instantiate the action
  72470. * @param triggerOptions defines the trigger options
  72471. * @param sound defines the sound to play
  72472. * @param condition defines the trigger related conditions
  72473. */
  72474. function PlaySoundAction(triggerOptions, sound, condition) {
  72475. var _this = _super.call(this, triggerOptions, condition) || this;
  72476. _this._sound = sound;
  72477. return _this;
  72478. }
  72479. /** @hidden */
  72480. PlaySoundAction.prototype._prepare = function () {
  72481. };
  72482. /**
  72483. * Execute the action and play the sound.
  72484. */
  72485. PlaySoundAction.prototype.execute = function () {
  72486. if (this._sound !== undefined) {
  72487. this._sound.play();
  72488. }
  72489. };
  72490. /**
  72491. * Serializes the actions and its related information.
  72492. * @param parent defines the object to serialize in
  72493. * @returns the serialized object
  72494. */
  72495. PlaySoundAction.prototype.serialize = function (parent) {
  72496. return _super.prototype._serialize.call(this, {
  72497. name: "PlaySoundAction",
  72498. properties: [{ name: "sound", value: this._sound.name }]
  72499. }, parent);
  72500. };
  72501. return PlaySoundAction;
  72502. }(BABYLON.Action));
  72503. BABYLON.PlaySoundAction = PlaySoundAction;
  72504. /**
  72505. * This defines an action helpful to stop a defined sound on a triggered action.
  72506. */
  72507. var StopSoundAction = /** @class */ (function (_super) {
  72508. __extends(StopSoundAction, _super);
  72509. /**
  72510. * Instantiate the action
  72511. * @param triggerOptions defines the trigger options
  72512. * @param sound defines the sound to stop
  72513. * @param condition defines the trigger related conditions
  72514. */
  72515. function StopSoundAction(triggerOptions, sound, condition) {
  72516. var _this = _super.call(this, triggerOptions, condition) || this;
  72517. _this._sound = sound;
  72518. return _this;
  72519. }
  72520. /** @hidden */
  72521. StopSoundAction.prototype._prepare = function () {
  72522. };
  72523. /**
  72524. * Execute the action and stop the sound.
  72525. */
  72526. StopSoundAction.prototype.execute = function () {
  72527. if (this._sound !== undefined) {
  72528. this._sound.stop();
  72529. }
  72530. };
  72531. /**
  72532. * Serializes the actions and its related information.
  72533. * @param parent defines the object to serialize in
  72534. * @returns the serialized object
  72535. */
  72536. StopSoundAction.prototype.serialize = function (parent) {
  72537. return _super.prototype._serialize.call(this, {
  72538. name: "StopSoundAction",
  72539. properties: [{ name: "sound", value: this._sound.name }]
  72540. }, parent);
  72541. };
  72542. return StopSoundAction;
  72543. }(BABYLON.Action));
  72544. BABYLON.StopSoundAction = StopSoundAction;
  72545. })(BABYLON || (BABYLON = {}));
  72546. //# sourceMappingURL=babylon.directAudioActions.js.map
  72547. var BABYLON;
  72548. (function (BABYLON) {
  72549. /**
  72550. * Class for creating a cube texture
  72551. */
  72552. var CubeTexture = /** @class */ (function (_super) {
  72553. __extends(CubeTexture, _super);
  72554. /**
  72555. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  72556. * as prefiltered data.
  72557. * @param rootUrl defines the url of the texture or the root name of the six images
  72558. * @param scene defines the scene the texture is attached to
  72559. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  72560. * @param noMipmap defines if mipmaps should be created or not
  72561. * @param files defines the six files to load for the different faces
  72562. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  72563. * @param onError defines a callback triggered in case of error during load
  72564. * @param format defines the internal format to use for the texture once loaded
  72565. * @param prefiltered defines whether or not the texture is created from prefiltered data
  72566. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  72567. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  72568. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  72569. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  72570. * @return the cube texture
  72571. */
  72572. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  72573. if (extensions === void 0) { extensions = null; }
  72574. if (noMipmap === void 0) { noMipmap = false; }
  72575. if (files === void 0) { files = null; }
  72576. if (onLoad === void 0) { onLoad = null; }
  72577. if (onError === void 0) { onError = null; }
  72578. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72579. if (prefiltered === void 0) { prefiltered = false; }
  72580. if (forcedExtension === void 0) { forcedExtension = null; }
  72581. if (createPolynomials === void 0) { createPolynomials = false; }
  72582. if (lodScale === void 0) { lodScale = 0.8; }
  72583. if (lodOffset === void 0) { lodOffset = 0; }
  72584. var _this = _super.call(this, scene) || this;
  72585. /**
  72586. * Gets or sets the center of the bounding box associated with the cube texture.
  72587. * It must define where the camera used to render the texture was set
  72588. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  72589. */
  72590. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72591. _this._rotationY = 0;
  72592. /** @hidden */
  72593. _this._prefiltered = false;
  72594. _this.name = rootUrl;
  72595. _this.url = rootUrl;
  72596. _this._noMipmap = noMipmap;
  72597. _this.hasAlpha = false;
  72598. _this._format = format;
  72599. _this.isCube = true;
  72600. _this._textureMatrix = BABYLON.Matrix.Identity();
  72601. _this._createPolynomials = createPolynomials;
  72602. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72603. if (!rootUrl && !files) {
  72604. return _this;
  72605. }
  72606. var lastDot = rootUrl.lastIndexOf(".");
  72607. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  72608. var isDDS = (extension === ".dds");
  72609. var isEnv = (extension === ".env");
  72610. if (isEnv) {
  72611. _this.gammaSpace = false;
  72612. _this._prefiltered = false;
  72613. }
  72614. else {
  72615. _this._prefiltered = prefiltered;
  72616. if (prefiltered) {
  72617. _this.gammaSpace = false;
  72618. }
  72619. }
  72620. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  72621. if (!files) {
  72622. if (!isEnv && !isDDS && !extensions) {
  72623. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  72624. }
  72625. files = [];
  72626. if (extensions) {
  72627. for (var index = 0; index < extensions.length; index++) {
  72628. files.push(rootUrl + extensions[index]);
  72629. }
  72630. }
  72631. }
  72632. _this._files = files;
  72633. if (!_this._texture) {
  72634. if (!scene.useDelayedTextureLoading) {
  72635. if (prefiltered) {
  72636. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  72637. }
  72638. else {
  72639. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  72640. }
  72641. }
  72642. else {
  72643. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72644. }
  72645. }
  72646. else if (onLoad) {
  72647. if (_this._texture.isReady) {
  72648. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  72649. }
  72650. else {
  72651. _this._texture.onLoadedObservable.add(onLoad);
  72652. }
  72653. }
  72654. return _this;
  72655. }
  72656. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  72657. /**
  72658. * Returns the bounding box size
  72659. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  72660. */
  72661. get: function () {
  72662. return this._boundingBoxSize;
  72663. },
  72664. /**
  72665. * Gets or sets the size of the bounding box associated with the cube texture
  72666. * When defined, the cubemap will switch to local mode
  72667. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72668. * @example https://www.babylonjs-playground.com/#RNASML
  72669. */
  72670. set: function (value) {
  72671. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72672. return;
  72673. }
  72674. this._boundingBoxSize = value;
  72675. var scene = this.getScene();
  72676. if (scene) {
  72677. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72678. }
  72679. },
  72680. enumerable: true,
  72681. configurable: true
  72682. });
  72683. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  72684. /**
  72685. * Gets texture matrix rotation angle around Y axis radians.
  72686. */
  72687. get: function () {
  72688. return this._rotationY;
  72689. },
  72690. /**
  72691. * Sets texture matrix rotation angle around Y axis in radians.
  72692. */
  72693. set: function (value) {
  72694. this._rotationY = value;
  72695. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  72696. },
  72697. enumerable: true,
  72698. configurable: true
  72699. });
  72700. /**
  72701. * Creates a cube texture from an array of image urls
  72702. * @param files defines an array of image urls
  72703. * @param scene defines the hosting scene
  72704. * @param noMipmap specifies if mip maps are not used
  72705. * @returns a cube texture
  72706. */
  72707. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  72708. var rootUrlKey = "";
  72709. files.forEach(function (url) { return rootUrlKey += url; });
  72710. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  72711. };
  72712. /**
  72713. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  72714. * @param url defines the url of the prefiltered texture
  72715. * @param scene defines the scene the texture is attached to
  72716. * @param forcedExtension defines the extension of the file if different from the url
  72717. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  72718. * @return the prefiltered texture
  72719. */
  72720. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  72721. if (forcedExtension === void 0) { forcedExtension = null; }
  72722. if (createPolynomials === void 0) { createPolynomials = true; }
  72723. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  72724. };
  72725. /**
  72726. * Delays loading of the cube texture
  72727. */
  72728. CubeTexture.prototype.delayLoad = function () {
  72729. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  72730. return;
  72731. }
  72732. var scene = this.getScene();
  72733. if (!scene) {
  72734. return;
  72735. }
  72736. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  72737. this._texture = this._getFromCache(this.url, this._noMipmap);
  72738. if (!this._texture) {
  72739. if (this._prefiltered) {
  72740. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  72741. }
  72742. else {
  72743. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  72744. }
  72745. }
  72746. };
  72747. /**
  72748. * Returns the reflection texture matrix
  72749. * @returns the reflection texture matrix
  72750. */
  72751. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  72752. return this._textureMatrix;
  72753. };
  72754. /**
  72755. * Sets the reflection texture matrix
  72756. * @param value Reflection texture matrix
  72757. */
  72758. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  72759. this._textureMatrix = value;
  72760. };
  72761. /**
  72762. * Parses text to create a cube texture
  72763. * @param parsedTexture define the serialized text to read from
  72764. * @param scene defines the hosting scene
  72765. * @param rootUrl defines the root url of the cube texture
  72766. * @returns a cube texture
  72767. */
  72768. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  72769. var texture = BABYLON.SerializationHelper.Parse(function () {
  72770. var prefiltered = false;
  72771. if (parsedTexture.prefiltered) {
  72772. prefiltered = parsedTexture.prefiltered;
  72773. }
  72774. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  72775. }, parsedTexture, scene);
  72776. // Local Cubemaps
  72777. if (parsedTexture.boundingBoxPosition) {
  72778. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  72779. }
  72780. if (parsedTexture.boundingBoxSize) {
  72781. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  72782. }
  72783. // Animations
  72784. if (parsedTexture.animations) {
  72785. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  72786. var parsedAnimation = parsedTexture.animations[animationIndex];
  72787. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  72788. }
  72789. }
  72790. return texture;
  72791. };
  72792. /**
  72793. * Makes a clone, or deep copy, of the cube texture
  72794. * @returns a new cube texture
  72795. */
  72796. CubeTexture.prototype.clone = function () {
  72797. var _this = this;
  72798. return BABYLON.SerializationHelper.Clone(function () {
  72799. var scene = _this.getScene();
  72800. if (!scene) {
  72801. return _this;
  72802. }
  72803. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  72804. }, this);
  72805. };
  72806. __decorate([
  72807. BABYLON.serialize("rotationY")
  72808. ], CubeTexture.prototype, "rotationY", null);
  72809. return CubeTexture;
  72810. }(BABYLON.BaseTexture));
  72811. BABYLON.CubeTexture = CubeTexture;
  72812. })(BABYLON || (BABYLON = {}));
  72813. //# sourceMappingURL=babylon.cubeTexture.js.map
  72814. var BABYLON;
  72815. (function (BABYLON) {
  72816. /**
  72817. * Raw cube texture where the raw buffers are passed in
  72818. */
  72819. var RawCubeTexture = /** @class */ (function (_super) {
  72820. __extends(RawCubeTexture, _super);
  72821. /**
  72822. * Creates a cube texture where the raw buffers are passed in.
  72823. * @param scene defines the scene the texture is attached to
  72824. * @param data defines the array of data to use to create each face
  72825. * @param size defines the size of the textures
  72826. * @param format defines the format of the data
  72827. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  72828. * @param generateMipMaps defines if the engine should generate the mip levels
  72829. * @param invertY defines if data must be stored with Y axis inverted
  72830. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  72831. * @param compression defines the compression used (null by default)
  72832. */
  72833. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  72834. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72835. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72836. if (generateMipMaps === void 0) { generateMipMaps = false; }
  72837. if (invertY === void 0) { invertY = false; }
  72838. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72839. if (compression === void 0) { compression = null; }
  72840. var _this = _super.call(this, "", scene) || this;
  72841. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  72842. return _this;
  72843. }
  72844. /**
  72845. * Updates the raw cube texture.
  72846. * @param data defines the data to store
  72847. * @param format defines the data format
  72848. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  72849. * @param invertY defines if data must be stored with Y axis inverted
  72850. * @param compression defines the compression used (null by default)
  72851. * @param level defines which level of the texture to update
  72852. */
  72853. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  72854. if (compression === void 0) { compression = null; }
  72855. if (level === void 0) { level = 0; }
  72856. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  72857. };
  72858. /**
  72859. * Updates a raw cube texture with RGBD encoded data.
  72860. * @param data defines the array of data [mipmap][face] to use to create each face
  72861. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  72862. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  72863. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  72864. * @returns a promsie that resolves when the operation is complete
  72865. */
  72866. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  72867. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  72868. if (lodScale === void 0) { lodScale = 0.8; }
  72869. if (lodOffset === void 0) { lodOffset = 0; }
  72870. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  72871. };
  72872. /**
  72873. * Clones the raw cube texture.
  72874. * @return a new cube texture
  72875. */
  72876. RawCubeTexture.prototype.clone = function () {
  72877. var _this = this;
  72878. return BABYLON.SerializationHelper.Clone(function () {
  72879. var scene = _this.getScene();
  72880. var internalTexture = _this._texture;
  72881. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  72882. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  72883. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  72884. }
  72885. return texture;
  72886. }, this);
  72887. };
  72888. /** @hidden */
  72889. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  72890. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  72891. internalTexture._bufferViewArrayArray = data;
  72892. internalTexture._lodGenerationScale = lodScale;
  72893. internalTexture._lodGenerationOffset = lodOffset;
  72894. internalTexture._sphericalPolynomial = sphericalPolynomial;
  72895. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  72896. internalTexture.isReady = true;
  72897. });
  72898. };
  72899. return RawCubeTexture;
  72900. }(BABYLON.CubeTexture));
  72901. BABYLON.RawCubeTexture = RawCubeTexture;
  72902. })(BABYLON || (BABYLON = {}));
  72903. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  72904. var BABYLON;
  72905. (function (BABYLON) {
  72906. /**
  72907. * This Helps creating a texture that will be created from a camera in your scene.
  72908. * It is basically a dynamic texture that could be used to create special effects for instance.
  72909. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  72910. */
  72911. var RenderTargetTexture = /** @class */ (function (_super) {
  72912. __extends(RenderTargetTexture, _super);
  72913. /**
  72914. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  72915. * or used a shadow, depth texture...
  72916. * @param name The friendly name of the texture
  72917. * @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)
  72918. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  72919. * @param generateMipMaps True if mip maps need to be generated after render.
  72920. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  72921. * @param type The type of the buffer in the RTT (int, half float, float...)
  72922. * @param isCube True if a cube texture needs to be created
  72923. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  72924. * @param generateDepthBuffer True to generate a depth buffer
  72925. * @param generateStencilBuffer True to generate a stencil buffer
  72926. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  72927. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  72928. * @param delayAllocation if the texture allocation should be delayed (default: false)
  72929. */
  72930. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format, delayAllocation) {
  72931. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  72932. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72933. if (isCube === void 0) { isCube = false; }
  72934. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72935. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  72936. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  72937. if (isMulti === void 0) { isMulti = false; }
  72938. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72939. if (delayAllocation === void 0) { delayAllocation = false; }
  72940. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  72941. _this.isCube = isCube;
  72942. /**
  72943. * Define if particles should be rendered in your texture.
  72944. */
  72945. _this.renderParticles = true;
  72946. /**
  72947. * Define if sprites should be rendered in your texture.
  72948. */
  72949. _this.renderSprites = false;
  72950. /**
  72951. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  72952. */
  72953. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  72954. /**
  72955. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  72956. */
  72957. _this.ignoreCameraViewport = false;
  72958. /**
  72959. * An event triggered when the texture is unbind.
  72960. */
  72961. _this.onBeforeBindObservable = new BABYLON.Observable();
  72962. /**
  72963. * An event triggered when the texture is unbind.
  72964. */
  72965. _this.onAfterUnbindObservable = new BABYLON.Observable();
  72966. /**
  72967. * An event triggered before rendering the texture
  72968. */
  72969. _this.onBeforeRenderObservable = new BABYLON.Observable();
  72970. /**
  72971. * An event triggered after rendering the texture
  72972. */
  72973. _this.onAfterRenderObservable = new BABYLON.Observable();
  72974. /**
  72975. * An event triggered after the texture clear
  72976. */
  72977. _this.onClearObservable = new BABYLON.Observable();
  72978. _this._currentRefreshId = -1;
  72979. _this._refreshRate = 1;
  72980. _this._samples = 1;
  72981. /**
  72982. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  72983. * It must define where the camera used to render the texture is set
  72984. */
  72985. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72986. scene = _this.getScene();
  72987. if (!scene) {
  72988. return _this;
  72989. }
  72990. _this.renderList = new Array();
  72991. _this._engine = scene.getEngine();
  72992. _this.name = name;
  72993. _this.isRenderTarget = true;
  72994. _this._initialSizeParameter = size;
  72995. _this._processSizeParameter(size);
  72996. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  72997. });
  72998. _this._generateMipMaps = generateMipMaps ? true : false;
  72999. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  73000. // Rendering groups
  73001. _this._renderingManager = new BABYLON.RenderingManager(scene);
  73002. _this._renderingManager._useSceneAutoClearSetup = true;
  73003. if (isMulti) {
  73004. return _this;
  73005. }
  73006. _this._renderTargetOptions = {
  73007. generateMipMaps: generateMipMaps,
  73008. type: type,
  73009. format: format,
  73010. samplingMode: samplingMode,
  73011. generateDepthBuffer: generateDepthBuffer,
  73012. generateStencilBuffer: generateStencilBuffer
  73013. };
  73014. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  73015. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73016. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73017. }
  73018. if (!delayAllocation) {
  73019. if (isCube) {
  73020. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  73021. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  73022. _this._textureMatrix = BABYLON.Matrix.Identity();
  73023. }
  73024. else {
  73025. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  73026. }
  73027. }
  73028. return _this;
  73029. }
  73030. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  73031. /**
  73032. * Use this list to define the list of mesh you want to render.
  73033. */
  73034. get: function () {
  73035. return this._renderList;
  73036. },
  73037. set: function (value) {
  73038. this._renderList = value;
  73039. if (this._renderList) {
  73040. this._hookArray(this._renderList);
  73041. }
  73042. },
  73043. enumerable: true,
  73044. configurable: true
  73045. });
  73046. RenderTargetTexture.prototype._hookArray = function (array) {
  73047. var _this = this;
  73048. var oldPush = array.push;
  73049. array.push = function () {
  73050. var items = [];
  73051. for (var _i = 0; _i < arguments.length; _i++) {
  73052. items[_i] = arguments[_i];
  73053. }
  73054. var wasEmpty = array.length === 0;
  73055. var result = oldPush.apply(array, items);
  73056. if (wasEmpty) {
  73057. _this.getScene().meshes.forEach(function (mesh) {
  73058. mesh._markSubMeshesAsLightDirty();
  73059. });
  73060. }
  73061. return result;
  73062. };
  73063. var oldSplice = array.splice;
  73064. array.splice = function (index, deleteCount) {
  73065. var deleted = oldSplice.apply(array, [index, deleteCount]);
  73066. if (array.length === 0) {
  73067. _this.getScene().meshes.forEach(function (mesh) {
  73068. mesh._markSubMeshesAsLightDirty();
  73069. });
  73070. }
  73071. return deleted;
  73072. };
  73073. };
  73074. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  73075. /**
  73076. * Set a after unbind callback in the texture.
  73077. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  73078. */
  73079. set: function (callback) {
  73080. if (this._onAfterUnbindObserver) {
  73081. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  73082. }
  73083. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  73084. },
  73085. enumerable: true,
  73086. configurable: true
  73087. });
  73088. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  73089. /**
  73090. * Set a before render callback in the texture.
  73091. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  73092. */
  73093. set: function (callback) {
  73094. if (this._onBeforeRenderObserver) {
  73095. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73096. }
  73097. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73098. },
  73099. enumerable: true,
  73100. configurable: true
  73101. });
  73102. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  73103. /**
  73104. * Set a after render callback in the texture.
  73105. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  73106. */
  73107. set: function (callback) {
  73108. if (this._onAfterRenderObserver) {
  73109. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73110. }
  73111. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73112. },
  73113. enumerable: true,
  73114. configurable: true
  73115. });
  73116. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  73117. /**
  73118. * Set a clear callback in the texture.
  73119. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  73120. */
  73121. set: function (callback) {
  73122. if (this._onClearObserver) {
  73123. this.onClearObservable.remove(this._onClearObserver);
  73124. }
  73125. this._onClearObserver = this.onClearObservable.add(callback);
  73126. },
  73127. enumerable: true,
  73128. configurable: true
  73129. });
  73130. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  73131. /**
  73132. * Gets render target creation options that were used.
  73133. */
  73134. get: function () {
  73135. return this._renderTargetOptions;
  73136. },
  73137. enumerable: true,
  73138. configurable: true
  73139. });
  73140. RenderTargetTexture.prototype._onRatioRescale = function () {
  73141. if (this._sizeRatio) {
  73142. this.resize(this._initialSizeParameter);
  73143. }
  73144. };
  73145. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  73146. get: function () {
  73147. return this._boundingBoxSize;
  73148. },
  73149. /**
  73150. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  73151. * When defined, the cubemap will switch to local mode
  73152. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73153. * @example https://www.babylonjs-playground.com/#RNASML
  73154. */
  73155. set: function (value) {
  73156. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73157. return;
  73158. }
  73159. this._boundingBoxSize = value;
  73160. var scene = this.getScene();
  73161. if (scene) {
  73162. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73163. }
  73164. },
  73165. enumerable: true,
  73166. configurable: true
  73167. });
  73168. /**
  73169. * Creates a depth stencil texture.
  73170. * This is only available in WebGL 2 or with the depth texture extension available.
  73171. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  73172. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  73173. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  73174. */
  73175. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  73176. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  73177. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  73178. if (generateStencil === void 0) { generateStencil = false; }
  73179. if (!this.getScene()) {
  73180. return;
  73181. }
  73182. var engine = this.getScene().getEngine();
  73183. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  73184. bilinearFiltering: bilinearFiltering,
  73185. comparisonFunction: comparisonFunction,
  73186. generateStencil: generateStencil,
  73187. isCube: this.isCube
  73188. });
  73189. engine.setFrameBufferDepthStencilTexture(this);
  73190. };
  73191. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  73192. if (size.ratio) {
  73193. this._sizeRatio = size.ratio;
  73194. this._size = {
  73195. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  73196. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  73197. };
  73198. }
  73199. else {
  73200. this._size = size;
  73201. }
  73202. };
  73203. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  73204. /**
  73205. * Define the number of samples to use in case of MSAA.
  73206. * It defaults to one meaning no MSAA has been enabled.
  73207. */
  73208. get: function () {
  73209. return this._samples;
  73210. },
  73211. set: function (value) {
  73212. if (this._samples === value) {
  73213. return;
  73214. }
  73215. var scene = this.getScene();
  73216. if (!scene) {
  73217. return;
  73218. }
  73219. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  73220. },
  73221. enumerable: true,
  73222. configurable: true
  73223. });
  73224. /**
  73225. * Resets the refresh counter of the texture and start bak from scratch.
  73226. * Could be usefull to regenerate the texture if it is setup to render only once.
  73227. */
  73228. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  73229. this._currentRefreshId = -1;
  73230. };
  73231. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  73232. /**
  73233. * Define the refresh rate of the texture or the rendering frequency.
  73234. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  73235. */
  73236. get: function () {
  73237. return this._refreshRate;
  73238. },
  73239. set: function (value) {
  73240. this._refreshRate = value;
  73241. this.resetRefreshCounter();
  73242. },
  73243. enumerable: true,
  73244. configurable: true
  73245. });
  73246. /**
  73247. * Adds a post process to the render target rendering passes.
  73248. * @param postProcess define the post process to add
  73249. */
  73250. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  73251. if (!this._postProcessManager) {
  73252. var scene = this.getScene();
  73253. if (!scene) {
  73254. return;
  73255. }
  73256. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  73257. this._postProcesses = new Array();
  73258. }
  73259. this._postProcesses.push(postProcess);
  73260. this._postProcesses[0].autoClear = false;
  73261. };
  73262. /**
  73263. * Clear all the post processes attached to the render target
  73264. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  73265. */
  73266. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  73267. if (dispose === void 0) { dispose = false; }
  73268. if (!this._postProcesses) {
  73269. return;
  73270. }
  73271. if (dispose) {
  73272. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  73273. var postProcess = _a[_i];
  73274. postProcess.dispose();
  73275. }
  73276. }
  73277. this._postProcesses = [];
  73278. };
  73279. /**
  73280. * Remove one of the post process from the list of attached post processes to the texture
  73281. * @param postProcess define the post process to remove from the list
  73282. */
  73283. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  73284. if (!this._postProcesses) {
  73285. return;
  73286. }
  73287. var index = this._postProcesses.indexOf(postProcess);
  73288. if (index === -1) {
  73289. return;
  73290. }
  73291. this._postProcesses.splice(index, 1);
  73292. if (this._postProcesses.length > 0) {
  73293. this._postProcesses[0].autoClear = false;
  73294. }
  73295. };
  73296. /** @hidden */
  73297. RenderTargetTexture.prototype._shouldRender = function () {
  73298. if (this._currentRefreshId === -1) { // At least render once
  73299. this._currentRefreshId = 1;
  73300. return true;
  73301. }
  73302. if (this.refreshRate === this._currentRefreshId) {
  73303. this._currentRefreshId = 1;
  73304. return true;
  73305. }
  73306. this._currentRefreshId++;
  73307. return false;
  73308. };
  73309. /**
  73310. * Gets the actual render size of the texture.
  73311. * @returns the width of the render size
  73312. */
  73313. RenderTargetTexture.prototype.getRenderSize = function () {
  73314. return this.getRenderWidth();
  73315. };
  73316. /**
  73317. * Gets the actual render width of the texture.
  73318. * @returns the width of the render size
  73319. */
  73320. RenderTargetTexture.prototype.getRenderWidth = function () {
  73321. if (this._size.width) {
  73322. return this._size.width;
  73323. }
  73324. return this._size;
  73325. };
  73326. /**
  73327. * Gets the actual render height of the texture.
  73328. * @returns the height of the render size
  73329. */
  73330. RenderTargetTexture.prototype.getRenderHeight = function () {
  73331. if (this._size.width) {
  73332. return this._size.height;
  73333. }
  73334. return this._size;
  73335. };
  73336. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  73337. /**
  73338. * Get if the texture can be rescaled or not.
  73339. */
  73340. get: function () {
  73341. return true;
  73342. },
  73343. enumerable: true,
  73344. configurable: true
  73345. });
  73346. /**
  73347. * Resize the texture using a ratio.
  73348. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  73349. */
  73350. RenderTargetTexture.prototype.scale = function (ratio) {
  73351. var newSize = this.getRenderSize() * ratio;
  73352. this.resize(newSize);
  73353. };
  73354. /**
  73355. * Get the texture reflection matrix used to rotate/transform the reflection.
  73356. * @returns the reflection matrix
  73357. */
  73358. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  73359. if (this.isCube) {
  73360. return this._textureMatrix;
  73361. }
  73362. return _super.prototype.getReflectionTextureMatrix.call(this);
  73363. };
  73364. /**
  73365. * Resize the texture to a new desired size.
  73366. * Be carrefull as it will recreate all the data in the new texture.
  73367. * @param size Define the new size. It can be:
  73368. * - a number for squared texture,
  73369. * - an object containing { width: number, height: number }
  73370. * - or an object containing a ratio { ratio: number }
  73371. */
  73372. RenderTargetTexture.prototype.resize = function (size) {
  73373. this.releaseInternalTexture();
  73374. var scene = this.getScene();
  73375. if (!scene) {
  73376. return;
  73377. }
  73378. this._processSizeParameter(size);
  73379. if (this.isCube) {
  73380. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  73381. }
  73382. else {
  73383. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  73384. }
  73385. };
  73386. /**
  73387. * Renders all the objects from the render list into the texture.
  73388. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  73389. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  73390. */
  73391. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  73392. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  73393. if (dumpForDebug === void 0) { dumpForDebug = false; }
  73394. var scene = this.getScene();
  73395. if (!scene) {
  73396. return;
  73397. }
  73398. var engine = scene.getEngine();
  73399. if (this.useCameraPostProcesses !== undefined) {
  73400. useCameraPostProcess = this.useCameraPostProcesses;
  73401. }
  73402. if (this._waitingRenderList) {
  73403. this.renderList = [];
  73404. for (var index = 0; index < this._waitingRenderList.length; index++) {
  73405. var id = this._waitingRenderList[index];
  73406. var mesh_1 = scene.getMeshByID(id);
  73407. if (mesh_1) {
  73408. this.renderList.push(mesh_1);
  73409. }
  73410. }
  73411. delete this._waitingRenderList;
  73412. }
  73413. // Is predicate defined?
  73414. if (this.renderListPredicate) {
  73415. if (this.renderList) {
  73416. this.renderList.length = 0; // Clear previous renderList
  73417. }
  73418. else {
  73419. this.renderList = [];
  73420. }
  73421. var scene = this.getScene();
  73422. if (!scene) {
  73423. return;
  73424. }
  73425. var sceneMeshes = scene.meshes;
  73426. for (var index = 0; index < sceneMeshes.length; index++) {
  73427. var mesh = sceneMeshes[index];
  73428. if (this.renderListPredicate(mesh)) {
  73429. this.renderList.push(mesh);
  73430. }
  73431. }
  73432. }
  73433. this.onBeforeBindObservable.notifyObservers(this);
  73434. // Set custom projection.
  73435. // Needs to be before binding to prevent changing the aspect ratio.
  73436. var camera;
  73437. if (this.activeCamera) {
  73438. camera = this.activeCamera;
  73439. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  73440. if (this.activeCamera !== scene.activeCamera) {
  73441. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  73442. }
  73443. }
  73444. else {
  73445. camera = scene.activeCamera;
  73446. if (camera) {
  73447. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  73448. }
  73449. }
  73450. // Prepare renderingManager
  73451. this._renderingManager.reset();
  73452. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  73453. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  73454. var sceneRenderId = scene.getRenderId();
  73455. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  73456. var mesh = currentRenderList[meshIndex];
  73457. if (mesh) {
  73458. if (!mesh.isReady(this.refreshRate === 0)) {
  73459. this.resetRefreshCounter();
  73460. continue;
  73461. }
  73462. mesh._preActivateForIntermediateRendering(sceneRenderId);
  73463. var isMasked = void 0;
  73464. if (!this.renderList && camera) {
  73465. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  73466. }
  73467. else {
  73468. isMasked = false;
  73469. }
  73470. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  73471. mesh._activate(sceneRenderId);
  73472. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  73473. var subMesh = mesh.subMeshes[subIndex];
  73474. scene._activeIndices.addCount(subMesh.indexCount, false);
  73475. this._renderingManager.dispatch(subMesh, mesh);
  73476. }
  73477. }
  73478. }
  73479. }
  73480. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  73481. var particleSystem = scene.particleSystems[particleIndex];
  73482. var emitter = particleSystem.emitter;
  73483. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  73484. continue;
  73485. }
  73486. if (currentRenderList.indexOf(emitter) >= 0) {
  73487. this._renderingManager.dispatchParticles(particleSystem);
  73488. }
  73489. }
  73490. if (this.isCube) {
  73491. for (var face = 0; face < 6; face++) {
  73492. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  73493. scene.incrementRenderId();
  73494. scene.resetCachedMaterial();
  73495. }
  73496. }
  73497. else {
  73498. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  73499. }
  73500. this.onAfterUnbindObservable.notifyObservers(this);
  73501. if (scene.activeCamera) {
  73502. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  73503. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  73504. }
  73505. engine.setViewport(scene.activeCamera.viewport);
  73506. }
  73507. scene.resetCachedMaterial();
  73508. };
  73509. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  73510. var minimum = 128;
  73511. var x = renderDimension * scale;
  73512. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  73513. // Ensure we don't exceed the render dimension (while staying POT)
  73514. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  73515. };
  73516. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  73517. var _this = this;
  73518. if (!this._texture) {
  73519. return;
  73520. }
  73521. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  73522. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  73523. });
  73524. };
  73525. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  73526. var scene = this.getScene();
  73527. if (!scene) {
  73528. return;
  73529. }
  73530. var engine = scene.getEngine();
  73531. if (!this._texture) {
  73532. return;
  73533. }
  73534. // Bind
  73535. if (this._postProcessManager) {
  73536. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  73537. }
  73538. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  73539. if (this._texture) {
  73540. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  73541. }
  73542. }
  73543. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  73544. // Clear
  73545. if (this.onClearObservable.hasObservers()) {
  73546. this.onClearObservable.notifyObservers(engine);
  73547. }
  73548. else {
  73549. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  73550. }
  73551. if (!this._doNotChangeAspectRatio) {
  73552. scene.updateTransformMatrix(true);
  73553. }
  73554. // Render
  73555. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  73556. if (this._postProcessManager) {
  73557. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  73558. }
  73559. else if (useCameraPostProcess) {
  73560. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  73561. }
  73562. if (!this._doNotChangeAspectRatio) {
  73563. scene.updateTransformMatrix(true);
  73564. }
  73565. // Dump ?
  73566. if (dumpForDebug) {
  73567. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  73568. }
  73569. // Unbind
  73570. if (!this.isCube || faceIndex === 5) {
  73571. if (this.isCube) {
  73572. if (faceIndex === 5) {
  73573. engine.generateMipMapsForCubemap(this._texture);
  73574. }
  73575. }
  73576. this.unbindFrameBuffer(engine, faceIndex);
  73577. }
  73578. else {
  73579. this.onAfterRenderObservable.notifyObservers(faceIndex);
  73580. }
  73581. };
  73582. /**
  73583. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  73584. * This allowed control for front to back rendering or reversly depending of the special needs.
  73585. *
  73586. * @param renderingGroupId The rendering group id corresponding to its index
  73587. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  73588. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  73589. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  73590. */
  73591. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  73592. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  73593. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  73594. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  73595. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  73596. };
  73597. /**
  73598. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73599. *
  73600. * @param renderingGroupId The rendering group id corresponding to its index
  73601. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73602. */
  73603. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73604. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73605. this._renderingManager._useSceneAutoClearSetup = false;
  73606. };
  73607. /**
  73608. * Clones the texture.
  73609. * @returns the cloned texture
  73610. */
  73611. RenderTargetTexture.prototype.clone = function () {
  73612. var textureSize = this.getSize();
  73613. 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);
  73614. // Base texture
  73615. newTexture.hasAlpha = this.hasAlpha;
  73616. newTexture.level = this.level;
  73617. // RenderTarget Texture
  73618. newTexture.coordinatesMode = this.coordinatesMode;
  73619. if (this.renderList) {
  73620. newTexture.renderList = this.renderList.slice(0);
  73621. }
  73622. return newTexture;
  73623. };
  73624. /**
  73625. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  73626. * @returns The JSON representation of the texture
  73627. */
  73628. RenderTargetTexture.prototype.serialize = function () {
  73629. if (!this.name) {
  73630. return null;
  73631. }
  73632. var serializationObject = _super.prototype.serialize.call(this);
  73633. serializationObject.renderTargetSize = this.getRenderSize();
  73634. serializationObject.renderList = [];
  73635. if (this.renderList) {
  73636. for (var index = 0; index < this.renderList.length; index++) {
  73637. serializationObject.renderList.push(this.renderList[index].id);
  73638. }
  73639. }
  73640. return serializationObject;
  73641. };
  73642. /**
  73643. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  73644. */
  73645. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  73646. var objBuffer = this.getInternalTexture();
  73647. var scene = this.getScene();
  73648. if (objBuffer && scene) {
  73649. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  73650. }
  73651. };
  73652. /**
  73653. * Dispose the texture and release its associated resources.
  73654. */
  73655. RenderTargetTexture.prototype.dispose = function () {
  73656. if (this._postProcessManager) {
  73657. this._postProcessManager.dispose();
  73658. this._postProcessManager = null;
  73659. }
  73660. this.clearPostProcesses(true);
  73661. if (this._resizeObserver) {
  73662. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  73663. this._resizeObserver = null;
  73664. }
  73665. this.renderList = null;
  73666. // Remove from custom render targets
  73667. var scene = this.getScene();
  73668. if (!scene) {
  73669. return;
  73670. }
  73671. var index = scene.customRenderTargets.indexOf(this);
  73672. if (index >= 0) {
  73673. scene.customRenderTargets.splice(index, 1);
  73674. }
  73675. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  73676. var camera = _a[_i];
  73677. index = camera.customRenderTargets.indexOf(this);
  73678. if (index >= 0) {
  73679. camera.customRenderTargets.splice(index, 1);
  73680. }
  73681. }
  73682. _super.prototype.dispose.call(this);
  73683. };
  73684. /** @hidden */
  73685. RenderTargetTexture.prototype._rebuild = function () {
  73686. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  73687. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  73688. }
  73689. if (this._postProcessManager) {
  73690. this._postProcessManager._rebuild();
  73691. }
  73692. };
  73693. /**
  73694. * Clear the info related to rendering groups preventing retention point in material dispose.
  73695. */
  73696. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  73697. if (this._renderingManager) {
  73698. this._renderingManager.freeRenderingGroups();
  73699. }
  73700. };
  73701. /**
  73702. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  73703. */
  73704. RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
  73705. /**
  73706. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  73707. */
  73708. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  73709. /**
  73710. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  73711. * the central point of your effect and can save a lot of performances.
  73712. */
  73713. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  73714. return RenderTargetTexture;
  73715. }(BABYLON.Texture));
  73716. BABYLON.RenderTargetTexture = RenderTargetTexture;
  73717. })(BABYLON || (BABYLON = {}));
  73718. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  73719. var BABYLON;
  73720. (function (BABYLON) {
  73721. /**
  73722. * A multi render target, like a render target provides the ability to render to a texture.
  73723. * Unlike the render target, it can render to several draw buffers in one draw.
  73724. * This is specially interesting in deferred rendering or for any effects requiring more than
  73725. * just one color from a single pass.
  73726. */
  73727. var MultiRenderTarget = /** @class */ (function (_super) {
  73728. __extends(MultiRenderTarget, _super);
  73729. /**
  73730. * Instantiate a new multi render target texture.
  73731. * A multi render target, like a render target provides the ability to render to a texture.
  73732. * Unlike the render target, it can render to several draw buffers in one draw.
  73733. * This is specially interesting in deferred rendering or for any effects requiring more than
  73734. * just one color from a single pass.
  73735. * @param name Define the name of the texture
  73736. * @param size Define the size of the buffers to render to
  73737. * @param count Define the number of target we are rendering into
  73738. * @param scene Define the scene the texture belongs to
  73739. * @param options Define the options used to create the multi render target
  73740. */
  73741. function MultiRenderTarget(name, size, count, scene, options) {
  73742. var _this = this;
  73743. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  73744. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  73745. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  73746. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  73747. _this._engine = scene.getEngine();
  73748. if (!_this.isSupported) {
  73749. _this.dispose();
  73750. return;
  73751. }
  73752. var types = [];
  73753. var samplingModes = [];
  73754. for (var i = 0; i < count; i++) {
  73755. if (options && options.types && options.types[i] !== undefined) {
  73756. types.push(options.types[i]);
  73757. }
  73758. else {
  73759. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73760. }
  73761. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  73762. samplingModes.push(options.samplingModes[i]);
  73763. }
  73764. else {
  73765. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73766. }
  73767. }
  73768. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  73769. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  73770. _this._size = size;
  73771. _this._multiRenderTargetOptions = {
  73772. samplingModes: samplingModes,
  73773. generateMipMaps: generateMipMaps,
  73774. generateDepthBuffer: generateDepthBuffer,
  73775. generateStencilBuffer: generateStencilBuffer,
  73776. generateDepthTexture: generateDepthTexture,
  73777. types: types,
  73778. textureCount: count
  73779. };
  73780. _this._createInternalTextures();
  73781. _this._createTextures();
  73782. return _this;
  73783. }
  73784. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  73785. /**
  73786. * Get if draw buffers are currently supported by the used hardware and browser.
  73787. */
  73788. get: function () {
  73789. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  73790. },
  73791. enumerable: true,
  73792. configurable: true
  73793. });
  73794. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  73795. /**
  73796. * Get the list of textures generated by the multi render target.
  73797. */
  73798. get: function () {
  73799. return this._textures;
  73800. },
  73801. enumerable: true,
  73802. configurable: true
  73803. });
  73804. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  73805. /**
  73806. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  73807. */
  73808. get: function () {
  73809. return this._textures[this._textures.length - 1];
  73810. },
  73811. enumerable: true,
  73812. configurable: true
  73813. });
  73814. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  73815. /**
  73816. * Set the wrapping mode on U of all the textures we are rendering to.
  73817. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  73818. */
  73819. set: function (wrap) {
  73820. if (this._textures) {
  73821. for (var i = 0; i < this._textures.length; i++) {
  73822. this._textures[i].wrapU = wrap;
  73823. }
  73824. }
  73825. },
  73826. enumerable: true,
  73827. configurable: true
  73828. });
  73829. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  73830. /**
  73831. * Set the wrapping mode on V of all the textures we are rendering to.
  73832. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  73833. */
  73834. set: function (wrap) {
  73835. if (this._textures) {
  73836. for (var i = 0; i < this._textures.length; i++) {
  73837. this._textures[i].wrapV = wrap;
  73838. }
  73839. }
  73840. },
  73841. enumerable: true,
  73842. configurable: true
  73843. });
  73844. /** @hidden */
  73845. MultiRenderTarget.prototype._rebuild = function () {
  73846. this.releaseInternalTextures();
  73847. this._createInternalTextures();
  73848. for (var i = 0; i < this._internalTextures.length; i++) {
  73849. var texture = this._textures[i];
  73850. texture._texture = this._internalTextures[i];
  73851. }
  73852. // Keeps references to frame buffer and stencil/depth buffer
  73853. this._texture = this._internalTextures[0];
  73854. };
  73855. MultiRenderTarget.prototype._createInternalTextures = function () {
  73856. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  73857. };
  73858. MultiRenderTarget.prototype._createTextures = function () {
  73859. this._textures = [];
  73860. for (var i = 0; i < this._internalTextures.length; i++) {
  73861. var texture = new BABYLON.Texture(null, this.getScene());
  73862. texture._texture = this._internalTextures[i];
  73863. this._textures.push(texture);
  73864. }
  73865. // Keeps references to frame buffer and stencil/depth buffer
  73866. this._texture = this._internalTextures[0];
  73867. };
  73868. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  73869. /**
  73870. * Define the number of samples used if MSAA is enabled.
  73871. */
  73872. get: function () {
  73873. return this._samples;
  73874. },
  73875. set: function (value) {
  73876. if (this._samples === value) {
  73877. return;
  73878. }
  73879. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  73880. },
  73881. enumerable: true,
  73882. configurable: true
  73883. });
  73884. /**
  73885. * Resize all the textures in the multi render target.
  73886. * Be carrefull as it will recreate all the data in the new texture.
  73887. * @param size Define the new size
  73888. */
  73889. MultiRenderTarget.prototype.resize = function (size) {
  73890. this.releaseInternalTextures();
  73891. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  73892. this._createInternalTextures();
  73893. };
  73894. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  73895. var _this = this;
  73896. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  73897. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  73898. });
  73899. };
  73900. /**
  73901. * Dispose the render targets and their associated resources
  73902. */
  73903. MultiRenderTarget.prototype.dispose = function () {
  73904. this.releaseInternalTextures();
  73905. _super.prototype.dispose.call(this);
  73906. };
  73907. /**
  73908. * Release all the underlying texture used as draw buffers.
  73909. */
  73910. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  73911. if (!this._internalTextures) {
  73912. return;
  73913. }
  73914. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  73915. if (this._internalTextures[i] !== undefined) {
  73916. this._internalTextures[i].dispose();
  73917. this._internalTextures.splice(i, 1);
  73918. }
  73919. }
  73920. };
  73921. return MultiRenderTarget;
  73922. }(BABYLON.RenderTargetTexture));
  73923. BABYLON.MultiRenderTarget = MultiRenderTarget;
  73924. })(BABYLON || (BABYLON = {}));
  73925. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  73926. var BABYLON;
  73927. (function (BABYLON) {
  73928. /**
  73929. * Mirror texture can be used to simulate the view from a mirror in a scene.
  73930. * It will dynamically be rendered every frame to adapt to the camera point of view.
  73931. * You can then easily use it as a reflectionTexture on a flat surface.
  73932. * In case the surface is not a plane, please consider relying on reflection probes.
  73933. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  73934. */
  73935. var MirrorTexture = /** @class */ (function (_super) {
  73936. __extends(MirrorTexture, _super);
  73937. /**
  73938. * Instantiates a Mirror Texture.
  73939. * Mirror texture can be used to simulate the view from a mirror in a scene.
  73940. * It will dynamically be rendered every frame to adapt to the camera point of view.
  73941. * You can then easily use it as a reflectionTexture on a flat surface.
  73942. * In case the surface is not a plane, please consider relying on reflection probes.
  73943. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  73944. * @param name
  73945. * @param size
  73946. * @param scene
  73947. * @param generateMipMaps
  73948. * @param type
  73949. * @param samplingMode
  73950. * @param generateDepthBuffer
  73951. */
  73952. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  73953. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73954. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73955. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  73956. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  73957. _this.scene = scene;
  73958. /**
  73959. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  73960. * 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.
  73961. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  73962. */
  73963. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  73964. _this._transformMatrix = BABYLON.Matrix.Zero();
  73965. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  73966. _this._adaptiveBlurKernel = 0;
  73967. _this._blurKernelX = 0;
  73968. _this._blurKernelY = 0;
  73969. _this._blurRatio = 1.0;
  73970. _this.ignoreCameraViewport = true;
  73971. _this._updateGammaSpace();
  73972. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  73973. _this._updateGammaSpace;
  73974. });
  73975. _this.onBeforeRenderObservable.add(function () {
  73976. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  73977. _this._savedViewMatrix = scene.getViewMatrix();
  73978. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  73979. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  73980. scene.clipPlane = _this.mirrorPlane;
  73981. scene.getEngine().cullBackFaces = false;
  73982. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  73983. });
  73984. _this.onAfterRenderObservable.add(function () {
  73985. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  73986. scene.getEngine().cullBackFaces = true;
  73987. scene._mirroredCameraPosition = null;
  73988. delete scene.clipPlane;
  73989. });
  73990. return _this;
  73991. }
  73992. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  73993. get: function () {
  73994. return this._blurRatio;
  73995. },
  73996. /**
  73997. * Define the blur ratio used to blur the reflection if needed.
  73998. */
  73999. set: function (value) {
  74000. if (this._blurRatio === value) {
  74001. return;
  74002. }
  74003. this._blurRatio = value;
  74004. this._preparePostProcesses();
  74005. },
  74006. enumerable: true,
  74007. configurable: true
  74008. });
  74009. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  74010. /**
  74011. * Define the adaptive blur kernel used to blur the reflection if needed.
  74012. * This will autocompute the closest best match for the `blurKernel`
  74013. */
  74014. set: function (value) {
  74015. this._adaptiveBlurKernel = value;
  74016. this._autoComputeBlurKernel();
  74017. },
  74018. enumerable: true,
  74019. configurable: true
  74020. });
  74021. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  74022. /**
  74023. * Define the blur kernel used to blur the reflection if needed.
  74024. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74025. */
  74026. set: function (value) {
  74027. this.blurKernelX = value;
  74028. this.blurKernelY = value;
  74029. },
  74030. enumerable: true,
  74031. configurable: true
  74032. });
  74033. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  74034. get: function () {
  74035. return this._blurKernelX;
  74036. },
  74037. /**
  74038. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  74039. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74040. */
  74041. set: function (value) {
  74042. if (this._blurKernelX === value) {
  74043. return;
  74044. }
  74045. this._blurKernelX = value;
  74046. this._preparePostProcesses();
  74047. },
  74048. enumerable: true,
  74049. configurable: true
  74050. });
  74051. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  74052. get: function () {
  74053. return this._blurKernelY;
  74054. },
  74055. /**
  74056. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  74057. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74058. */
  74059. set: function (value) {
  74060. if (this._blurKernelY === value) {
  74061. return;
  74062. }
  74063. this._blurKernelY = value;
  74064. this._preparePostProcesses();
  74065. },
  74066. enumerable: true,
  74067. configurable: true
  74068. });
  74069. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  74070. var engine = this.getScene().getEngine();
  74071. var dw = this.getRenderWidth() / engine.getRenderWidth();
  74072. var dh = this.getRenderHeight() / engine.getRenderHeight();
  74073. this.blurKernelX = this._adaptiveBlurKernel * dw;
  74074. this.blurKernelY = this._adaptiveBlurKernel * dh;
  74075. };
  74076. MirrorTexture.prototype._onRatioRescale = function () {
  74077. if (this._sizeRatio) {
  74078. this.resize(this._initialSizeParameter);
  74079. if (!this._adaptiveBlurKernel) {
  74080. this._preparePostProcesses();
  74081. }
  74082. }
  74083. if (this._adaptiveBlurKernel) {
  74084. this._autoComputeBlurKernel();
  74085. }
  74086. };
  74087. MirrorTexture.prototype._updateGammaSpace = function () {
  74088. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  74089. };
  74090. MirrorTexture.prototype._preparePostProcesses = function () {
  74091. this.clearPostProcesses(true);
  74092. if (this._blurKernelX && this._blurKernelY) {
  74093. var engine = this.getScene().getEngine();
  74094. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74095. 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);
  74096. this._blurX.autoClear = false;
  74097. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  74098. this._blurX.inputTexture = this._texture;
  74099. }
  74100. else {
  74101. this._blurX.alwaysForcePOT = true;
  74102. }
  74103. 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);
  74104. this._blurY.autoClear = false;
  74105. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  74106. this.addPostProcess(this._blurX);
  74107. this.addPostProcess(this._blurY);
  74108. }
  74109. else {
  74110. if (this._blurY) {
  74111. this.removePostProcess(this._blurY);
  74112. this._blurY.dispose();
  74113. this._blurY = null;
  74114. }
  74115. if (this._blurX) {
  74116. this.removePostProcess(this._blurX);
  74117. this._blurX.dispose();
  74118. this._blurX = null;
  74119. }
  74120. }
  74121. };
  74122. /**
  74123. * Clone the mirror texture.
  74124. * @returns the cloned texture
  74125. */
  74126. MirrorTexture.prototype.clone = function () {
  74127. var scene = this.getScene();
  74128. if (!scene) {
  74129. return this;
  74130. }
  74131. var textureSize = this.getSize();
  74132. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  74133. // Base texture
  74134. newTexture.hasAlpha = this.hasAlpha;
  74135. newTexture.level = this.level;
  74136. // Mirror Texture
  74137. newTexture.mirrorPlane = this.mirrorPlane.clone();
  74138. if (this.renderList) {
  74139. newTexture.renderList = this.renderList.slice(0);
  74140. }
  74141. return newTexture;
  74142. };
  74143. /**
  74144. * Serialize the texture to a JSON representation you could use in Parse later on
  74145. * @returns the serialized JSON representation
  74146. */
  74147. MirrorTexture.prototype.serialize = function () {
  74148. if (!this.name) {
  74149. return null;
  74150. }
  74151. var serializationObject = _super.prototype.serialize.call(this);
  74152. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  74153. return serializationObject;
  74154. };
  74155. /**
  74156. * Dispose the texture and release its associated resources.
  74157. */
  74158. MirrorTexture.prototype.dispose = function () {
  74159. _super.prototype.dispose.call(this);
  74160. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  74161. };
  74162. return MirrorTexture;
  74163. }(BABYLON.RenderTargetTexture));
  74164. BABYLON.MirrorTexture = MirrorTexture;
  74165. })(BABYLON || (BABYLON = {}));
  74166. //# sourceMappingURL=babylon.mirrorTexture.js.map
  74167. var BABYLON;
  74168. (function (BABYLON) {
  74169. /**
  74170. * Creates a refraction texture used by refraction channel of the standard material.
  74171. * It is like a mirror but to see through a material.
  74172. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74173. */
  74174. var RefractionTexture = /** @class */ (function (_super) {
  74175. __extends(RefractionTexture, _super);
  74176. /**
  74177. * Creates a refraction texture used by refraction channel of the standard material.
  74178. * It is like a mirror but to see through a material.
  74179. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74180. * @param name Define the texture name
  74181. * @param size Define the size of the underlying texture
  74182. * @param scene Define the scene the refraction belongs to
  74183. * @param generateMipMaps Define if we need to generate mips level for the refraction
  74184. */
  74185. function RefractionTexture(name, size, scene, generateMipMaps) {
  74186. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  74187. /**
  74188. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  74189. * 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.
  74190. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74191. */
  74192. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  74193. /**
  74194. * Define how deep under the surface we should see.
  74195. */
  74196. _this.depth = 2.0;
  74197. _this.onBeforeRenderObservable.add(function () {
  74198. scene.clipPlane = _this.refractionPlane;
  74199. });
  74200. _this.onAfterRenderObservable.add(function () {
  74201. delete scene.clipPlane;
  74202. });
  74203. return _this;
  74204. }
  74205. /**
  74206. * Clone the refraction texture.
  74207. * @returns the cloned texture
  74208. */
  74209. RefractionTexture.prototype.clone = function () {
  74210. var scene = this.getScene();
  74211. if (!scene) {
  74212. return this;
  74213. }
  74214. var textureSize = this.getSize();
  74215. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  74216. // Base texture
  74217. newTexture.hasAlpha = this.hasAlpha;
  74218. newTexture.level = this.level;
  74219. // Refraction Texture
  74220. newTexture.refractionPlane = this.refractionPlane.clone();
  74221. if (this.renderList) {
  74222. newTexture.renderList = this.renderList.slice(0);
  74223. }
  74224. newTexture.depth = this.depth;
  74225. return newTexture;
  74226. };
  74227. /**
  74228. * Serialize the texture to a JSON representation you could use in Parse later on
  74229. * @returns the serialized JSON representation
  74230. */
  74231. RefractionTexture.prototype.serialize = function () {
  74232. if (!this.name) {
  74233. return null;
  74234. }
  74235. var serializationObject = _super.prototype.serialize.call(this);
  74236. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  74237. serializationObject.depth = this.depth;
  74238. return serializationObject;
  74239. };
  74240. return RefractionTexture;
  74241. }(BABYLON.RenderTargetTexture));
  74242. BABYLON.RefractionTexture = RefractionTexture;
  74243. })(BABYLON || (BABYLON = {}));
  74244. //# sourceMappingURL=babylon.refractionTexture.js.map
  74245. var BABYLON;
  74246. (function (BABYLON) {
  74247. /**
  74248. * A class extending Texture allowing drawing on a texture
  74249. * @see http://doc.babylonjs.com/how_to/dynamictexture
  74250. */
  74251. var DynamicTexture = /** @class */ (function (_super) {
  74252. __extends(DynamicTexture, _super);
  74253. /**
  74254. * Creates a DynamicTexture
  74255. * @param name defines the name of the texture
  74256. * @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
  74257. * @param scene defines the scene where you want the texture
  74258. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  74259. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  74260. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  74261. */
  74262. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  74263. if (scene === void 0) { scene = null; }
  74264. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74265. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  74266. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  74267. _this.name = name;
  74268. _this._engine = _this.getScene().getEngine();
  74269. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74270. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74271. _this._generateMipMaps = generateMipMaps;
  74272. if (options.getContext) {
  74273. _this._canvas = options;
  74274. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  74275. }
  74276. else {
  74277. _this._canvas = document.createElement("canvas");
  74278. if (options.width || options.width === 0) {
  74279. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  74280. }
  74281. else {
  74282. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  74283. }
  74284. }
  74285. var textureSize = _this.getSize();
  74286. _this._canvas.width = textureSize.width;
  74287. _this._canvas.height = textureSize.height;
  74288. _this._context = _this._canvas.getContext("2d");
  74289. return _this;
  74290. }
  74291. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  74292. /**
  74293. * Gets the current state of canRescale
  74294. */
  74295. get: function () {
  74296. return true;
  74297. },
  74298. enumerable: true,
  74299. configurable: true
  74300. });
  74301. DynamicTexture.prototype._recreate = function (textureSize) {
  74302. this._canvas.width = textureSize.width;
  74303. this._canvas.height = textureSize.height;
  74304. this.releaseInternalTexture();
  74305. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  74306. };
  74307. /**
  74308. * Scales the texture
  74309. * @param ratio the scale factor to apply to both width and height
  74310. */
  74311. DynamicTexture.prototype.scale = function (ratio) {
  74312. var textureSize = this.getSize();
  74313. textureSize.width *= ratio;
  74314. textureSize.height *= ratio;
  74315. this._recreate(textureSize);
  74316. };
  74317. /**
  74318. * Resizes the texture
  74319. * @param width the new width
  74320. * @param height the new height
  74321. */
  74322. DynamicTexture.prototype.scaleTo = function (width, height) {
  74323. var textureSize = this.getSize();
  74324. textureSize.width = width;
  74325. textureSize.height = height;
  74326. this._recreate(textureSize);
  74327. };
  74328. /**
  74329. * Gets the context of the canvas used by the texture
  74330. * @returns the canvas context of the dynamic texture
  74331. */
  74332. DynamicTexture.prototype.getContext = function () {
  74333. return this._context;
  74334. };
  74335. /**
  74336. * Clears the texture
  74337. */
  74338. DynamicTexture.prototype.clear = function () {
  74339. var size = this.getSize();
  74340. this._context.fillRect(0, 0, size.width, size.height);
  74341. };
  74342. /**
  74343. * Updates the texture
  74344. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  74345. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  74346. */
  74347. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  74348. if (premulAlpha === void 0) { premulAlpha = false; }
  74349. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  74350. };
  74351. /**
  74352. * Draws text onto the texture
  74353. * @param text defines the text to be drawn
  74354. * @param x defines the placement of the text from the left
  74355. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  74356. * @param font defines the font to be used with font-style, font-size, font-name
  74357. * @param color defines the color used for the text
  74358. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  74359. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  74360. * @param update defines whether texture is immediately update (default is true)
  74361. */
  74362. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  74363. if (update === void 0) { update = true; }
  74364. var size = this.getSize();
  74365. if (clearColor) {
  74366. this._context.fillStyle = clearColor;
  74367. this._context.fillRect(0, 0, size.width, size.height);
  74368. }
  74369. this._context.font = font;
  74370. if (x === null || x === undefined) {
  74371. var textSize = this._context.measureText(text);
  74372. x = (size.width - textSize.width) / 2;
  74373. }
  74374. if (y === null || y === undefined) {
  74375. var fontSize = parseInt((font.replace(/\D/g, '')));
  74376. y = (size.height / 2) + (fontSize / 3.65);
  74377. }
  74378. this._context.fillStyle = color;
  74379. this._context.fillText(text, x, y);
  74380. if (update) {
  74381. this.update(invertY);
  74382. }
  74383. };
  74384. /**
  74385. * Clones the texture
  74386. * @returns the clone of the texture.
  74387. */
  74388. DynamicTexture.prototype.clone = function () {
  74389. var scene = this.getScene();
  74390. if (!scene) {
  74391. return this;
  74392. }
  74393. var textureSize = this.getSize();
  74394. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  74395. // Base texture
  74396. newTexture.hasAlpha = this.hasAlpha;
  74397. newTexture.level = this.level;
  74398. // Dynamic Texture
  74399. newTexture.wrapU = this.wrapU;
  74400. newTexture.wrapV = this.wrapV;
  74401. return newTexture;
  74402. };
  74403. /**
  74404. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  74405. * @returns a serialized dynamic texture object
  74406. */
  74407. DynamicTexture.prototype.serialize = function () {
  74408. var scene = this.getScene();
  74409. if (scene && !scene.isReady()) {
  74410. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  74411. }
  74412. var serializationObject = _super.prototype.serialize.call(this);
  74413. serializationObject.base64String = this._canvas.toDataURL();
  74414. serializationObject.invertY = this._invertY;
  74415. serializationObject.samplingMode = this.samplingMode;
  74416. return serializationObject;
  74417. };
  74418. /** @hidden */
  74419. DynamicTexture.prototype._rebuild = function () {
  74420. this.update();
  74421. };
  74422. return DynamicTexture;
  74423. }(BABYLON.Texture));
  74424. BABYLON.DynamicTexture = DynamicTexture;
  74425. })(BABYLON || (BABYLON = {}));
  74426. //# sourceMappingURL=babylon.dynamicTexture.js.map
  74427. var BABYLON;
  74428. (function (BABYLON) {
  74429. /**
  74430. * If you want to display a video in your scene, this is the special texture for that.
  74431. * This special texture works similar to other textures, with the exception of a few parameters.
  74432. * @see https://doc.babylonjs.com/how_to/video_texture
  74433. */
  74434. var VideoTexture = /** @class */ (function (_super) {
  74435. __extends(VideoTexture, _super);
  74436. /**
  74437. * Creates a video texture.
  74438. * If you want to display a video in your scene, this is the special texture for that.
  74439. * This special texture works similar to other textures, with the exception of a few parameters.
  74440. * @see https://doc.babylonjs.com/how_to/video_texture
  74441. * @param name optional name, will detect from video source, if not defined
  74442. * @param src can be used to provide an url, array of urls or an already setup HTML video element.
  74443. * @param scene is obviously the current scene.
  74444. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  74445. * @param invertY is false by default but can be used to invert video on Y axis
  74446. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  74447. * @param settings allows finer control over video usage
  74448. */
  74449. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  74450. if (generateMipMaps === void 0) { generateMipMaps = false; }
  74451. if (invertY === void 0) { invertY = false; }
  74452. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74453. if (settings === void 0) { settings = {
  74454. autoPlay: true,
  74455. loop: true,
  74456. autoUpdateTexture: true,
  74457. }; }
  74458. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  74459. _this._onUserActionRequestedObservable = null;
  74460. _this._stillImageCaptured = false;
  74461. _this._poster = false;
  74462. _this._createInternalTexture = function () {
  74463. if (_this._texture != null) {
  74464. if (_this._poster) {
  74465. _this._texture.dispose();
  74466. _this._poster = false;
  74467. }
  74468. else {
  74469. return;
  74470. }
  74471. }
  74472. if (!_this._engine.needPOTTextures ||
  74473. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  74474. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74475. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74476. }
  74477. else {
  74478. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74479. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74480. _this._generateMipMaps = false;
  74481. }
  74482. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  74483. if (!_this.video.autoplay) {
  74484. var oldHandler_1 = _this.video.onplaying;
  74485. var error_1 = false;
  74486. _this.video.onplaying = function () {
  74487. _this.video.onplaying = oldHandler_1;
  74488. _this._texture.isReady = true;
  74489. _this._updateInternalTexture();
  74490. if (!error_1) {
  74491. _this.video.pause();
  74492. }
  74493. if (_this.onLoadObservable.hasObservers()) {
  74494. _this.onLoadObservable.notifyObservers(_this);
  74495. }
  74496. };
  74497. var playing = _this.video.play();
  74498. if (playing) {
  74499. playing.then(function () {
  74500. // Everything is good.
  74501. })
  74502. .catch(function () {
  74503. error_1 = true;
  74504. // On Chrome for instance, new policies might prevent playing without user interaction.
  74505. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  74506. _this._onUserActionRequestedObservable.notifyObservers(_this);
  74507. }
  74508. });
  74509. }
  74510. else {
  74511. _this.video.onplaying = oldHandler_1;
  74512. _this._texture.isReady = true;
  74513. _this._updateInternalTexture();
  74514. if (_this.onLoadObservable.hasObservers()) {
  74515. _this.onLoadObservable.notifyObservers(_this);
  74516. }
  74517. }
  74518. }
  74519. else {
  74520. _this._texture.isReady = true;
  74521. _this._updateInternalTexture();
  74522. if (_this.onLoadObservable.hasObservers()) {
  74523. _this.onLoadObservable.notifyObservers(_this);
  74524. }
  74525. }
  74526. };
  74527. _this.reset = function () {
  74528. if (_this._texture == null) {
  74529. return;
  74530. }
  74531. if (!_this._poster) {
  74532. _this._texture.dispose();
  74533. _this._texture = null;
  74534. }
  74535. };
  74536. _this._updateInternalTexture = function (e) {
  74537. if (_this._texture == null || !_this._texture.isReady) {
  74538. return;
  74539. }
  74540. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  74541. return;
  74542. }
  74543. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  74544. };
  74545. _this._engine = _this.getScene().getEngine();
  74546. _this._generateMipMaps = generateMipMaps;
  74547. _this._samplingMode = samplingMode;
  74548. _this.autoUpdateTexture = settings.autoUpdateTexture;
  74549. _this.name = name || _this._getName(src);
  74550. _this.video = _this._getVideo(src);
  74551. if (settings.poster) {
  74552. _this.video.poster = settings.poster;
  74553. }
  74554. if (settings.autoPlay !== undefined) {
  74555. _this.video.autoplay = settings.autoPlay;
  74556. }
  74557. if (settings.loop !== undefined) {
  74558. _this.video.loop = settings.loop;
  74559. }
  74560. _this.video.setAttribute("playsinline", "");
  74561. _this.video.addEventListener("canplay", _this._createInternalTexture);
  74562. _this.video.addEventListener("paused", _this._updateInternalTexture);
  74563. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  74564. _this.video.addEventListener("emptied", _this.reset);
  74565. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  74566. _this._createInternalTexture();
  74567. }
  74568. if (settings.poster) {
  74569. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  74570. _this._poster = true;
  74571. }
  74572. return _this;
  74573. }
  74574. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  74575. /**
  74576. * Event triggerd when a dom action is required by the user to play the video.
  74577. * This happens due to recent changes in browser policies preventing video to auto start.
  74578. */
  74579. get: function () {
  74580. if (!this._onUserActionRequestedObservable) {
  74581. this._onUserActionRequestedObservable = new BABYLON.Observable();
  74582. }
  74583. return this._onUserActionRequestedObservable;
  74584. },
  74585. enumerable: true,
  74586. configurable: true
  74587. });
  74588. VideoTexture.prototype._getName = function (src) {
  74589. if (src instanceof HTMLVideoElement) {
  74590. return src.currentSrc;
  74591. }
  74592. if (typeof src === "object") {
  74593. return src.toString();
  74594. }
  74595. return src;
  74596. };
  74597. VideoTexture.prototype._getVideo = function (src) {
  74598. if (src instanceof HTMLVideoElement) {
  74599. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  74600. return src;
  74601. }
  74602. var video = document.createElement("video");
  74603. if (typeof src === "string") {
  74604. BABYLON.Tools.SetCorsBehavior(src, video);
  74605. video.src = src;
  74606. }
  74607. else {
  74608. BABYLON.Tools.SetCorsBehavior(src[0], video);
  74609. src.forEach(function (url) {
  74610. var source = document.createElement("source");
  74611. source.src = url;
  74612. video.appendChild(source);
  74613. });
  74614. }
  74615. return video;
  74616. };
  74617. /**
  74618. * @hidden Internal method to initiate `update`.
  74619. */
  74620. VideoTexture.prototype._rebuild = function () {
  74621. this.update();
  74622. };
  74623. /**
  74624. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  74625. */
  74626. VideoTexture.prototype.update = function () {
  74627. if (!this.autoUpdateTexture) {
  74628. // Expecting user to call `updateTexture` manually
  74629. return;
  74630. }
  74631. this.updateTexture(true);
  74632. };
  74633. /**
  74634. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  74635. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  74636. */
  74637. VideoTexture.prototype.updateTexture = function (isVisible) {
  74638. if (!isVisible) {
  74639. return;
  74640. }
  74641. if (this.video.paused && this._stillImageCaptured) {
  74642. return;
  74643. }
  74644. this._stillImageCaptured = true;
  74645. this._updateInternalTexture();
  74646. };
  74647. /**
  74648. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  74649. * @param url New url.
  74650. */
  74651. VideoTexture.prototype.updateURL = function (url) {
  74652. this.video.src = url;
  74653. };
  74654. /**
  74655. * Dispose the texture and release its associated resources.
  74656. */
  74657. VideoTexture.prototype.dispose = function () {
  74658. _super.prototype.dispose.call(this);
  74659. if (this._onUserActionRequestedObservable) {
  74660. this._onUserActionRequestedObservable.clear();
  74661. this._onUserActionRequestedObservable = null;
  74662. }
  74663. this.video.removeEventListener("canplay", this._createInternalTexture);
  74664. this.video.removeEventListener("paused", this._updateInternalTexture);
  74665. this.video.removeEventListener("seeked", this._updateInternalTexture);
  74666. this.video.removeEventListener("emptied", this.reset);
  74667. this.video.pause();
  74668. };
  74669. /**
  74670. * Creates a video texture straight from your WebCam video feed.
  74671. * @param scene Define the scene the texture should be created in
  74672. * @param onReady Define a callback to triggered once the texture will be ready
  74673. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  74674. */
  74675. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  74676. var video = document.createElement("video");
  74677. video.setAttribute('autoplay', '');
  74678. video.setAttribute('muted', '');
  74679. video.setAttribute('playsinline', '');
  74680. var constraintsDeviceId;
  74681. if (constraints && constraints.deviceId) {
  74682. constraintsDeviceId = {
  74683. exact: constraints.deviceId,
  74684. };
  74685. }
  74686. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  74687. if (navigator.mediaDevices) {
  74688. navigator.mediaDevices.getUserMedia({ video: constraints })
  74689. .then(function (stream) {
  74690. if (video.mozSrcObject !== undefined) {
  74691. // hack for Firefox < 19
  74692. video.mozSrcObject = stream;
  74693. }
  74694. else {
  74695. video.srcObject = stream;
  74696. }
  74697. var onPlaying = function () {
  74698. if (onReady) {
  74699. onReady(new VideoTexture("video", video, scene, true, true));
  74700. }
  74701. video.removeEventListener("playing", onPlaying);
  74702. };
  74703. video.addEventListener("playing", onPlaying);
  74704. video.play();
  74705. })
  74706. .catch(function (err) {
  74707. BABYLON.Tools.Error(err.name);
  74708. });
  74709. }
  74710. else {
  74711. navigator.getUserMedia =
  74712. navigator.getUserMedia ||
  74713. navigator.webkitGetUserMedia ||
  74714. navigator.mozGetUserMedia ||
  74715. navigator.msGetUserMedia;
  74716. if (navigator.getUserMedia) {
  74717. navigator.getUserMedia({
  74718. video: {
  74719. deviceId: constraintsDeviceId,
  74720. width: {
  74721. min: (constraints && constraints.minWidth) || 256,
  74722. max: (constraints && constraints.maxWidth) || 640,
  74723. },
  74724. height: {
  74725. min: (constraints && constraints.minHeight) || 256,
  74726. max: (constraints && constraints.maxHeight) || 480,
  74727. },
  74728. },
  74729. }, function (stream) {
  74730. if (video.mozSrcObject !== undefined) {
  74731. // hack for Firefox < 19
  74732. video.mozSrcObject = stream;
  74733. }
  74734. else {
  74735. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  74736. }
  74737. video.play();
  74738. if (onReady) {
  74739. onReady(new VideoTexture("video", video, scene, true, true));
  74740. }
  74741. }, function (e) {
  74742. BABYLON.Tools.Error(e.name);
  74743. });
  74744. }
  74745. }
  74746. };
  74747. return VideoTexture;
  74748. }(BABYLON.Texture));
  74749. BABYLON.VideoTexture = VideoTexture;
  74750. })(BABYLON || (BABYLON = {}));
  74751. //# sourceMappingURL=babylon.videoTexture.js.map
  74752. var BABYLON;
  74753. (function (BABYLON) {
  74754. /**
  74755. * Raw texture can help creating a texture directly from an array of data.
  74756. * This can be super useful if you either get the data from an uncompressed source or
  74757. * if you wish to create your texture pixel by pixel.
  74758. */
  74759. var RawTexture = /** @class */ (function (_super) {
  74760. __extends(RawTexture, _super);
  74761. /**
  74762. * Instantiates a new RawTexture.
  74763. * Raw texture can help creating a texture directly from an array of data.
  74764. * This can be super useful if you either get the data from an uncompressed source or
  74765. * if you wish to create your texture pixel by pixel.
  74766. * @param data define the array of data to use to create the texture
  74767. * @param width define the width of the texture
  74768. * @param height define the height of the texture
  74769. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  74770. * @param scene define the scene the texture belongs to
  74771. * @param generateMipMaps define whether mip maps should be generated or not
  74772. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74773. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74774. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74775. */
  74776. function RawTexture(data, width, height,
  74777. /**
  74778. * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  74779. */
  74780. format, scene, generateMipMaps, invertY, samplingMode, type) {
  74781. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74782. if (invertY === void 0) { invertY = false; }
  74783. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74784. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74785. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  74786. _this.format = format;
  74787. _this._engine = scene.getEngine();
  74788. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  74789. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74790. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74791. return _this;
  74792. }
  74793. /**
  74794. * Updates the texture underlying data.
  74795. * @param data Define the new data of the texture
  74796. */
  74797. RawTexture.prototype.update = function (data) {
  74798. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  74799. };
  74800. /**
  74801. * Creates a luminance texture from some data.
  74802. * @param data Define the texture data
  74803. * @param width Define the width of the texture
  74804. * @param height Define the height of the texture
  74805. * @param scene Define the scene the texture belongs to
  74806. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74807. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74808. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74809. * @returns the luminance texture
  74810. */
  74811. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  74812. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74813. if (invertY === void 0) { invertY = false; }
  74814. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74815. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  74816. };
  74817. /**
  74818. * Creates a luminance alpha texture from some data.
  74819. * @param data Define the texture data
  74820. * @param width Define the width of the texture
  74821. * @param height Define the height of the texture
  74822. * @param scene Define the scene the texture belongs to
  74823. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74824. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74825. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74826. * @returns the luminance alpha texture
  74827. */
  74828. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  74829. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74830. if (invertY === void 0) { invertY = false; }
  74831. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74832. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  74833. };
  74834. /**
  74835. * Creates an alpha texture from some data.
  74836. * @param data Define the texture data
  74837. * @param width Define the width of the texture
  74838. * @param height Define the height of the texture
  74839. * @param scene Define the scene the texture belongs to
  74840. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74841. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74842. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74843. * @returns the alpha texture
  74844. */
  74845. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  74846. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74847. if (invertY === void 0) { invertY = false; }
  74848. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74849. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  74850. };
  74851. /**
  74852. * Creates a RGB texture from some data.
  74853. * @param data Define the texture data
  74854. * @param width Define the width of the texture
  74855. * @param height Define the height of the texture
  74856. * @param scene Define the scene the texture belongs to
  74857. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74858. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74859. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74860. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74861. * @returns the RGB alpha texture
  74862. */
  74863. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  74864. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74865. if (invertY === void 0) { invertY = false; }
  74866. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74867. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74868. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  74869. };
  74870. /**
  74871. * Creates a RGBA 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. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74880. * @returns the RGBA texture
  74881. */
  74882. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  74883. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74884. if (invertY === void 0) { invertY = false; }
  74885. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74886. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74887. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  74888. };
  74889. /**
  74890. * Creates a R texture from some data.
  74891. * @param data Define the texture data
  74892. * @param width Define the width of the texture
  74893. * @param height Define the height of the texture
  74894. * @param scene Define the scene the texture belongs to
  74895. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74896. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74897. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74898. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74899. * @returns the R texture
  74900. */
  74901. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  74902. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74903. if (invertY === void 0) { invertY = false; }
  74904. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74905. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  74906. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  74907. };
  74908. return RawTexture;
  74909. }(BABYLON.Texture));
  74910. BABYLON.RawTexture = RawTexture;
  74911. })(BABYLON || (BABYLON = {}));
  74912. //# sourceMappingURL=babylon.rawTexture.js.map
  74913. var BABYLON;
  74914. (function (BABYLON) {
  74915. /**
  74916. * Class used to store 3D textures containing user data
  74917. */
  74918. var RawTexture3D = /** @class */ (function (_super) {
  74919. __extends(RawTexture3D, _super);
  74920. /**
  74921. * Create a new RawTexture3D
  74922. * @param data defines the data of the texture
  74923. * @param width defines the width of the texture
  74924. * @param height defines the height of the texture
  74925. * @param depth defines the depth of the texture
  74926. * @param format defines the texture format to use
  74927. * @param scene defines the hosting scene
  74928. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  74929. * @param invertY defines if texture must be stored with Y axis inverted
  74930. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  74931. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  74932. */
  74933. function RawTexture3D(data, width, height, depth,
  74934. /** Gets or sets the texture format to use */
  74935. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  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 (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74940. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  74941. _this.format = format;
  74942. _this._engine = scene.getEngine();
  74943. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  74944. _this.is3D = true;
  74945. return _this;
  74946. }
  74947. /**
  74948. * Update the texture with new data
  74949. * @param data defines the data to store in the texture
  74950. */
  74951. RawTexture3D.prototype.update = function (data) {
  74952. if (!this._texture) {
  74953. return;
  74954. }
  74955. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  74956. };
  74957. return RawTexture3D;
  74958. }(BABYLON.Texture));
  74959. BABYLON.RawTexture3D = RawTexture3D;
  74960. })(BABYLON || (BABYLON = {}));
  74961. //# sourceMappingURL=babylon.rawTexture3D.js.map
  74962. var BABYLON;
  74963. (function (BABYLON) {
  74964. /**
  74965. * PostProcessManager is used to manage one or more post processes or post process pipelines
  74966. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  74967. */
  74968. var PostProcessManager = /** @class */ (function () {
  74969. /**
  74970. * Creates a new instance PostProcess
  74971. * @param scene The scene that the post process is associated with.
  74972. */
  74973. function PostProcessManager(scene) {
  74974. this._vertexBuffers = {};
  74975. this._scene = scene;
  74976. }
  74977. PostProcessManager.prototype._prepareBuffers = function () {
  74978. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  74979. return;
  74980. }
  74981. // VBO
  74982. var vertices = [];
  74983. vertices.push(1, 1);
  74984. vertices.push(-1, 1);
  74985. vertices.push(-1, -1);
  74986. vertices.push(1, -1);
  74987. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74988. this._buildIndexBuffer();
  74989. };
  74990. PostProcessManager.prototype._buildIndexBuffer = function () {
  74991. // Indices
  74992. var indices = [];
  74993. indices.push(0);
  74994. indices.push(1);
  74995. indices.push(2);
  74996. indices.push(0);
  74997. indices.push(2);
  74998. indices.push(3);
  74999. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  75000. };
  75001. /**
  75002. * Rebuilds the vertex buffers of the manager.
  75003. * @hidden
  75004. */
  75005. PostProcessManager.prototype._rebuild = function () {
  75006. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75007. if (!vb) {
  75008. return;
  75009. }
  75010. vb._rebuild();
  75011. this._buildIndexBuffer();
  75012. };
  75013. // Methods
  75014. /**
  75015. * Prepares a frame to be run through a post process.
  75016. * @param sourceTexture The input texture to the post procesess. (default: null)
  75017. * @param postProcesses An array of post processes to be run. (default: null)
  75018. * @returns True if the post processes were able to be run.
  75019. * @hidden
  75020. */
  75021. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  75022. if (sourceTexture === void 0) { sourceTexture = null; }
  75023. if (postProcesses === void 0) { postProcesses = null; }
  75024. var camera = this._scene.activeCamera;
  75025. if (!camera) {
  75026. return false;
  75027. }
  75028. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  75029. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  75030. return false;
  75031. }
  75032. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  75033. return true;
  75034. };
  75035. /**
  75036. * Manually render a set of post processes to a texture.
  75037. * @param postProcesses An array of post processes to be run.
  75038. * @param targetTexture The target texture to render to.
  75039. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  75040. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  75041. * @param lodLevel defines which lod of the texture to render to
  75042. */
  75043. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  75044. if (targetTexture === void 0) { targetTexture = null; }
  75045. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  75046. if (faceIndex === void 0) { faceIndex = 0; }
  75047. if (lodLevel === void 0) { lodLevel = 0; }
  75048. var engine = this._scene.getEngine();
  75049. for (var index = 0; index < postProcesses.length; index++) {
  75050. if (index < postProcesses.length - 1) {
  75051. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  75052. }
  75053. else {
  75054. if (targetTexture) {
  75055. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  75056. }
  75057. else {
  75058. engine.restoreDefaultFramebuffer();
  75059. }
  75060. }
  75061. var pp = postProcesses[index];
  75062. var effect = pp.apply();
  75063. if (effect) {
  75064. pp.onBeforeRenderObservable.notifyObservers(effect);
  75065. // VBOs
  75066. this._prepareBuffers();
  75067. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  75068. // Draw order
  75069. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75070. pp.onAfterRenderObservable.notifyObservers(effect);
  75071. }
  75072. }
  75073. // Restore depth buffer
  75074. engine.setDepthBuffer(true);
  75075. engine.setDepthWrite(true);
  75076. };
  75077. /**
  75078. * Finalize the result of the output of the postprocesses.
  75079. * @param doNotPresent If true the result will not be displayed to the screen.
  75080. * @param targetTexture The target texture to render to.
  75081. * @param faceIndex The index of the face to bind the target texture to.
  75082. * @param postProcesses The array of post processes to render.
  75083. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  75084. * @hidden
  75085. */
  75086. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  75087. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  75088. var camera = this._scene.activeCamera;
  75089. if (!camera) {
  75090. return;
  75091. }
  75092. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  75093. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  75094. return;
  75095. }
  75096. var engine = this._scene.getEngine();
  75097. for (var index = 0, len = postProcesses.length; index < len; index++) {
  75098. var pp = postProcesses[index];
  75099. if (index < len - 1) {
  75100. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  75101. }
  75102. else {
  75103. if (targetTexture) {
  75104. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  75105. pp._outputTexture = targetTexture;
  75106. }
  75107. else {
  75108. engine.restoreDefaultFramebuffer();
  75109. pp._outputTexture = null;
  75110. }
  75111. }
  75112. if (doNotPresent) {
  75113. break;
  75114. }
  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 states
  75127. engine.setDepthBuffer(true);
  75128. engine.setDepthWrite(true);
  75129. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75130. };
  75131. /**
  75132. * Disposes of the post process manager.
  75133. */
  75134. PostProcessManager.prototype.dispose = function () {
  75135. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75136. if (buffer) {
  75137. buffer.dispose();
  75138. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75139. }
  75140. if (this._indexBuffer) {
  75141. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75142. this._indexBuffer = null;
  75143. }
  75144. };
  75145. return PostProcessManager;
  75146. }());
  75147. BABYLON.PostProcessManager = PostProcessManager;
  75148. })(BABYLON || (BABYLON = {}));
  75149. //# sourceMappingURL=babylon.postProcessManager.js.map
  75150. var BABYLON;
  75151. (function (BABYLON) {
  75152. /**
  75153. * PostProcess can be used to apply a shader to a texture after it has been rendered
  75154. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  75155. */
  75156. var PostProcess = /** @class */ (function () {
  75157. /**
  75158. * Creates a new instance PostProcess
  75159. * @param name The name of the PostProcess.
  75160. * @param fragmentUrl The url of the fragment shader to be used.
  75161. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  75162. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  75163. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75164. * @param camera The camera to apply the render pass to.
  75165. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75166. * @param engine The engine which the post process will be applied. (default: current engine)
  75167. * @param reusable If the post process can be reused on the same frame. (default: false)
  75168. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  75169. * @param textureType Type of textures used when performing the post process. (default: 0)
  75170. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  75171. * @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
  75172. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  75173. */
  75174. function PostProcess(
  75175. /** Name of the PostProcess. */
  75176. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  75177. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  75178. if (defines === void 0) { defines = null; }
  75179. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75180. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  75181. if (blockCompilation === void 0) { blockCompilation = false; }
  75182. this.name = name;
  75183. /**
  75184. * Width of the texture to apply the post process on
  75185. */
  75186. this.width = -1;
  75187. /**
  75188. * Height of the texture to apply the post process on
  75189. */
  75190. this.height = -1;
  75191. /**
  75192. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  75193. * @hidden
  75194. */
  75195. this._outputTexture = null;
  75196. /**
  75197. * If the buffer needs to be cleared before applying the post process. (default: true)
  75198. * Should be set to false if shader will overwrite all previous pixels.
  75199. */
  75200. this.autoClear = true;
  75201. /**
  75202. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  75203. */
  75204. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  75205. /**
  75206. * Animations to be used for the post processing
  75207. */
  75208. this.animations = new Array();
  75209. /**
  75210. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  75211. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  75212. */
  75213. this.enablePixelPerfectMode = false;
  75214. /**
  75215. * Force the postprocess to be applied without taking in account viewport
  75216. */
  75217. this.forceFullscreenViewport = true;
  75218. /**
  75219. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  75220. *
  75221. * | Value | Type | Description |
  75222. * | ----- | ----------------------------------- | ----------- |
  75223. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  75224. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  75225. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  75226. *
  75227. */
  75228. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  75229. /**
  75230. * Force textures to be a power of two (default: false)
  75231. */
  75232. this.alwaysForcePOT = false;
  75233. this._samples = 1;
  75234. /**
  75235. * Modify the scale of the post process to be the same as the viewport (default: false)
  75236. */
  75237. this.adaptScaleToCurrentViewport = false;
  75238. this._reusable = false;
  75239. /**
  75240. * Smart array of input and output textures for the post process.
  75241. * @hidden
  75242. */
  75243. this._textures = new BABYLON.SmartArray(2);
  75244. /**
  75245. * The index in _textures that corresponds to the output texture.
  75246. * @hidden
  75247. */
  75248. this._currentRenderTextureInd = 0;
  75249. this._scaleRatio = new BABYLON.Vector2(1, 1);
  75250. this._texelSize = BABYLON.Vector2.Zero();
  75251. // Events
  75252. /**
  75253. * An event triggered when the postprocess is activated.
  75254. */
  75255. this.onActivateObservable = new BABYLON.Observable();
  75256. /**
  75257. * An event triggered when the postprocess changes its size.
  75258. */
  75259. this.onSizeChangedObservable = new BABYLON.Observable();
  75260. /**
  75261. * An event triggered when the postprocess applies its effect.
  75262. */
  75263. this.onApplyObservable = new BABYLON.Observable();
  75264. /**
  75265. * An event triggered before rendering the postprocess
  75266. */
  75267. this.onBeforeRenderObservable = new BABYLON.Observable();
  75268. /**
  75269. * An event triggered after rendering the postprocess
  75270. */
  75271. this.onAfterRenderObservable = new BABYLON.Observable();
  75272. if (camera != null) {
  75273. this._camera = camera;
  75274. this._scene = camera.getScene();
  75275. camera.attachPostProcess(this);
  75276. this._engine = this._scene.getEngine();
  75277. this._scene.postProcesses.push(this);
  75278. }
  75279. else if (engine) {
  75280. this._engine = engine;
  75281. this._engine.postProcesses.push(this);
  75282. }
  75283. this._options = options;
  75284. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  75285. this._reusable = reusable || false;
  75286. this._textureType = textureType;
  75287. this._samplers = samplers || [];
  75288. this._samplers.push("textureSampler");
  75289. this._fragmentUrl = fragmentUrl;
  75290. this._vertexUrl = vertexUrl;
  75291. this._parameters = parameters || [];
  75292. this._parameters.push("scale");
  75293. this._indexParameters = indexParameters;
  75294. if (!blockCompilation) {
  75295. this.updateEffect(defines);
  75296. }
  75297. }
  75298. Object.defineProperty(PostProcess.prototype, "samples", {
  75299. /**
  75300. * Number of sample textures (default: 1)
  75301. */
  75302. get: function () {
  75303. return this._samples;
  75304. },
  75305. set: function (n) {
  75306. var _this = this;
  75307. this._samples = n;
  75308. this._textures.forEach(function (texture) {
  75309. if (texture.samples !== _this._samples) {
  75310. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  75311. }
  75312. });
  75313. },
  75314. enumerable: true,
  75315. configurable: true
  75316. });
  75317. Object.defineProperty(PostProcess.prototype, "onActivate", {
  75318. /**
  75319. * A function that is added to the onActivateObservable
  75320. */
  75321. set: function (callback) {
  75322. if (this._onActivateObserver) {
  75323. this.onActivateObservable.remove(this._onActivateObserver);
  75324. }
  75325. if (callback) {
  75326. this._onActivateObserver = this.onActivateObservable.add(callback);
  75327. }
  75328. },
  75329. enumerable: true,
  75330. configurable: true
  75331. });
  75332. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  75333. /**
  75334. * A function that is added to the onSizeChangedObservable
  75335. */
  75336. set: function (callback) {
  75337. if (this._onSizeChangedObserver) {
  75338. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  75339. }
  75340. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  75341. },
  75342. enumerable: true,
  75343. configurable: true
  75344. });
  75345. Object.defineProperty(PostProcess.prototype, "onApply", {
  75346. /**
  75347. * A function that is added to the onApplyObservable
  75348. */
  75349. set: function (callback) {
  75350. if (this._onApplyObserver) {
  75351. this.onApplyObservable.remove(this._onApplyObserver);
  75352. }
  75353. this._onApplyObserver = this.onApplyObservable.add(callback);
  75354. },
  75355. enumerable: true,
  75356. configurable: true
  75357. });
  75358. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  75359. /**
  75360. * A function that is added to the onBeforeRenderObservable
  75361. */
  75362. set: function (callback) {
  75363. if (this._onBeforeRenderObserver) {
  75364. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  75365. }
  75366. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  75367. },
  75368. enumerable: true,
  75369. configurable: true
  75370. });
  75371. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  75372. /**
  75373. * A function that is added to the onAfterRenderObservable
  75374. */
  75375. set: function (callback) {
  75376. if (this._onAfterRenderObserver) {
  75377. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  75378. }
  75379. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  75380. },
  75381. enumerable: true,
  75382. configurable: true
  75383. });
  75384. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  75385. /**
  75386. * 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
  75387. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  75388. */
  75389. get: function () {
  75390. return this._textures.data[this._currentRenderTextureInd];
  75391. },
  75392. set: function (value) {
  75393. this._forcedOutputTexture = value;
  75394. },
  75395. enumerable: true,
  75396. configurable: true
  75397. });
  75398. /**
  75399. * Gets the camera which post process is applied to.
  75400. * @returns The camera the post process is applied to.
  75401. */
  75402. PostProcess.prototype.getCamera = function () {
  75403. return this._camera;
  75404. };
  75405. Object.defineProperty(PostProcess.prototype, "texelSize", {
  75406. /**
  75407. * Gets the texel size of the postprocess.
  75408. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  75409. */
  75410. get: function () {
  75411. if (this._shareOutputWithPostProcess) {
  75412. return this._shareOutputWithPostProcess.texelSize;
  75413. }
  75414. if (this._forcedOutputTexture) {
  75415. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  75416. }
  75417. return this._texelSize;
  75418. },
  75419. enumerable: true,
  75420. configurable: true
  75421. });
  75422. /**
  75423. * Gets the engine which this post process belongs to.
  75424. * @returns The engine the post process was enabled with.
  75425. */
  75426. PostProcess.prototype.getEngine = function () {
  75427. return this._engine;
  75428. };
  75429. /**
  75430. * The effect that is created when initializing the post process.
  75431. * @returns The created effect corrisponding the the postprocess.
  75432. */
  75433. PostProcess.prototype.getEffect = function () {
  75434. return this._effect;
  75435. };
  75436. /**
  75437. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  75438. * @param postProcess The post process to share the output with.
  75439. * @returns This post process.
  75440. */
  75441. PostProcess.prototype.shareOutputWith = function (postProcess) {
  75442. this._disposeTextures();
  75443. this._shareOutputWithPostProcess = postProcess;
  75444. return this;
  75445. };
  75446. /**
  75447. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  75448. * This should be called if the post process that shares output with this post process is disabled/disposed.
  75449. */
  75450. PostProcess.prototype.useOwnOutput = function () {
  75451. if (this._textures.length == 0) {
  75452. this._textures = new BABYLON.SmartArray(2);
  75453. }
  75454. this._shareOutputWithPostProcess = null;
  75455. };
  75456. /**
  75457. * Updates the effect with the current post process compile time values and recompiles the shader.
  75458. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75459. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75460. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75461. * @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
  75462. * @param onCompiled Called when the shader has been compiled.
  75463. * @param onError Called if there is an error when compiling a shader.
  75464. */
  75465. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75466. if (defines === void 0) { defines = null; }
  75467. if (uniforms === void 0) { uniforms = null; }
  75468. if (samplers === void 0) { samplers = null; }
  75469. 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);
  75470. };
  75471. /**
  75472. * The post process is reusable if it can be used multiple times within one frame.
  75473. * @returns If the post process is reusable
  75474. */
  75475. PostProcess.prototype.isReusable = function () {
  75476. return this._reusable;
  75477. };
  75478. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  75479. PostProcess.prototype.markTextureDirty = function () {
  75480. this.width = -1;
  75481. };
  75482. /**
  75483. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  75484. * 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.
  75485. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  75486. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  75487. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  75488. * @returns The target texture that was bound to be written to.
  75489. */
  75490. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  75491. var _this = this;
  75492. if (sourceTexture === void 0) { sourceTexture = null; }
  75493. camera = camera || this._camera;
  75494. var scene = camera.getScene();
  75495. var engine = scene.getEngine();
  75496. var maxSize = engine.getCaps().maxTextureSize;
  75497. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  75498. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  75499. // 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
  75500. var webVRCamera = camera.parent;
  75501. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  75502. requiredWidth /= 2;
  75503. }
  75504. var desiredWidth = (this._options.width || requiredWidth);
  75505. var desiredHeight = this._options.height || requiredHeight;
  75506. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  75507. if (this.adaptScaleToCurrentViewport) {
  75508. var currentViewport = engine.currentViewport;
  75509. if (currentViewport) {
  75510. desiredWidth *= currentViewport.width;
  75511. desiredHeight *= currentViewport.height;
  75512. }
  75513. }
  75514. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  75515. if (!this._options.width) {
  75516. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  75517. }
  75518. if (!this._options.height) {
  75519. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  75520. }
  75521. }
  75522. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  75523. if (this._textures.length > 0) {
  75524. for (var i = 0; i < this._textures.length; i++) {
  75525. this._engine._releaseTexture(this._textures.data[i]);
  75526. }
  75527. this._textures.reset();
  75528. }
  75529. this.width = desiredWidth;
  75530. this.height = desiredHeight;
  75531. var textureSize = { width: this.width, height: this.height };
  75532. var textureOptions = {
  75533. generateMipMaps: false,
  75534. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  75535. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  75536. samplingMode: this.renderTargetSamplingMode,
  75537. type: this._textureType
  75538. };
  75539. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  75540. if (this._reusable) {
  75541. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  75542. }
  75543. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  75544. this.onSizeChangedObservable.notifyObservers(this);
  75545. }
  75546. this._textures.forEach(function (texture) {
  75547. if (texture.samples !== _this.samples) {
  75548. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  75549. }
  75550. });
  75551. }
  75552. var target;
  75553. if (this._shareOutputWithPostProcess) {
  75554. target = this._shareOutputWithPostProcess.inputTexture;
  75555. }
  75556. else if (this._forcedOutputTexture) {
  75557. target = this._forcedOutputTexture;
  75558. this.width = this._forcedOutputTexture.width;
  75559. this.height = this._forcedOutputTexture.height;
  75560. }
  75561. else {
  75562. target = this.inputTexture;
  75563. }
  75564. // Bind the input of this post process to be used as the output of the previous post process.
  75565. if (this.enablePixelPerfectMode) {
  75566. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  75567. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  75568. }
  75569. else {
  75570. this._scaleRatio.copyFromFloats(1, 1);
  75571. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  75572. }
  75573. this.onActivateObservable.notifyObservers(camera);
  75574. // Clear
  75575. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  75576. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  75577. }
  75578. if (this._reusable) {
  75579. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  75580. }
  75581. return target;
  75582. };
  75583. Object.defineProperty(PostProcess.prototype, "isSupported", {
  75584. /**
  75585. * If the post process is supported.
  75586. */
  75587. get: function () {
  75588. return this._effect.isSupported;
  75589. },
  75590. enumerable: true,
  75591. configurable: true
  75592. });
  75593. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  75594. /**
  75595. * The aspect ratio of the output texture.
  75596. */
  75597. get: function () {
  75598. if (this._shareOutputWithPostProcess) {
  75599. return this._shareOutputWithPostProcess.aspectRatio;
  75600. }
  75601. if (this._forcedOutputTexture) {
  75602. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  75603. }
  75604. return this.width / this.height;
  75605. },
  75606. enumerable: true,
  75607. configurable: true
  75608. });
  75609. /**
  75610. * Get a value indicating if the post-process is ready to be used
  75611. * @returns true if the post-process is ready (shader is compiled)
  75612. */
  75613. PostProcess.prototype.isReady = function () {
  75614. return this._effect && this._effect.isReady();
  75615. };
  75616. /**
  75617. * Binds all textures and uniforms to the shader, this will be run on every pass.
  75618. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  75619. */
  75620. PostProcess.prototype.apply = function () {
  75621. // Check
  75622. if (!this._effect || !this._effect.isReady()) {
  75623. return null;
  75624. }
  75625. // States
  75626. this._engine.enableEffect(this._effect);
  75627. this._engine.setState(false);
  75628. this._engine.setDepthBuffer(false);
  75629. this._engine.setDepthWrite(false);
  75630. // Alpha
  75631. this._engine.setAlphaMode(this.alphaMode);
  75632. if (this.alphaConstants) {
  75633. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  75634. }
  75635. // Bind the output texture of the preivous post process as the input to this post process.
  75636. var source;
  75637. if (this._shareOutputWithPostProcess) {
  75638. source = this._shareOutputWithPostProcess.inputTexture;
  75639. }
  75640. else if (this._forcedOutputTexture) {
  75641. source = this._forcedOutputTexture;
  75642. }
  75643. else {
  75644. source = this.inputTexture;
  75645. }
  75646. this._effect._bindTexture("textureSampler", source);
  75647. // Parameters
  75648. this._effect.setVector2("scale", this._scaleRatio);
  75649. this.onApplyObservable.notifyObservers(this._effect);
  75650. return this._effect;
  75651. };
  75652. PostProcess.prototype._disposeTextures = function () {
  75653. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  75654. return;
  75655. }
  75656. if (this._textures.length > 0) {
  75657. for (var i = 0; i < this._textures.length; i++) {
  75658. this._engine._releaseTexture(this._textures.data[i]);
  75659. }
  75660. }
  75661. this._textures.dispose();
  75662. };
  75663. /**
  75664. * Disposes the post process.
  75665. * @param camera The camera to dispose the post process on.
  75666. */
  75667. PostProcess.prototype.dispose = function (camera) {
  75668. camera = camera || this._camera;
  75669. this._disposeTextures();
  75670. if (this._scene) {
  75671. var index_1 = this._scene.postProcesses.indexOf(this);
  75672. if (index_1 !== -1) {
  75673. this._scene.postProcesses.splice(index_1, 1);
  75674. }
  75675. }
  75676. else {
  75677. var index_2 = this._engine.postProcesses.indexOf(this);
  75678. if (index_2 !== -1) {
  75679. this._engine.postProcesses.splice(index_2, 1);
  75680. }
  75681. }
  75682. if (!camera) {
  75683. return;
  75684. }
  75685. camera.detachPostProcess(this);
  75686. var index = camera._postProcesses.indexOf(this);
  75687. if (index === 0 && camera._postProcesses.length > 0) {
  75688. var firstPostProcess = this._camera._getFirstPostProcess();
  75689. if (firstPostProcess) {
  75690. firstPostProcess.markTextureDirty();
  75691. }
  75692. }
  75693. this.onActivateObservable.clear();
  75694. this.onAfterRenderObservable.clear();
  75695. this.onApplyObservable.clear();
  75696. this.onBeforeRenderObservable.clear();
  75697. this.onSizeChangedObservable.clear();
  75698. };
  75699. return PostProcess;
  75700. }());
  75701. BABYLON.PostProcess = PostProcess;
  75702. })(BABYLON || (BABYLON = {}));
  75703. //# sourceMappingURL=babylon.postProcess.js.map
  75704. var BABYLON;
  75705. (function (BABYLON) {
  75706. /**
  75707. * PassPostProcess which produces an output the same as it's input
  75708. */
  75709. var PassPostProcess = /** @class */ (function (_super) {
  75710. __extends(PassPostProcess, _super);
  75711. /**
  75712. * Creates the PassPostProcess
  75713. * @param name The name of the effect.
  75714. * @param options The required width/height ratio to downsize to before computing the render pass.
  75715. * @param camera The camera to apply the render pass to.
  75716. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75717. * @param engine The engine which the post process will be applied. (default: current engine)
  75718. * @param reusable If the post process can be reused on the same frame. (default: false)
  75719. * @param textureType The type of texture to be used when performing the post processing.
  75720. * @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)
  75721. */
  75722. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75723. if (camera === void 0) { camera = null; }
  75724. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75725. if (blockCompilation === void 0) { blockCompilation = false; }
  75726. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  75727. }
  75728. return PassPostProcess;
  75729. }(BABYLON.PostProcess));
  75730. BABYLON.PassPostProcess = PassPostProcess;
  75731. })(BABYLON || (BABYLON = {}));
  75732. //# sourceMappingURL=babylon.passPostProcess.js.map
  75733. var __assign = (this && this.__assign) || function () {
  75734. __assign = Object.assign || function(t) {
  75735. for (var s, i = 1, n = arguments.length; i < n; i++) {
  75736. s = arguments[i];
  75737. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  75738. t[p] = s[p];
  75739. }
  75740. return t;
  75741. };
  75742. return __assign.apply(this, arguments);
  75743. };
  75744. var BABYLON;
  75745. (function (BABYLON) {
  75746. /**
  75747. * Default implementation IShadowGenerator.
  75748. * This is the main object responsible of generating shadows in the framework.
  75749. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  75750. */
  75751. var ShadowGenerator = /** @class */ (function () {
  75752. /**
  75753. * Creates a ShadowGenerator object.
  75754. * A ShadowGenerator is the required tool to use the shadows.
  75755. * Each light casting shadows needs to use its own ShadowGenerator.
  75756. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  75757. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  75758. * @param light The light object generating the shadows.
  75759. * @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.
  75760. */
  75761. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  75762. this._bias = 0.00005;
  75763. this._normalBias = 0;
  75764. this._blurBoxOffset = 1;
  75765. this._blurScale = 2;
  75766. this._blurKernel = 1;
  75767. this._useKernelBlur = false;
  75768. this._filter = ShadowGenerator.FILTER_NONE;
  75769. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  75770. this._contactHardeningLightSizeUVRatio = 0.1;
  75771. this._darkness = 0;
  75772. this._transparencyShadow = false;
  75773. /**
  75774. * Controls the extent to which the shadows fade out at the edge of the frustum
  75775. * Used only by directionals and spots
  75776. */
  75777. this.frustumEdgeFalloff = 0;
  75778. /**
  75779. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  75780. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  75781. * It might on the other hand introduce peter panning.
  75782. */
  75783. this.forceBackFacesOnly = false;
  75784. this._lightDirection = BABYLON.Vector3.Zero();
  75785. this._viewMatrix = BABYLON.Matrix.Zero();
  75786. this._projectionMatrix = BABYLON.Matrix.Zero();
  75787. this._transformMatrix = BABYLON.Matrix.Zero();
  75788. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  75789. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  75790. this._currentFaceIndex = 0;
  75791. this._currentFaceIndexCache = 0;
  75792. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  75793. this._mapSize = mapSize;
  75794. this._light = light;
  75795. this._scene = light.getScene();
  75796. light._shadowGenerator = this;
  75797. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  75798. if (!component) {
  75799. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  75800. this._scene._addComponent(component);
  75801. }
  75802. // Texture type fallback from float to int if not supported.
  75803. var caps = this._scene.getEngine().getCaps();
  75804. if (!useFullFloatFirst) {
  75805. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  75806. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75807. }
  75808. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  75809. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75810. }
  75811. else {
  75812. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75813. }
  75814. }
  75815. else {
  75816. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  75817. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75818. }
  75819. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  75820. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75821. }
  75822. else {
  75823. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75824. }
  75825. }
  75826. this._initializeGenerator();
  75827. this._applyFilterValues();
  75828. }
  75829. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  75830. /**
  75831. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  75832. */
  75833. get: function () {
  75834. return this._bias;
  75835. },
  75836. /**
  75837. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  75838. */
  75839. set: function (bias) {
  75840. this._bias = bias;
  75841. },
  75842. enumerable: true,
  75843. configurable: true
  75844. });
  75845. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  75846. /**
  75847. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  75848. */
  75849. get: function () {
  75850. return this._normalBias;
  75851. },
  75852. /**
  75853. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  75854. */
  75855. set: function (normalBias) {
  75856. this._normalBias = normalBias;
  75857. },
  75858. enumerable: true,
  75859. configurable: true
  75860. });
  75861. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  75862. /**
  75863. * Gets the blur box offset: offset applied during the blur pass.
  75864. * Only usefull if useKernelBlur = false
  75865. */
  75866. get: function () {
  75867. return this._blurBoxOffset;
  75868. },
  75869. /**
  75870. * Sets the blur box offset: offset applied during the blur pass.
  75871. * Only usefull if useKernelBlur = false
  75872. */
  75873. set: function (value) {
  75874. if (this._blurBoxOffset === value) {
  75875. return;
  75876. }
  75877. this._blurBoxOffset = value;
  75878. this._disposeBlurPostProcesses();
  75879. },
  75880. enumerable: true,
  75881. configurable: true
  75882. });
  75883. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  75884. /**
  75885. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  75886. * 2 means half of the size.
  75887. */
  75888. get: function () {
  75889. return this._blurScale;
  75890. },
  75891. /**
  75892. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  75893. * 2 means half of the size.
  75894. */
  75895. set: function (value) {
  75896. if (this._blurScale === value) {
  75897. return;
  75898. }
  75899. this._blurScale = value;
  75900. this._disposeBlurPostProcesses();
  75901. },
  75902. enumerable: true,
  75903. configurable: true
  75904. });
  75905. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  75906. /**
  75907. * Gets the blur kernel: kernel size of the blur pass.
  75908. * Only usefull if useKernelBlur = true
  75909. */
  75910. get: function () {
  75911. return this._blurKernel;
  75912. },
  75913. /**
  75914. * Sets the blur kernel: kernel size of the blur pass.
  75915. * Only usefull if useKernelBlur = true
  75916. */
  75917. set: function (value) {
  75918. if (this._blurKernel === value) {
  75919. return;
  75920. }
  75921. this._blurKernel = value;
  75922. this._disposeBlurPostProcesses();
  75923. },
  75924. enumerable: true,
  75925. configurable: true
  75926. });
  75927. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  75928. /**
  75929. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  75930. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  75931. */
  75932. get: function () {
  75933. return this._useKernelBlur;
  75934. },
  75935. /**
  75936. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  75937. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  75938. */
  75939. set: function (value) {
  75940. if (this._useKernelBlur === value) {
  75941. return;
  75942. }
  75943. this._useKernelBlur = value;
  75944. this._disposeBlurPostProcesses();
  75945. },
  75946. enumerable: true,
  75947. configurable: true
  75948. });
  75949. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  75950. /**
  75951. * Gets the depth scale used in ESM mode.
  75952. */
  75953. get: function () {
  75954. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  75955. },
  75956. /**
  75957. * Sets the depth scale used in ESM mode.
  75958. * This can override the scale stored on the light.
  75959. */
  75960. set: function (value) {
  75961. this._depthScale = value;
  75962. },
  75963. enumerable: true,
  75964. configurable: true
  75965. });
  75966. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  75967. /**
  75968. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  75969. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  75970. */
  75971. get: function () {
  75972. return this._filter;
  75973. },
  75974. /**
  75975. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  75976. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  75977. */
  75978. set: function (value) {
  75979. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  75980. if (this._light.needCube()) {
  75981. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  75982. this.useExponentialShadowMap = true;
  75983. return;
  75984. }
  75985. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  75986. this.useCloseExponentialShadowMap = true;
  75987. return;
  75988. }
  75989. // PCF on cubemap would also be expensive
  75990. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  75991. this.usePoissonSampling = true;
  75992. return;
  75993. }
  75994. }
  75995. // Weblg1 fallback for PCF.
  75996. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  75997. if (this._scene.getEngine().webGLVersion === 1) {
  75998. this.usePoissonSampling = true;
  75999. return;
  76000. }
  76001. }
  76002. if (this._filter === value) {
  76003. return;
  76004. }
  76005. this._filter = value;
  76006. this._disposeBlurPostProcesses();
  76007. this._applyFilterValues();
  76008. this._light._markMeshesAsLightDirty();
  76009. },
  76010. enumerable: true,
  76011. configurable: true
  76012. });
  76013. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  76014. /**
  76015. * Gets if the current filter is set to Poisson Sampling.
  76016. */
  76017. get: function () {
  76018. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  76019. },
  76020. /**
  76021. * Sets the current filter to Poisson Sampling.
  76022. */
  76023. set: function (value) {
  76024. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  76025. return;
  76026. }
  76027. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  76028. },
  76029. enumerable: true,
  76030. configurable: true
  76031. });
  76032. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  76033. /**
  76034. * Gets if the current filter is set to ESM.
  76035. */
  76036. get: function () {
  76037. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  76038. },
  76039. /**
  76040. * Sets the current filter is to ESM.
  76041. */
  76042. set: function (value) {
  76043. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  76044. return;
  76045. }
  76046. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76047. },
  76048. enumerable: true,
  76049. configurable: true
  76050. });
  76051. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  76052. /**
  76053. * Gets if the current filter is set to filtered ESM.
  76054. */
  76055. get: function () {
  76056. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  76057. },
  76058. /**
  76059. * Gets if the current filter is set to filtered ESM.
  76060. */
  76061. set: function (value) {
  76062. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  76063. return;
  76064. }
  76065. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76066. },
  76067. enumerable: true,
  76068. configurable: true
  76069. });
  76070. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  76071. /**
  76072. * Gets if the current filter is set to "close ESM" (using the inverse of the
  76073. * exponential to prevent steep falloff artifacts).
  76074. */
  76075. get: function () {
  76076. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  76077. },
  76078. /**
  76079. * Sets the current filter to "close ESM" (using the inverse of the
  76080. * exponential to prevent steep falloff artifacts).
  76081. */
  76082. set: function (value) {
  76083. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  76084. return;
  76085. }
  76086. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76087. },
  76088. enumerable: true,
  76089. configurable: true
  76090. });
  76091. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  76092. /**
  76093. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  76094. * exponential to prevent steep falloff artifacts).
  76095. */
  76096. get: function () {
  76097. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  76098. },
  76099. /**
  76100. * Sets the current filter to filtered "close ESM" (using the inverse of the
  76101. * exponential to prevent steep falloff artifacts).
  76102. */
  76103. set: function (value) {
  76104. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  76105. return;
  76106. }
  76107. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76108. },
  76109. enumerable: true,
  76110. configurable: true
  76111. });
  76112. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  76113. /**
  76114. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  76115. */
  76116. get: function () {
  76117. return this.filter === ShadowGenerator.FILTER_PCF;
  76118. },
  76119. /**
  76120. * Sets the current filter to "PCF" (percentage closer filtering).
  76121. */
  76122. set: function (value) {
  76123. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  76124. return;
  76125. }
  76126. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  76127. },
  76128. enumerable: true,
  76129. configurable: true
  76130. });
  76131. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  76132. /**
  76133. * Gets the PCF or PCSS Quality.
  76134. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  76135. */
  76136. get: function () {
  76137. return this._filteringQuality;
  76138. },
  76139. /**
  76140. * Sets the PCF or PCSS Quality.
  76141. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  76142. */
  76143. set: function (filteringQuality) {
  76144. this._filteringQuality = filteringQuality;
  76145. },
  76146. enumerable: true,
  76147. configurable: true
  76148. });
  76149. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  76150. /**
  76151. * Gets if the current filter is set to "PCSS" (contact hardening).
  76152. */
  76153. get: function () {
  76154. return this.filter === ShadowGenerator.FILTER_PCSS;
  76155. },
  76156. /**
  76157. * Sets the current filter to "PCSS" (contact hardening).
  76158. */
  76159. set: function (value) {
  76160. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  76161. return;
  76162. }
  76163. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  76164. },
  76165. enumerable: true,
  76166. configurable: true
  76167. });
  76168. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  76169. /**
  76170. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  76171. * Using a ratio helps keeping shape stability independently of the map size.
  76172. *
  76173. * It does not account for the light projection as it was having too much
  76174. * instability during the light setup or during light position changes.
  76175. *
  76176. * Only valid if useContactHardeningShadow is true.
  76177. */
  76178. get: function () {
  76179. return this._contactHardeningLightSizeUVRatio;
  76180. },
  76181. /**
  76182. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  76183. * Using a ratio helps keeping shape stability independently of the map size.
  76184. *
  76185. * It does not account for the light projection as it was having too much
  76186. * instability during the light setup or during light position changes.
  76187. *
  76188. * Only valid if useContactHardeningShadow is true.
  76189. */
  76190. set: function (contactHardeningLightSizeUVRatio) {
  76191. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  76192. },
  76193. enumerable: true,
  76194. configurable: true
  76195. });
  76196. /**
  76197. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  76198. * 0 means strongest and 1 would means no shadow.
  76199. * @returns the darkness.
  76200. */
  76201. ShadowGenerator.prototype.getDarkness = function () {
  76202. return this._darkness;
  76203. };
  76204. /**
  76205. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  76206. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  76207. * @returns the shadow generator allowing fluent coding.
  76208. */
  76209. ShadowGenerator.prototype.setDarkness = function (darkness) {
  76210. if (darkness >= 1.0) {
  76211. this._darkness = 1.0;
  76212. }
  76213. else if (darkness <= 0.0) {
  76214. this._darkness = 0.0;
  76215. }
  76216. else {
  76217. this._darkness = darkness;
  76218. }
  76219. return this;
  76220. };
  76221. /**
  76222. * Sets the ability to have transparent shadow (boolean).
  76223. * @param transparent True if transparent else False
  76224. * @returns the shadow generator allowing fluent coding
  76225. */
  76226. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  76227. this._transparencyShadow = transparent;
  76228. return this;
  76229. };
  76230. /**
  76231. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  76232. * @returns The render target texture if present otherwise, null
  76233. */
  76234. ShadowGenerator.prototype.getShadowMap = function () {
  76235. return this._shadowMap;
  76236. };
  76237. /**
  76238. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  76239. * @returns The render target texture if the shadow map is present otherwise, null
  76240. */
  76241. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  76242. if (this._shadowMap2) {
  76243. return this._shadowMap2;
  76244. }
  76245. return this._shadowMap;
  76246. };
  76247. /**
  76248. * Helper function to add a mesh and its descendants to the list of shadow casters.
  76249. * @param mesh Mesh to add
  76250. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  76251. * @returns the Shadow Generator itself
  76252. */
  76253. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  76254. if (includeDescendants === void 0) { includeDescendants = true; }
  76255. var _a;
  76256. if (!this._shadowMap) {
  76257. return this;
  76258. }
  76259. if (!this._shadowMap.renderList) {
  76260. this._shadowMap.renderList = [];
  76261. }
  76262. this._shadowMap.renderList.push(mesh);
  76263. if (includeDescendants) {
  76264. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  76265. }
  76266. return this;
  76267. };
  76268. /**
  76269. * Helper function to remove a mesh and its descendants from the list of shadow casters
  76270. * @param mesh Mesh to remove
  76271. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  76272. * @returns the Shadow Generator itself
  76273. */
  76274. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  76275. if (includeDescendants === void 0) { includeDescendants = true; }
  76276. if (!this._shadowMap || !this._shadowMap.renderList) {
  76277. return this;
  76278. }
  76279. var index = this._shadowMap.renderList.indexOf(mesh);
  76280. if (index !== -1) {
  76281. this._shadowMap.renderList.splice(index, 1);
  76282. }
  76283. if (includeDescendants) {
  76284. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  76285. var child = _a[_i];
  76286. this.removeShadowCaster(child);
  76287. }
  76288. }
  76289. return this;
  76290. };
  76291. /**
  76292. * Returns the associated light object.
  76293. * @returns the light generating the shadow
  76294. */
  76295. ShadowGenerator.prototype.getLight = function () {
  76296. return this._light;
  76297. };
  76298. ShadowGenerator.prototype._initializeGenerator = function () {
  76299. this._light._markMeshesAsLightDirty();
  76300. this._initializeShadowMap();
  76301. };
  76302. ShadowGenerator.prototype._initializeShadowMap = function () {
  76303. var _this = this;
  76304. // Render target
  76305. var engine = this._scene.getEngine();
  76306. if (engine.webGLVersion > 1) {
  76307. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  76308. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  76309. }
  76310. else {
  76311. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  76312. }
  76313. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76314. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76315. this._shadowMap.anisotropicFilteringLevel = 1;
  76316. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76317. this._shadowMap.renderParticles = false;
  76318. this._shadowMap.ignoreCameraViewport = true;
  76319. // Record Face Index before render.
  76320. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  76321. _this._currentFaceIndex = faceIndex;
  76322. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76323. engine.setColorWrite(false);
  76324. }
  76325. });
  76326. // Custom render function.
  76327. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  76328. // Blur if required afer render.
  76329. this._shadowMap.onAfterUnbindObservable.add(function () {
  76330. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76331. engine.setColorWrite(true);
  76332. }
  76333. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  76334. return;
  76335. }
  76336. var shadowMap = _this.getShadowMapForRendering();
  76337. if (shadowMap) {
  76338. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  76339. }
  76340. });
  76341. // Clear according to the chosen filter.
  76342. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  76343. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  76344. this._shadowMap.onClearObservable.add(function (engine) {
  76345. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76346. engine.clear(clearOne, false, true, false);
  76347. }
  76348. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  76349. engine.clear(clearZero, true, true, false);
  76350. }
  76351. else {
  76352. engine.clear(clearOne, true, true, false);
  76353. }
  76354. });
  76355. };
  76356. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  76357. var _this = this;
  76358. var engine = this._scene.getEngine();
  76359. var targetSize = this._mapSize / this.blurScale;
  76360. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  76361. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  76362. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76363. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76364. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76365. }
  76366. if (this.useKernelBlur) {
  76367. 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);
  76368. this._kernelBlurXPostprocess.width = targetSize;
  76369. this._kernelBlurXPostprocess.height = targetSize;
  76370. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  76371. effect.setTexture("textureSampler", _this._shadowMap);
  76372. });
  76373. 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);
  76374. this._kernelBlurXPostprocess.autoClear = false;
  76375. this._kernelBlurYPostprocess.autoClear = false;
  76376. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  76377. this._kernelBlurXPostprocess.packedFloat = true;
  76378. this._kernelBlurYPostprocess.packedFloat = true;
  76379. }
  76380. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  76381. }
  76382. else {
  76383. 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);
  76384. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  76385. effect.setFloat2("screenSize", targetSize, targetSize);
  76386. effect.setTexture("textureSampler", _this._shadowMap);
  76387. });
  76388. this._boxBlurPostprocess.autoClear = false;
  76389. this._blurPostProcesses = [this._boxBlurPostprocess];
  76390. }
  76391. };
  76392. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76393. var index;
  76394. var engine = this._scene.getEngine();
  76395. if (depthOnlySubMeshes.length) {
  76396. engine.setColorWrite(false);
  76397. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76398. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  76399. }
  76400. engine.setColorWrite(true);
  76401. }
  76402. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76403. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  76404. }
  76405. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76406. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  76407. }
  76408. if (this._transparencyShadow) {
  76409. for (index = 0; index < transparentSubMeshes.length; index++) {
  76410. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  76411. }
  76412. }
  76413. };
  76414. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  76415. var _this = this;
  76416. var mesh = subMesh.getRenderingMesh();
  76417. var scene = this._scene;
  76418. var engine = scene.getEngine();
  76419. var material = subMesh.getMaterial();
  76420. if (!material || subMesh.verticesCount === 0) {
  76421. return;
  76422. }
  76423. // Culling
  76424. engine.setState(material.backFaceCulling);
  76425. // Managing instances
  76426. var batch = mesh._getInstancesRenderList(subMesh._id);
  76427. if (batch.mustReturn) {
  76428. return;
  76429. }
  76430. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76431. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  76432. engine.enableEffect(this._effect);
  76433. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  76434. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  76435. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  76436. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  76437. this._effect.setVector3("lightData", this._cachedDirection);
  76438. }
  76439. else {
  76440. this._effect.setVector3("lightData", this._cachedPosition);
  76441. }
  76442. if (scene.activeCamera) {
  76443. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  76444. }
  76445. // Alpha test
  76446. if (material && material.needAlphaTesting()) {
  76447. var alphaTexture = material.getAlphaTestTexture();
  76448. if (alphaTexture) {
  76449. this._effect.setTexture("diffuseSampler", alphaTexture);
  76450. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  76451. }
  76452. }
  76453. // Bones
  76454. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76455. var skeleton = mesh.skeleton;
  76456. if (skeleton.isUsingTextureForMatrices) {
  76457. var boneTexture = skeleton.getTransformMatrixTexture();
  76458. if (!boneTexture) {
  76459. return;
  76460. }
  76461. this._effect.setTexture("boneSampler", boneTexture);
  76462. this._effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  76463. }
  76464. else {
  76465. this._effect.setMatrices("mBones", skeleton.getTransformMatrices((mesh)));
  76466. }
  76467. }
  76468. // Morph targets
  76469. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  76470. if (this.forceBackFacesOnly) {
  76471. engine.setState(true, 0, false, true);
  76472. }
  76473. // Draw
  76474. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76475. if (this.forceBackFacesOnly) {
  76476. engine.setState(true, 0, false, false);
  76477. }
  76478. }
  76479. else {
  76480. // Need to reset refresh rate of the shadowMap
  76481. if (this._shadowMap) {
  76482. this._shadowMap.resetRefreshCounter();
  76483. }
  76484. }
  76485. };
  76486. ShadowGenerator.prototype._applyFilterValues = function () {
  76487. if (!this._shadowMap) {
  76488. return;
  76489. }
  76490. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  76491. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  76492. }
  76493. else {
  76494. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76495. }
  76496. };
  76497. /**
  76498. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  76499. * @param onCompiled Callback triggered at the and of the effects compilation
  76500. * @param options Sets of optional options forcing the compilation with different modes
  76501. */
  76502. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  76503. var _this = this;
  76504. var localOptions = __assign({ useInstances: false }, options);
  76505. var shadowMap = this.getShadowMap();
  76506. if (!shadowMap) {
  76507. if (onCompiled) {
  76508. onCompiled(this);
  76509. }
  76510. return;
  76511. }
  76512. var renderList = shadowMap.renderList;
  76513. if (!renderList) {
  76514. if (onCompiled) {
  76515. onCompiled(this);
  76516. }
  76517. return;
  76518. }
  76519. var subMeshes = new Array();
  76520. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  76521. var mesh = renderList_1[_i];
  76522. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  76523. }
  76524. if (subMeshes.length === 0) {
  76525. if (onCompiled) {
  76526. onCompiled(this);
  76527. }
  76528. return;
  76529. }
  76530. var currentIndex = 0;
  76531. var checkReady = function () {
  76532. if (!_this._scene || !_this._scene.getEngine()) {
  76533. return;
  76534. }
  76535. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  76536. currentIndex++;
  76537. if (currentIndex >= subMeshes.length) {
  76538. if (onCompiled) {
  76539. onCompiled(_this);
  76540. }
  76541. return;
  76542. }
  76543. }
  76544. setTimeout(checkReady, 16);
  76545. };
  76546. checkReady();
  76547. };
  76548. /**
  76549. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  76550. * @param options Sets of optional options forcing the compilation with different modes
  76551. * @returns A promise that resolves when the compilation completes
  76552. */
  76553. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  76554. var _this = this;
  76555. return new Promise(function (resolve) {
  76556. _this.forceCompilation(function () {
  76557. resolve();
  76558. }, options);
  76559. });
  76560. };
  76561. /**
  76562. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  76563. * @param subMesh The submesh we want to render in the shadow map
  76564. * @param useInstances Defines wether will draw in the map using instances
  76565. * @returns true if ready otherwise, false
  76566. */
  76567. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  76568. var defines = [];
  76569. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  76570. defines.push("#define FLOAT");
  76571. }
  76572. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  76573. defines.push("#define ESM");
  76574. }
  76575. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  76576. defines.push("#define DEPTHTEXTURE");
  76577. }
  76578. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76579. var mesh = subMesh.getMesh();
  76580. var material = subMesh.getMaterial();
  76581. // Normal bias.
  76582. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  76583. attribs.push(BABYLON.VertexBuffer.NormalKind);
  76584. defines.push("#define NORMAL");
  76585. if (mesh.nonUniformScaling) {
  76586. defines.push("#define NONUNIFORMSCALING");
  76587. }
  76588. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  76589. defines.push("#define DIRECTIONINLIGHTDATA");
  76590. }
  76591. }
  76592. // Alpha test
  76593. if (material && material.needAlphaTesting()) {
  76594. var alphaTexture = material.getAlphaTestTexture();
  76595. if (alphaTexture) {
  76596. defines.push("#define ALPHATEST");
  76597. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76598. attribs.push(BABYLON.VertexBuffer.UVKind);
  76599. defines.push("#define UV1");
  76600. }
  76601. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76602. if (alphaTexture.coordinatesIndex === 1) {
  76603. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76604. defines.push("#define UV2");
  76605. }
  76606. }
  76607. }
  76608. }
  76609. // Bones
  76610. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76611. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76612. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76613. if (mesh.numBoneInfluencers > 4) {
  76614. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76615. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76616. }
  76617. var skeleton = mesh.skeleton;
  76618. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76619. if (skeleton.isUsingTextureForMatrices) {
  76620. defines.push("#define BONETEXTURE");
  76621. }
  76622. else {
  76623. defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
  76624. }
  76625. }
  76626. else {
  76627. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76628. }
  76629. // Morph targets
  76630. var manager = mesh.morphTargetManager;
  76631. var morphInfluencers = 0;
  76632. if (manager) {
  76633. if (manager.numInfluencers > 0) {
  76634. defines.push("#define MORPHTARGETS");
  76635. morphInfluencers = manager.numInfluencers;
  76636. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  76637. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  76638. }
  76639. }
  76640. // Instances
  76641. if (useInstances) {
  76642. defines.push("#define INSTANCES");
  76643. attribs.push("world0");
  76644. attribs.push("world1");
  76645. attribs.push("world2");
  76646. attribs.push("world3");
  76647. }
  76648. // Get correct effect
  76649. var join = defines.join("\n");
  76650. if (this._cachedDefines !== join) {
  76651. this._cachedDefines = join;
  76652. 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 });
  76653. }
  76654. if (!this._effect.isReady()) {
  76655. return false;
  76656. }
  76657. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  76658. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  76659. this._initializeBlurRTTAndPostProcesses();
  76660. }
  76661. }
  76662. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  76663. return false;
  76664. }
  76665. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  76666. return false;
  76667. }
  76668. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  76669. return false;
  76670. }
  76671. return true;
  76672. };
  76673. /**
  76674. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  76675. * @param defines Defines of the material we want to update
  76676. * @param lightIndex Index of the light in the enabled light list of the material
  76677. */
  76678. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  76679. var scene = this._scene;
  76680. var light = this._light;
  76681. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  76682. return;
  76683. }
  76684. defines["SHADOW" + lightIndex] = true;
  76685. if (this.useContactHardeningShadow) {
  76686. defines["SHADOWPCSS" + lightIndex] = true;
  76687. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  76688. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  76689. }
  76690. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  76691. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  76692. }
  76693. // else default to high.
  76694. }
  76695. if (this.usePercentageCloserFiltering) {
  76696. defines["SHADOWPCF" + lightIndex] = true;
  76697. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  76698. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  76699. }
  76700. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  76701. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  76702. }
  76703. // else default to high.
  76704. }
  76705. else if (this.usePoissonSampling) {
  76706. defines["SHADOWPOISSON" + lightIndex] = true;
  76707. }
  76708. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  76709. defines["SHADOWESM" + lightIndex] = true;
  76710. }
  76711. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  76712. defines["SHADOWCLOSEESM" + lightIndex] = true;
  76713. }
  76714. if (light.needCube()) {
  76715. defines["SHADOWCUBE" + lightIndex] = true;
  76716. }
  76717. };
  76718. /**
  76719. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  76720. * defined in the generator but impacting the effect).
  76721. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  76722. * @param effect The effect we are binfing the information for
  76723. */
  76724. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  76725. var light = this._light;
  76726. var scene = this._scene;
  76727. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  76728. return;
  76729. }
  76730. var camera = scene.activeCamera;
  76731. if (!camera) {
  76732. return;
  76733. }
  76734. var shadowMap = this.getShadowMap();
  76735. if (!shadowMap) {
  76736. return;
  76737. }
  76738. if (!light.needCube()) {
  76739. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  76740. }
  76741. // Only PCF uses depth stencil texture.
  76742. if (this._filter === ShadowGenerator.FILTER_PCF) {
  76743. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76744. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  76745. }
  76746. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  76747. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76748. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  76749. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  76750. }
  76751. else {
  76752. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76753. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  76754. }
  76755. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  76756. };
  76757. /**
  76758. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  76759. * (eq to shadow prjection matrix * light transform matrix)
  76760. * @returns The transform matrix used to create the shadow map
  76761. */
  76762. ShadowGenerator.prototype.getTransformMatrix = function () {
  76763. var scene = this._scene;
  76764. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  76765. return this._transformMatrix;
  76766. }
  76767. this._currentRenderID = scene.getRenderId();
  76768. this._currentFaceIndexCache = this._currentFaceIndex;
  76769. var lightPosition = this._light.position;
  76770. if (this._light.computeTransformedInformation()) {
  76771. lightPosition = this._light.transformedPosition;
  76772. }
  76773. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  76774. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  76775. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  76776. }
  76777. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  76778. this._cachedPosition.copyFrom(lightPosition);
  76779. this._cachedDirection.copyFrom(this._lightDirection);
  76780. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  76781. var shadowMap = this.getShadowMap();
  76782. if (shadowMap) {
  76783. var renderList = shadowMap.renderList;
  76784. if (renderList) {
  76785. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  76786. }
  76787. }
  76788. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  76789. }
  76790. return this._transformMatrix;
  76791. };
  76792. /**
  76793. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  76794. * Cube and 2D textures for instance.
  76795. */
  76796. ShadowGenerator.prototype.recreateShadowMap = function () {
  76797. var shadowMap = this._shadowMap;
  76798. if (!shadowMap) {
  76799. return;
  76800. }
  76801. // Track render list.
  76802. var renderList = shadowMap.renderList;
  76803. // Clean up existing data.
  76804. this._disposeRTTandPostProcesses();
  76805. // Reinitializes.
  76806. this._initializeGenerator();
  76807. // Reaffect the filter to ensure a correct fallback if necessary.
  76808. this.filter = this.filter;
  76809. // Reaffect the filter.
  76810. this._applyFilterValues();
  76811. // Reaffect Render List.
  76812. this._shadowMap.renderList = renderList;
  76813. };
  76814. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  76815. if (this._shadowMap2) {
  76816. this._shadowMap2.dispose();
  76817. this._shadowMap2 = null;
  76818. }
  76819. if (this._boxBlurPostprocess) {
  76820. this._boxBlurPostprocess.dispose();
  76821. this._boxBlurPostprocess = null;
  76822. }
  76823. if (this._kernelBlurXPostprocess) {
  76824. this._kernelBlurXPostprocess.dispose();
  76825. this._kernelBlurXPostprocess = null;
  76826. }
  76827. if (this._kernelBlurYPostprocess) {
  76828. this._kernelBlurYPostprocess.dispose();
  76829. this._kernelBlurYPostprocess = null;
  76830. }
  76831. this._blurPostProcesses = [];
  76832. };
  76833. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  76834. if (this._shadowMap) {
  76835. this._shadowMap.dispose();
  76836. this._shadowMap = null;
  76837. }
  76838. this._disposeBlurPostProcesses();
  76839. };
  76840. /**
  76841. * Disposes the ShadowGenerator.
  76842. * Returns nothing.
  76843. */
  76844. ShadowGenerator.prototype.dispose = function () {
  76845. this._disposeRTTandPostProcesses();
  76846. if (this._light) {
  76847. this._light._shadowGenerator = null;
  76848. this._light._markMeshesAsLightDirty();
  76849. }
  76850. };
  76851. /**
  76852. * Serializes the shadow generator setup to a json object.
  76853. * @returns The serialized JSON object
  76854. */
  76855. ShadowGenerator.prototype.serialize = function () {
  76856. var serializationObject = {};
  76857. var shadowMap = this.getShadowMap();
  76858. if (!shadowMap) {
  76859. return serializationObject;
  76860. }
  76861. serializationObject.lightId = this._light.id;
  76862. serializationObject.mapSize = shadowMap.getRenderSize();
  76863. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  76864. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  76865. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  76866. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  76867. serializationObject.usePoissonSampling = this.usePoissonSampling;
  76868. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  76869. serializationObject.depthScale = this.depthScale;
  76870. serializationObject.darkness = this.getDarkness();
  76871. serializationObject.blurBoxOffset = this.blurBoxOffset;
  76872. serializationObject.blurKernel = this.blurKernel;
  76873. serializationObject.blurScale = this.blurScale;
  76874. serializationObject.useKernelBlur = this.useKernelBlur;
  76875. serializationObject.transparencyShadow = this._transparencyShadow;
  76876. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  76877. serializationObject.bias = this.bias;
  76878. serializationObject.normalBias = this.normalBias;
  76879. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  76880. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  76881. serializationObject.filteringQuality = this.filteringQuality;
  76882. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  76883. serializationObject.renderList = [];
  76884. if (shadowMap.renderList) {
  76885. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  76886. var mesh = shadowMap.renderList[meshIndex];
  76887. serializationObject.renderList.push(mesh.id);
  76888. }
  76889. }
  76890. return serializationObject;
  76891. };
  76892. /**
  76893. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  76894. * @param parsedShadowGenerator The JSON object to parse
  76895. * @param scene The scene to create the shadow map for
  76896. * @returns The parsed shadow generator
  76897. */
  76898. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  76899. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  76900. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  76901. var shadowMap = shadowGenerator.getShadowMap();
  76902. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  76903. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  76904. meshes.forEach(function (mesh) {
  76905. if (!shadowMap) {
  76906. return;
  76907. }
  76908. if (!shadowMap.renderList) {
  76909. shadowMap.renderList = [];
  76910. }
  76911. shadowMap.renderList.push(mesh);
  76912. });
  76913. }
  76914. if (parsedShadowGenerator.usePoissonSampling) {
  76915. shadowGenerator.usePoissonSampling = true;
  76916. }
  76917. else if (parsedShadowGenerator.useExponentialShadowMap) {
  76918. shadowGenerator.useExponentialShadowMap = true;
  76919. }
  76920. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  76921. shadowGenerator.useBlurExponentialShadowMap = true;
  76922. }
  76923. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  76924. shadowGenerator.useCloseExponentialShadowMap = true;
  76925. }
  76926. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  76927. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  76928. }
  76929. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  76930. shadowGenerator.usePercentageCloserFiltering = true;
  76931. }
  76932. else if (parsedShadowGenerator.useContactHardeningShadow) {
  76933. shadowGenerator.useContactHardeningShadow = true;
  76934. }
  76935. if (parsedShadowGenerator.filteringQuality) {
  76936. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  76937. }
  76938. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  76939. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  76940. }
  76941. // Backward compat
  76942. else if (parsedShadowGenerator.useVarianceShadowMap) {
  76943. shadowGenerator.useExponentialShadowMap = true;
  76944. }
  76945. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  76946. shadowGenerator.useBlurExponentialShadowMap = true;
  76947. }
  76948. if (parsedShadowGenerator.depthScale) {
  76949. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  76950. }
  76951. if (parsedShadowGenerator.blurScale) {
  76952. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  76953. }
  76954. if (parsedShadowGenerator.blurBoxOffset) {
  76955. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  76956. }
  76957. if (parsedShadowGenerator.useKernelBlur) {
  76958. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  76959. }
  76960. if (parsedShadowGenerator.blurKernel) {
  76961. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  76962. }
  76963. if (parsedShadowGenerator.bias !== undefined) {
  76964. shadowGenerator.bias = parsedShadowGenerator.bias;
  76965. }
  76966. if (parsedShadowGenerator.normalBias !== undefined) {
  76967. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  76968. }
  76969. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  76970. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  76971. }
  76972. if (parsedShadowGenerator.darkness) {
  76973. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  76974. }
  76975. if (parsedShadowGenerator.transparencyShadow) {
  76976. shadowGenerator.setTransparencyShadow(true);
  76977. }
  76978. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  76979. return shadowGenerator;
  76980. };
  76981. /**
  76982. * Shadow generator mode None: no filtering applied.
  76983. */
  76984. ShadowGenerator.FILTER_NONE = 0;
  76985. /**
  76986. * Shadow generator mode ESM: Exponential Shadow Mapping.
  76987. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  76988. */
  76989. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  76990. /**
  76991. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  76992. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  76993. */
  76994. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  76995. /**
  76996. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  76997. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  76998. */
  76999. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  77000. /**
  77001. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  77002. * edge artifacts on steep falloff.
  77003. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77004. */
  77005. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  77006. /**
  77007. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  77008. * edge artifacts on steep falloff.
  77009. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77010. */
  77011. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  77012. /**
  77013. * Shadow generator mode PCF: Percentage Closer Filtering
  77014. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  77015. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  77016. */
  77017. ShadowGenerator.FILTER_PCF = 6;
  77018. /**
  77019. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  77020. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  77021. * Contact Hardening
  77022. */
  77023. ShadowGenerator.FILTER_PCSS = 7;
  77024. /**
  77025. * Reserved for PCF and PCSS
  77026. * Highest Quality.
  77027. *
  77028. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  77029. *
  77030. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  77031. */
  77032. ShadowGenerator.QUALITY_HIGH = 0;
  77033. /**
  77034. * Reserved for PCF and PCSS
  77035. * Good tradeoff for quality/perf cross devices
  77036. *
  77037. * Execute PCF on a 3*3 kernel.
  77038. *
  77039. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  77040. */
  77041. ShadowGenerator.QUALITY_MEDIUM = 1;
  77042. /**
  77043. * Reserved for PCF and PCSS
  77044. * The lowest quality but the fastest.
  77045. *
  77046. * Execute PCF on a 1*1 kernel.
  77047. *
  77048. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  77049. */
  77050. ShadowGenerator.QUALITY_LOW = 2;
  77051. return ShadowGenerator;
  77052. }());
  77053. BABYLON.ShadowGenerator = ShadowGenerator;
  77054. })(BABYLON || (BABYLON = {}));
  77055. //# sourceMappingURL=babylon.shadowGenerator.js.map
  77056. var BABYLON;
  77057. (function (BABYLON) {
  77058. // Adds the parser to the scene parsers.
  77059. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  77060. // Shadows
  77061. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  77062. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  77063. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  77064. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  77065. // SG would be available on their associated lights
  77066. }
  77067. }
  77068. });
  77069. /**
  77070. * Defines the shadow generator component responsible to manage any shadow generators
  77071. * in a given scene.
  77072. */
  77073. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  77074. /**
  77075. * Creates a new instance of the component for the given scene
  77076. * @param scene Defines the scene to register the component in
  77077. */
  77078. function ShadowGeneratorSceneComponent(scene) {
  77079. /**
  77080. * The component name helpfull to identify the component in the list of scene components.
  77081. */
  77082. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  77083. this.scene = scene;
  77084. }
  77085. /**
  77086. * Registers the component in a given scene
  77087. */
  77088. ShadowGeneratorSceneComponent.prototype.register = function () {
  77089. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  77090. };
  77091. /**
  77092. * Rebuilds the elements related to this component in case of
  77093. * context lost for instance.
  77094. */
  77095. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  77096. // Nothing To Do Here.
  77097. };
  77098. /**
  77099. * Serializes the component data to the specified json object
  77100. * @param serializationObject The object to serialize to
  77101. */
  77102. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  77103. // Shadows
  77104. serializationObject.shadowGenerators = [];
  77105. var lights = this.scene.lights;
  77106. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  77107. var light = lights_1[_i];
  77108. var shadowGenerator = light.getShadowGenerator();
  77109. if (shadowGenerator) {
  77110. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  77111. }
  77112. }
  77113. };
  77114. /**
  77115. * Adds all the element from the container to the scene
  77116. * @param container the container holding the elements
  77117. */
  77118. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  77119. // Nothing To Do Here. (directly attached to a light)
  77120. };
  77121. /**
  77122. * Removes all the elements in the container from the scene
  77123. * @param container contains the elements to remove
  77124. */
  77125. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  77126. // Nothing To Do Here. (directly attached to a light)
  77127. };
  77128. /**
  77129. * Rebuilds the elements related to this component in case of
  77130. * context lost for instance.
  77131. */
  77132. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  77133. // Nothing To Do Here.
  77134. };
  77135. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77136. // Shadows
  77137. var scene = this.scene;
  77138. if (this.scene.shadowsEnabled) {
  77139. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  77140. var light = scene.lights[lightIndex];
  77141. var shadowGenerator = light.getShadowGenerator();
  77142. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  77143. var shadowMap = (shadowGenerator.getShadowMap());
  77144. if (scene.textures.indexOf(shadowMap) !== -1) {
  77145. renderTargets.push(shadowMap);
  77146. }
  77147. }
  77148. }
  77149. }
  77150. };
  77151. return ShadowGeneratorSceneComponent;
  77152. }());
  77153. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  77154. })(BABYLON || (BABYLON = {}));
  77155. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  77156. var BABYLON;
  77157. (function (BABYLON) {
  77158. /**
  77159. * Class used for the default loading screen
  77160. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  77161. */
  77162. var DefaultLoadingScreen = /** @class */ (function () {
  77163. /**
  77164. * Creates a new default loading screen
  77165. * @param _renderingCanvas defines the canvas used to render the scene
  77166. * @param _loadingText defines the default text to display
  77167. * @param _loadingDivBackgroundColor defines the default background color
  77168. */
  77169. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  77170. if (_loadingText === void 0) { _loadingText = ""; }
  77171. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  77172. var _this = this;
  77173. this._renderingCanvas = _renderingCanvas;
  77174. this._loadingText = _loadingText;
  77175. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  77176. // Resize
  77177. this._resizeLoadingUI = function () {
  77178. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  77179. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  77180. if (!_this._loadingDiv) {
  77181. return;
  77182. }
  77183. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  77184. _this._loadingDiv.style.left = canvasRect.left + "px";
  77185. _this._loadingDiv.style.top = canvasRect.top + "px";
  77186. _this._loadingDiv.style.width = canvasRect.width + "px";
  77187. _this._loadingDiv.style.height = canvasRect.height + "px";
  77188. };
  77189. }
  77190. /**
  77191. * Function called to display the loading screen
  77192. */
  77193. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  77194. if (this._loadingDiv) {
  77195. // Do not add a loading screen if there is already one
  77196. return;
  77197. }
  77198. this._loadingDiv = document.createElement("div");
  77199. this._loadingDiv.id = "babylonjsLoadingDiv";
  77200. this._loadingDiv.style.opacity = "0";
  77201. this._loadingDiv.style.transition = "opacity 1.5s ease";
  77202. this._loadingDiv.style.pointerEvents = "none";
  77203. // Loading text
  77204. this._loadingTextDiv = document.createElement("div");
  77205. this._loadingTextDiv.style.position = "absolute";
  77206. this._loadingTextDiv.style.left = "0";
  77207. this._loadingTextDiv.style.top = "50%";
  77208. this._loadingTextDiv.style.marginTop = "80px";
  77209. this._loadingTextDiv.style.width = "100%";
  77210. this._loadingTextDiv.style.height = "20px";
  77211. this._loadingTextDiv.style.fontFamily = "Arial";
  77212. this._loadingTextDiv.style.fontSize = "14px";
  77213. this._loadingTextDiv.style.color = "white";
  77214. this._loadingTextDiv.style.textAlign = "center";
  77215. this._loadingTextDiv.innerHTML = "Loading";
  77216. this._loadingDiv.appendChild(this._loadingTextDiv);
  77217. //set the predefined text
  77218. this._loadingTextDiv.innerHTML = this._loadingText;
  77219. // Generating keyframes
  77220. var style = document.createElement('style');
  77221. style.type = 'text/css';
  77222. 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 }";
  77223. style.innerHTML = keyFrames;
  77224. document.getElementsByTagName('head')[0].appendChild(style);
  77225. // Loading img
  77226. var imgBack = new Image();
  77227. 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";
  77228. imgBack.style.position = "absolute";
  77229. imgBack.style.left = "50%";
  77230. imgBack.style.top = "50%";
  77231. imgBack.style.marginLeft = "-60px";
  77232. imgBack.style.marginTop = "-60px";
  77233. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  77234. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  77235. imgBack.style.transformOrigin = "50% 50%";
  77236. imgBack.style.webkitTransformOrigin = "50% 50%";
  77237. this._loadingDiv.appendChild(imgBack);
  77238. this._resizeLoadingUI();
  77239. window.addEventListener("resize", this._resizeLoadingUI);
  77240. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  77241. document.body.appendChild(this._loadingDiv);
  77242. this._loadingDiv.style.opacity = "1";
  77243. };
  77244. /**
  77245. * Function called to hide the loading screen
  77246. */
  77247. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  77248. var _this = this;
  77249. if (!this._loadingDiv) {
  77250. return;
  77251. }
  77252. var onTransitionEnd = function () {
  77253. if (!_this._loadingDiv) {
  77254. return;
  77255. }
  77256. document.body.removeChild(_this._loadingDiv);
  77257. window.removeEventListener("resize", _this._resizeLoadingUI);
  77258. _this._loadingDiv = null;
  77259. };
  77260. this._loadingDiv.style.opacity = "0";
  77261. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  77262. };
  77263. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  77264. get: function () {
  77265. return this._loadingText;
  77266. },
  77267. /**
  77268. * Gets or sets the text to display while loading
  77269. */
  77270. set: function (text) {
  77271. this._loadingText = text;
  77272. if (this._loadingTextDiv) {
  77273. this._loadingTextDiv.innerHTML = this._loadingText;
  77274. }
  77275. },
  77276. enumerable: true,
  77277. configurable: true
  77278. });
  77279. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  77280. /**
  77281. * Gets or sets the color to use for the background
  77282. */
  77283. get: function () {
  77284. return this._loadingDivBackgroundColor;
  77285. },
  77286. set: function (color) {
  77287. this._loadingDivBackgroundColor = color;
  77288. if (!this._loadingDiv) {
  77289. return;
  77290. }
  77291. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  77292. },
  77293. enumerable: true,
  77294. configurable: true
  77295. });
  77296. return DefaultLoadingScreen;
  77297. }());
  77298. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  77299. })(BABYLON || (BABYLON = {}));
  77300. //# sourceMappingURL=babylon.loadingScreen.js.map
  77301. var BABYLON;
  77302. (function (BABYLON) {
  77303. /**
  77304. * Class used to represent data loading progression
  77305. */
  77306. var SceneLoaderProgressEvent = /** @class */ (function () {
  77307. /**
  77308. * Create a new progress event
  77309. * @param lengthComputable defines if data length to load can be evaluated
  77310. * @param loaded defines the loaded data length
  77311. * @param total defines the data length to load
  77312. */
  77313. function SceneLoaderProgressEvent(
  77314. /** defines if data length to load can be evaluated */
  77315. lengthComputable,
  77316. /** defines the loaded data length */
  77317. loaded,
  77318. /** defines the data length to load */
  77319. total) {
  77320. this.lengthComputable = lengthComputable;
  77321. this.loaded = loaded;
  77322. this.total = total;
  77323. }
  77324. /**
  77325. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  77326. * @param event defines the source event
  77327. * @returns a new SceneLoaderProgressEvent
  77328. */
  77329. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  77330. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  77331. };
  77332. return SceneLoaderProgressEvent;
  77333. }());
  77334. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  77335. /**
  77336. * Class used to load scene from various file formats using registered plugins
  77337. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  77338. */
  77339. var SceneLoader = /** @class */ (function () {
  77340. function SceneLoader() {
  77341. }
  77342. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  77343. /**
  77344. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  77345. */
  77346. get: function () {
  77347. return SceneLoader._ForceFullSceneLoadingForIncremental;
  77348. },
  77349. set: function (value) {
  77350. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  77351. },
  77352. enumerable: true,
  77353. configurable: true
  77354. });
  77355. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  77356. /**
  77357. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  77358. */
  77359. get: function () {
  77360. return SceneLoader._ShowLoadingScreen;
  77361. },
  77362. set: function (value) {
  77363. SceneLoader._ShowLoadingScreen = value;
  77364. },
  77365. enumerable: true,
  77366. configurable: true
  77367. });
  77368. Object.defineProperty(SceneLoader, "loggingLevel", {
  77369. /**
  77370. * Defines the current logging level (while loading the scene)
  77371. * @ignorenaming
  77372. */
  77373. get: function () {
  77374. return SceneLoader._loggingLevel;
  77375. },
  77376. set: function (value) {
  77377. SceneLoader._loggingLevel = value;
  77378. },
  77379. enumerable: true,
  77380. configurable: true
  77381. });
  77382. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  77383. /**
  77384. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  77385. */
  77386. get: function () {
  77387. return SceneLoader._CleanBoneMatrixWeights;
  77388. },
  77389. set: function (value) {
  77390. SceneLoader._CleanBoneMatrixWeights = value;
  77391. },
  77392. enumerable: true,
  77393. configurable: true
  77394. });
  77395. SceneLoader._getDefaultPlugin = function () {
  77396. return SceneLoader._registeredPlugins[".babylon"];
  77397. };
  77398. SceneLoader._getPluginForExtension = function (extension) {
  77399. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  77400. if (registeredPlugin) {
  77401. return registeredPlugin;
  77402. }
  77403. 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");
  77404. return SceneLoader._getDefaultPlugin();
  77405. };
  77406. SceneLoader._getPluginForDirectLoad = function (data) {
  77407. for (var extension in SceneLoader._registeredPlugins) {
  77408. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  77409. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  77410. return SceneLoader._registeredPlugins[extension];
  77411. }
  77412. }
  77413. return SceneLoader._getDefaultPlugin();
  77414. };
  77415. SceneLoader._getPluginForFilename = function (sceneFilename) {
  77416. var queryStringPosition = sceneFilename.indexOf("?");
  77417. if (queryStringPosition !== -1) {
  77418. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  77419. }
  77420. var dotPosition = sceneFilename.lastIndexOf(".");
  77421. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  77422. return SceneLoader._getPluginForExtension(extension);
  77423. };
  77424. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  77425. SceneLoader._getDirectLoad = function (sceneFilename) {
  77426. if (sceneFilename.substr(0, 5) === "data:") {
  77427. return sceneFilename.substr(5);
  77428. }
  77429. return null;
  77430. };
  77431. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  77432. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  77433. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  77434. var plugin;
  77435. if (registeredPlugin.plugin.createPlugin) {
  77436. plugin = registeredPlugin.plugin.createPlugin();
  77437. }
  77438. else {
  77439. plugin = registeredPlugin.plugin;
  77440. }
  77441. var useArrayBuffer = registeredPlugin.isBinary;
  77442. var offlineProvider;
  77443. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  77444. var dataCallback = function (data, responseURL) {
  77445. if (scene.isDisposed) {
  77446. onError("Scene has been disposed");
  77447. return;
  77448. }
  77449. scene.offlineProvider = offlineProvider;
  77450. onSuccess(plugin, data, responseURL);
  77451. };
  77452. var request = null;
  77453. var pluginDisposed = false;
  77454. var onDisposeObservable = plugin.onDisposeObservable;
  77455. if (onDisposeObservable) {
  77456. onDisposeObservable.add(function () {
  77457. pluginDisposed = true;
  77458. if (request) {
  77459. request.abort();
  77460. request = null;
  77461. }
  77462. onDispose();
  77463. });
  77464. }
  77465. var manifestChecked = function () {
  77466. if (pluginDisposed) {
  77467. return;
  77468. }
  77469. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  77470. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  77471. } : undefined, offlineProvider, useArrayBuffer, function (request, exception) {
  77472. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  77473. });
  77474. };
  77475. if (directLoad) {
  77476. dataCallback(directLoad);
  77477. return plugin;
  77478. }
  77479. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  77480. var engine = scene.getEngine();
  77481. var canUseOfflineSupport = engine.enableOfflineSupport;
  77482. if (canUseOfflineSupport) {
  77483. // Also check for exceptions
  77484. var exceptionFound = false;
  77485. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  77486. var regex = _a[_i];
  77487. if (regex.test(fileInfo.url)) {
  77488. exceptionFound = true;
  77489. break;
  77490. }
  77491. }
  77492. canUseOfflineSupport = !exceptionFound;
  77493. }
  77494. if (canUseOfflineSupport && BABYLON.Engine.OfflineProviderFactory) {
  77495. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  77496. offlineProvider = BABYLON.Engine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  77497. }
  77498. else {
  77499. manifestChecked();
  77500. }
  77501. }
  77502. // Loading file from disk via input file or drag'n'drop
  77503. else {
  77504. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  77505. if (file) {
  77506. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  77507. }
  77508. else {
  77509. onError("Unable to find file named " + fileInfo.name);
  77510. }
  77511. }
  77512. return plugin;
  77513. };
  77514. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  77515. var url;
  77516. var name;
  77517. if (!sceneFilename) {
  77518. url = rootUrl;
  77519. name = BABYLON.Tools.GetFilename(rootUrl);
  77520. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  77521. }
  77522. else {
  77523. if (sceneFilename.substr(0, 1) === "/") {
  77524. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  77525. return null;
  77526. }
  77527. url = rootUrl + sceneFilename;
  77528. name = sceneFilename;
  77529. }
  77530. return {
  77531. url: url,
  77532. rootUrl: rootUrl,
  77533. name: name
  77534. };
  77535. };
  77536. // Public functions
  77537. /**
  77538. * Gets a plugin that can load the given extension
  77539. * @param extension defines the extension to load
  77540. * @returns a plugin or null if none works
  77541. */
  77542. SceneLoader.GetPluginForExtension = function (extension) {
  77543. return SceneLoader._getPluginForExtension(extension).plugin;
  77544. };
  77545. /**
  77546. * Gets a boolean indicating that the given extension can be loaded
  77547. * @param extension defines the extension to load
  77548. * @returns true if the extension is supported
  77549. */
  77550. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  77551. return !!SceneLoader._registeredPlugins[extension];
  77552. };
  77553. /**
  77554. * Adds a new plugin to the list of registered plugins
  77555. * @param plugin defines the plugin to add
  77556. */
  77557. SceneLoader.RegisterPlugin = function (plugin) {
  77558. if (typeof plugin.extensions === "string") {
  77559. var extension = plugin.extensions;
  77560. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  77561. plugin: plugin,
  77562. isBinary: false
  77563. };
  77564. }
  77565. else {
  77566. var extensions = plugin.extensions;
  77567. Object.keys(extensions).forEach(function (extension) {
  77568. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  77569. plugin: plugin,
  77570. isBinary: extensions[extension].isBinary
  77571. };
  77572. });
  77573. }
  77574. };
  77575. /**
  77576. * Import meshes into a scene
  77577. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  77578. * @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)
  77579. * @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)
  77580. * @param scene the instance of BABYLON.Scene to append to
  77581. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  77582. * @param onProgress a callback with a progress event for each file being loaded
  77583. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77584. * @param pluginExtension the extension used to determine the plugin
  77585. * @returns The loaded plugin
  77586. */
  77587. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  77588. if (sceneFilename === void 0) { sceneFilename = ""; }
  77589. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77590. if (onSuccess === void 0) { onSuccess = null; }
  77591. if (onProgress === void 0) { onProgress = null; }
  77592. if (onError === void 0) { onError = null; }
  77593. if (pluginExtension === void 0) { pluginExtension = null; }
  77594. if (!scene) {
  77595. BABYLON.Tools.Error("No scene available to import mesh to");
  77596. return null;
  77597. }
  77598. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  77599. if (!fileInfo) {
  77600. return null;
  77601. }
  77602. var loadingToken = {};
  77603. scene._addPendingData(loadingToken);
  77604. var disposeHandler = function () {
  77605. scene._removePendingData(loadingToken);
  77606. };
  77607. var errorHandler = function (message, exception) {
  77608. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  77609. if (onError) {
  77610. onError(scene, errorMessage, exception);
  77611. }
  77612. else {
  77613. BABYLON.Tools.Error(errorMessage);
  77614. // should the exception be thrown?
  77615. }
  77616. disposeHandler();
  77617. };
  77618. var progressHandler = onProgress ? function (event) {
  77619. try {
  77620. onProgress(event);
  77621. }
  77622. catch (e) {
  77623. errorHandler("Error in onProgress callback", e);
  77624. }
  77625. } : undefined;
  77626. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  77627. scene.importedMeshesFiles.push(fileInfo.url);
  77628. if (onSuccess) {
  77629. try {
  77630. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  77631. }
  77632. catch (e) {
  77633. errorHandler("Error in onSuccess callback", e);
  77634. }
  77635. }
  77636. scene._removePendingData(loadingToken);
  77637. };
  77638. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  77639. if (plugin.rewriteRootURL) {
  77640. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  77641. }
  77642. if (plugin.importMesh) {
  77643. var syncedPlugin = plugin;
  77644. var meshes = new Array();
  77645. var particleSystems = new Array();
  77646. var skeletons = new Array();
  77647. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  77648. return;
  77649. }
  77650. scene.loadingPluginName = plugin.name;
  77651. successHandler(meshes, particleSystems, skeletons, []);
  77652. }
  77653. else {
  77654. var asyncedPlugin = plugin;
  77655. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  77656. scene.loadingPluginName = plugin.name;
  77657. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  77658. }).catch(function (error) {
  77659. errorHandler(error.message, error);
  77660. });
  77661. }
  77662. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  77663. };
  77664. /**
  77665. * Import meshes into a scene
  77666. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  77667. * @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)
  77668. * @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)
  77669. * @param scene the instance of BABYLON.Scene to append to
  77670. * @param onProgress a callback with a progress event for each file being loaded
  77671. * @param pluginExtension the extension used to determine the plugin
  77672. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  77673. */
  77674. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  77675. if (sceneFilename === void 0) { sceneFilename = ""; }
  77676. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77677. if (onProgress === void 0) { onProgress = null; }
  77678. if (pluginExtension === void 0) { pluginExtension = null; }
  77679. return new Promise(function (resolve, reject) {
  77680. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  77681. resolve({
  77682. meshes: meshes,
  77683. particleSystems: particleSystems,
  77684. skeletons: skeletons,
  77685. animationGroups: animationGroups
  77686. });
  77687. }, onProgress, function (scene, message, exception) {
  77688. reject(exception || new Error(message));
  77689. }, pluginExtension);
  77690. });
  77691. };
  77692. /**
  77693. * Load a scene
  77694. * @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)
  77695. * @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)
  77696. * @param engine is the instance of BABYLON.Engine to use to create the scene
  77697. * @param onSuccess a callback with the scene when import succeeds
  77698. * @param onProgress a callback with a progress event for each file being loaded
  77699. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77700. * @param pluginExtension the extension used to determine the plugin
  77701. * @returns The loaded plugin
  77702. */
  77703. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  77704. if (onSuccess === void 0) { onSuccess = null; }
  77705. if (onProgress === void 0) { onProgress = null; }
  77706. if (onError === void 0) { onError = null; }
  77707. if (pluginExtension === void 0) { pluginExtension = null; }
  77708. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  77709. };
  77710. /**
  77711. * Load a scene
  77712. * @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)
  77713. * @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)
  77714. * @param engine is the instance of BABYLON.Engine to use to create the scene
  77715. * @param onProgress a callback with a progress event for each file being loaded
  77716. * @param pluginExtension the extension used to determine the plugin
  77717. * @returns The loaded scene
  77718. */
  77719. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  77720. if (onProgress === void 0) { onProgress = null; }
  77721. if (pluginExtension === void 0) { pluginExtension = null; }
  77722. return new Promise(function (resolve, reject) {
  77723. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  77724. resolve(scene);
  77725. }, onProgress, function (scene, message, exception) {
  77726. reject(exception || new Error(message));
  77727. }, pluginExtension);
  77728. });
  77729. };
  77730. /**
  77731. * Append a scene
  77732. * @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)
  77733. * @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)
  77734. * @param scene is the instance of BABYLON.Scene to append to
  77735. * @param onSuccess a callback with the scene when import succeeds
  77736. * @param onProgress a callback with a progress event for each file being loaded
  77737. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77738. * @param pluginExtension the extension used to determine the plugin
  77739. * @returns The loaded plugin
  77740. */
  77741. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  77742. if (sceneFilename === void 0) { sceneFilename = ""; }
  77743. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77744. if (onSuccess === void 0) { onSuccess = null; }
  77745. if (onProgress === void 0) { onProgress = null; }
  77746. if (onError === void 0) { onError = null; }
  77747. if (pluginExtension === void 0) { pluginExtension = null; }
  77748. if (!scene) {
  77749. BABYLON.Tools.Error("No scene available to append to");
  77750. return null;
  77751. }
  77752. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  77753. if (!fileInfo) {
  77754. return null;
  77755. }
  77756. if (SceneLoader.ShowLoadingScreen) {
  77757. scene.getEngine().displayLoadingUI();
  77758. }
  77759. var loadingToken = {};
  77760. scene._addPendingData(loadingToken);
  77761. var disposeHandler = function () {
  77762. scene._removePendingData(loadingToken);
  77763. scene.getEngine().hideLoadingUI();
  77764. };
  77765. var errorHandler = function (message, exception) {
  77766. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  77767. if (onError) {
  77768. onError(scene, errorMessage, exception);
  77769. }
  77770. else {
  77771. BABYLON.Tools.Error(errorMessage);
  77772. // should the exception be thrown?
  77773. }
  77774. disposeHandler();
  77775. };
  77776. var progressHandler = onProgress ? function (event) {
  77777. try {
  77778. onProgress(event);
  77779. }
  77780. catch (e) {
  77781. errorHandler("Error in onProgress callback", e);
  77782. }
  77783. } : undefined;
  77784. var successHandler = function () {
  77785. if (onSuccess) {
  77786. try {
  77787. onSuccess(scene);
  77788. }
  77789. catch (e) {
  77790. errorHandler("Error in onSuccess callback", e);
  77791. }
  77792. }
  77793. scene._removePendingData(loadingToken);
  77794. };
  77795. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  77796. if (plugin.load) {
  77797. var syncedPlugin = plugin;
  77798. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  77799. return;
  77800. }
  77801. scene.loadingPluginName = plugin.name;
  77802. successHandler();
  77803. }
  77804. else {
  77805. var asyncedPlugin = plugin;
  77806. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  77807. scene.loadingPluginName = plugin.name;
  77808. successHandler();
  77809. }).catch(function (error) {
  77810. errorHandler(error.message, error);
  77811. });
  77812. }
  77813. if (SceneLoader.ShowLoadingScreen) {
  77814. scene.executeWhenReady(function () {
  77815. scene.getEngine().hideLoadingUI();
  77816. });
  77817. }
  77818. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  77819. };
  77820. /**
  77821. * Append a scene
  77822. * @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)
  77823. * @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)
  77824. * @param scene is the instance of BABYLON.Scene to append to
  77825. * @param onProgress a callback with a progress event for each file being loaded
  77826. * @param pluginExtension the extension used to determine the plugin
  77827. * @returns The given scene
  77828. */
  77829. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  77830. if (sceneFilename === void 0) { sceneFilename = ""; }
  77831. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77832. if (onProgress === void 0) { onProgress = null; }
  77833. if (pluginExtension === void 0) { pluginExtension = null; }
  77834. return new Promise(function (resolve, reject) {
  77835. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  77836. resolve(scene);
  77837. }, onProgress, function (scene, message, exception) {
  77838. reject(exception || new Error(message));
  77839. }, pluginExtension);
  77840. });
  77841. };
  77842. /**
  77843. * Load a scene into an asset container
  77844. * @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)
  77845. * @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)
  77846. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  77847. * @param onSuccess a callback with the scene when import succeeds
  77848. * @param onProgress a callback with a progress event for each file being loaded
  77849. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77850. * @param pluginExtension the extension used to determine the plugin
  77851. * @returns The loaded plugin
  77852. */
  77853. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  77854. if (sceneFilename === void 0) { sceneFilename = ""; }
  77855. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77856. if (onSuccess === void 0) { onSuccess = null; }
  77857. if (onProgress === void 0) { onProgress = null; }
  77858. if (onError === void 0) { onError = null; }
  77859. if (pluginExtension === void 0) { pluginExtension = null; }
  77860. if (!scene) {
  77861. BABYLON.Tools.Error("No scene available to load asset container to");
  77862. return null;
  77863. }
  77864. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  77865. if (!fileInfo) {
  77866. return null;
  77867. }
  77868. var loadingToken = {};
  77869. scene._addPendingData(loadingToken);
  77870. var disposeHandler = function () {
  77871. scene._removePendingData(loadingToken);
  77872. };
  77873. var errorHandler = function (message, exception) {
  77874. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  77875. if (onError) {
  77876. onError(scene, errorMessage, exception);
  77877. }
  77878. else {
  77879. BABYLON.Tools.Error(errorMessage);
  77880. // should the exception be thrown?
  77881. }
  77882. disposeHandler();
  77883. };
  77884. var progressHandler = onProgress ? function (event) {
  77885. try {
  77886. onProgress(event);
  77887. }
  77888. catch (e) {
  77889. errorHandler("Error in onProgress callback", e);
  77890. }
  77891. } : undefined;
  77892. var successHandler = function (assets) {
  77893. if (onSuccess) {
  77894. try {
  77895. onSuccess(assets);
  77896. }
  77897. catch (e) {
  77898. errorHandler("Error in onSuccess callback", e);
  77899. }
  77900. }
  77901. scene._removePendingData(loadingToken);
  77902. };
  77903. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  77904. if (plugin.loadAssetContainer) {
  77905. var syncedPlugin = plugin;
  77906. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  77907. if (!assetContainer) {
  77908. return;
  77909. }
  77910. scene.loadingPluginName = plugin.name;
  77911. successHandler(assetContainer);
  77912. }
  77913. else if (plugin.loadAssetContainerAsync) {
  77914. var asyncedPlugin = plugin;
  77915. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  77916. scene.loadingPluginName = plugin.name;
  77917. successHandler(assetContainer);
  77918. }).catch(function (error) {
  77919. errorHandler(error.message, error);
  77920. });
  77921. }
  77922. else {
  77923. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  77924. }
  77925. if (SceneLoader.ShowLoadingScreen) {
  77926. scene.executeWhenReady(function () {
  77927. scene.getEngine().hideLoadingUI();
  77928. });
  77929. }
  77930. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  77931. };
  77932. /**
  77933. * Load a scene into an asset container
  77934. * @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)
  77935. * @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)
  77936. * @param scene is the instance of BABYLON.Scene to append to
  77937. * @param onProgress a callback with a progress event for each file being loaded
  77938. * @param pluginExtension the extension used to determine the plugin
  77939. * @returns The loaded asset container
  77940. */
  77941. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  77942. if (sceneFilename === void 0) { sceneFilename = ""; }
  77943. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77944. if (onProgress === void 0) { onProgress = null; }
  77945. if (pluginExtension === void 0) { pluginExtension = null; }
  77946. return new Promise(function (resolve, reject) {
  77947. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  77948. resolve(assetContainer);
  77949. }, onProgress, function (scene, message, exception) {
  77950. reject(exception || new Error(message));
  77951. }, pluginExtension);
  77952. });
  77953. };
  77954. // Flags
  77955. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  77956. SceneLoader._ShowLoadingScreen = true;
  77957. SceneLoader._CleanBoneMatrixWeights = false;
  77958. /**
  77959. * No logging while loading
  77960. */
  77961. SceneLoader.NO_LOGGING = 0;
  77962. /**
  77963. * Minimal logging while loading
  77964. */
  77965. SceneLoader.MINIMAL_LOGGING = 1;
  77966. /**
  77967. * Summary logging while loading
  77968. */
  77969. SceneLoader.SUMMARY_LOGGING = 2;
  77970. /**
  77971. * Detailled logging while loading
  77972. */
  77973. SceneLoader.DETAILED_LOGGING = 3;
  77974. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  77975. // Members
  77976. /**
  77977. * Event raised when a plugin is used to load a scene
  77978. */
  77979. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  77980. SceneLoader._registeredPlugins = {};
  77981. return SceneLoader;
  77982. }());
  77983. BABYLON.SceneLoader = SceneLoader;
  77984. })(BABYLON || (BABYLON = {}));
  77985. //# sourceMappingURL=babylon.sceneLoader.js.map
  77986. var BABYLON;
  77987. (function (BABYLON) {
  77988. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  77989. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  77990. var parsedMaterial = parsedData.materials[index];
  77991. if (parsedMaterial.id === id) {
  77992. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  77993. }
  77994. }
  77995. return null;
  77996. };
  77997. var isDescendantOf = function (mesh, names, hierarchyIds) {
  77998. for (var i in names) {
  77999. if (mesh.name === names[i]) {
  78000. hierarchyIds.push(mesh.id);
  78001. return true;
  78002. }
  78003. }
  78004. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  78005. hierarchyIds.push(mesh.id);
  78006. return true;
  78007. }
  78008. return false;
  78009. };
  78010. var logOperation = function (operation, producer) {
  78011. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  78012. };
  78013. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  78014. if (addToScene === void 0) { addToScene = false; }
  78015. var container = new BABYLON.AssetContainer(scene);
  78016. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78017. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78018. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78019. // and avoid problems with multiple concurrent .babylon loads.
  78020. var log = "importScene has failed JSON parse";
  78021. try {
  78022. var parsedData = JSON.parse(data);
  78023. log = "";
  78024. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  78025. var index;
  78026. var cache;
  78027. // Lights
  78028. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  78029. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  78030. var parsedLight = parsedData.lights[index];
  78031. var light = BABYLON.Light.Parse(parsedLight, scene);
  78032. if (light) {
  78033. container.lights.push(light);
  78034. log += (index === 0 ? "\n\tLights:" : "");
  78035. log += "\n\t\t" + light.toString(fullDetails);
  78036. }
  78037. }
  78038. }
  78039. // Animations
  78040. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  78041. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  78042. var parsedAnimation = parsedData.animations[index];
  78043. var animation = BABYLON.Animation.Parse(parsedAnimation);
  78044. scene.animations.push(animation);
  78045. container.animations.push(animation);
  78046. log += (index === 0 ? "\n\tAnimations:" : "");
  78047. log += "\n\t\t" + animation.toString(fullDetails);
  78048. }
  78049. }
  78050. // Materials
  78051. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  78052. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  78053. var parsedMaterial = parsedData.materials[index];
  78054. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  78055. container.materials.push(mat);
  78056. log += (index === 0 ? "\n\tMaterials:" : "");
  78057. log += "\n\t\t" + mat.toString(fullDetails);
  78058. }
  78059. }
  78060. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  78061. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  78062. var parsedMultiMaterial = parsedData.multiMaterials[index];
  78063. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  78064. container.multiMaterials.push(mmat);
  78065. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  78066. log += "\n\t\t" + mmat.toString(fullDetails);
  78067. }
  78068. }
  78069. // Morph targets
  78070. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  78071. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  78072. var managerData = _a[_i];
  78073. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  78074. }
  78075. }
  78076. // Skeletons
  78077. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  78078. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  78079. var parsedSkeleton = parsedData.skeletons[index];
  78080. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  78081. container.skeletons.push(skeleton);
  78082. log += (index === 0 ? "\n\tSkeletons:" : "");
  78083. log += "\n\t\t" + skeleton.toString(fullDetails);
  78084. }
  78085. }
  78086. // Geometries
  78087. var geometries = parsedData.geometries;
  78088. if (geometries !== undefined && geometries !== null) {
  78089. var addedGeometry = new Array();
  78090. // Boxes
  78091. var boxes = geometries.boxes;
  78092. if (boxes !== undefined && boxes !== null) {
  78093. for (index = 0, cache = boxes.length; index < cache; index++) {
  78094. var parsedBox = boxes[index];
  78095. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  78096. }
  78097. }
  78098. // Spheres
  78099. var spheres = geometries.spheres;
  78100. if (spheres !== undefined && spheres !== null) {
  78101. for (index = 0, cache = spheres.length; index < cache; index++) {
  78102. var parsedSphere = spheres[index];
  78103. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  78104. }
  78105. }
  78106. // Cylinders
  78107. var cylinders = geometries.cylinders;
  78108. if (cylinders !== undefined && cylinders !== null) {
  78109. for (index = 0, cache = cylinders.length; index < cache; index++) {
  78110. var parsedCylinder = cylinders[index];
  78111. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  78112. }
  78113. }
  78114. // Toruses
  78115. var toruses = geometries.toruses;
  78116. if (toruses !== undefined && toruses !== null) {
  78117. for (index = 0, cache = toruses.length; index < cache; index++) {
  78118. var parsedTorus = toruses[index];
  78119. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  78120. }
  78121. }
  78122. // Grounds
  78123. var grounds = geometries.grounds;
  78124. if (grounds !== undefined && grounds !== null) {
  78125. for (index = 0, cache = grounds.length; index < cache; index++) {
  78126. var parsedGround = grounds[index];
  78127. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  78128. }
  78129. }
  78130. // Planes
  78131. var planes = geometries.planes;
  78132. if (planes !== undefined && planes !== null) {
  78133. for (index = 0, cache = planes.length; index < cache; index++) {
  78134. var parsedPlane = planes[index];
  78135. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  78136. }
  78137. }
  78138. // TorusKnots
  78139. var torusKnots = geometries.torusKnots;
  78140. if (torusKnots !== undefined && torusKnots !== null) {
  78141. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  78142. var parsedTorusKnot = torusKnots[index];
  78143. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  78144. }
  78145. }
  78146. // VertexData
  78147. var vertexData = geometries.vertexData;
  78148. if (vertexData !== undefined && vertexData !== null) {
  78149. for (index = 0, cache = vertexData.length; index < cache; index++) {
  78150. var parsedVertexData = vertexData[index];
  78151. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  78152. }
  78153. }
  78154. addedGeometry.forEach(function (g) {
  78155. if (g) {
  78156. container.geometries.push(g);
  78157. }
  78158. });
  78159. }
  78160. // Transform nodes
  78161. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  78162. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  78163. var parsedTransformNode = parsedData.transformNodes[index];
  78164. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  78165. container.transformNodes.push(node);
  78166. }
  78167. }
  78168. // Meshes
  78169. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  78170. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  78171. var parsedMesh = parsedData.meshes[index];
  78172. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  78173. container.meshes.push(mesh);
  78174. log += (index === 0 ? "\n\tMeshes:" : "");
  78175. log += "\n\t\t" + mesh.toString(fullDetails);
  78176. }
  78177. }
  78178. // Cameras
  78179. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  78180. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  78181. var parsedCamera = parsedData.cameras[index];
  78182. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  78183. container.cameras.push(camera);
  78184. log += (index === 0 ? "\n\tCameras:" : "");
  78185. log += "\n\t\t" + camera.toString(fullDetails);
  78186. }
  78187. }
  78188. // Animation Groups
  78189. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  78190. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  78191. var parsedAnimationGroup = parsedData.animationGroups[index];
  78192. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  78193. container.animationGroups.push(animationGroup);
  78194. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  78195. log += "\n\t\t" + animationGroup.toString(fullDetails);
  78196. }
  78197. }
  78198. // Browsing all the graph to connect the dots
  78199. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  78200. var camera = scene.cameras[index];
  78201. if (camera._waitingParentId) {
  78202. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  78203. camera._waitingParentId = null;
  78204. }
  78205. }
  78206. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  78207. var light_1 = scene.lights[index];
  78208. if (light_1 && light_1._waitingParentId) {
  78209. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  78210. light_1._waitingParentId = null;
  78211. }
  78212. }
  78213. // Connect parents & children and parse actions
  78214. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  78215. var transformNode = scene.transformNodes[index];
  78216. if (transformNode._waitingParentId) {
  78217. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  78218. transformNode._waitingParentId = null;
  78219. }
  78220. }
  78221. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78222. var mesh = scene.meshes[index];
  78223. if (mesh._waitingParentId) {
  78224. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  78225. mesh._waitingParentId = null;
  78226. }
  78227. }
  78228. // freeze world matrix application
  78229. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78230. var currentMesh = scene.meshes[index];
  78231. if (currentMesh._waitingFreezeWorldMatrix) {
  78232. currentMesh.freezeWorldMatrix();
  78233. currentMesh._waitingFreezeWorldMatrix = null;
  78234. }
  78235. else {
  78236. currentMesh.computeWorldMatrix(true);
  78237. }
  78238. }
  78239. // Lights exclusions / inclusions
  78240. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  78241. var light_2 = scene.lights[index];
  78242. // Excluded check
  78243. if (light_2._excludedMeshesIds.length > 0) {
  78244. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  78245. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  78246. if (excludedMesh) {
  78247. light_2.excludedMeshes.push(excludedMesh);
  78248. }
  78249. }
  78250. light_2._excludedMeshesIds = [];
  78251. }
  78252. // Included check
  78253. if (light_2._includedOnlyMeshesIds.length > 0) {
  78254. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  78255. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  78256. if (includedOnlyMesh) {
  78257. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  78258. }
  78259. }
  78260. light_2._includedOnlyMeshesIds = [];
  78261. }
  78262. }
  78263. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  78264. // Actions (scene) Done last as it can access other objects.
  78265. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78266. var mesh = scene.meshes[index];
  78267. if (mesh._waitingActions) {
  78268. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  78269. mesh._waitingActions = null;
  78270. }
  78271. }
  78272. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  78273. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  78274. }
  78275. if (!addToScene) {
  78276. container.removeAllFromScene();
  78277. }
  78278. }
  78279. catch (err) {
  78280. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  78281. if (onError) {
  78282. onError(msg, err);
  78283. }
  78284. else {
  78285. BABYLON.Tools.Log(msg);
  78286. throw err;
  78287. }
  78288. }
  78289. finally {
  78290. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78291. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78292. }
  78293. }
  78294. return container;
  78295. };
  78296. BABYLON.SceneLoader.RegisterPlugin({
  78297. name: "babylon.js",
  78298. extensions: ".babylon",
  78299. canDirectLoad: function (data) {
  78300. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  78301. return true;
  78302. }
  78303. return false;
  78304. },
  78305. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  78306. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78307. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78308. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78309. // and avoid problems with multiple concurrent .babylon loads.
  78310. var log = "importMesh has failed JSON parse";
  78311. try {
  78312. var parsedData = JSON.parse(data);
  78313. log = "";
  78314. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  78315. if (!meshesNames) {
  78316. meshesNames = null;
  78317. }
  78318. else if (!Array.isArray(meshesNames)) {
  78319. meshesNames = [meshesNames];
  78320. }
  78321. var hierarchyIds = new Array();
  78322. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  78323. var loadedSkeletonsIds = [];
  78324. var loadedMaterialsIds = [];
  78325. var index;
  78326. var cache;
  78327. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  78328. var parsedMesh = parsedData.meshes[index];
  78329. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  78330. if (meshesNames !== null) {
  78331. // Remove found mesh name from list.
  78332. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  78333. }
  78334. //Geometry?
  78335. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  78336. //does the file contain geometries?
  78337. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  78338. //find the correct geometry and add it to the scene
  78339. var found = false;
  78340. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  78341. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  78342. return;
  78343. }
  78344. else {
  78345. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  78346. if (parsedGeometryData.id === parsedMesh.geometryId) {
  78347. switch (geometryType) {
  78348. case "boxes":
  78349. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  78350. break;
  78351. case "spheres":
  78352. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  78353. break;
  78354. case "cylinders":
  78355. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  78356. break;
  78357. case "toruses":
  78358. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  78359. break;
  78360. case "grounds":
  78361. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  78362. break;
  78363. case "planes":
  78364. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  78365. break;
  78366. case "torusKnots":
  78367. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  78368. break;
  78369. case "vertexData":
  78370. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  78371. break;
  78372. }
  78373. found = true;
  78374. }
  78375. });
  78376. }
  78377. });
  78378. if (found === false) {
  78379. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  78380. }
  78381. }
  78382. }
  78383. // Material ?
  78384. if (parsedMesh.materialId) {
  78385. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  78386. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  78387. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  78388. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  78389. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  78390. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  78391. var subMatId = parsedMultiMaterial.materials[matIndex];
  78392. loadedMaterialsIds.push(subMatId);
  78393. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  78394. if (mat) {
  78395. log += "\n\tMaterial " + mat.toString(fullDetails);
  78396. }
  78397. }
  78398. loadedMaterialsIds.push(parsedMultiMaterial.id);
  78399. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  78400. if (mmat) {
  78401. materialFound = true;
  78402. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  78403. }
  78404. break;
  78405. }
  78406. }
  78407. }
  78408. if (materialFound === false) {
  78409. loadedMaterialsIds.push(parsedMesh.materialId);
  78410. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  78411. if (!mat) {
  78412. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  78413. }
  78414. else {
  78415. log += "\n\tMaterial " + mat.toString(fullDetails);
  78416. }
  78417. }
  78418. }
  78419. // Skeleton ?
  78420. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  78421. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  78422. if (skeletonAlreadyLoaded === false) {
  78423. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  78424. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  78425. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  78426. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  78427. skeletons.push(skeleton);
  78428. loadedSkeletonsIds.push(parsedSkeleton.id);
  78429. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  78430. }
  78431. }
  78432. }
  78433. }
  78434. // Morph targets ?
  78435. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  78436. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  78437. var managerData = _a[_i];
  78438. BABYLON.MorphTargetManager.Parse(managerData, scene);
  78439. }
  78440. }
  78441. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  78442. meshes.push(mesh);
  78443. log += "\n\tMesh " + mesh.toString(fullDetails);
  78444. }
  78445. }
  78446. // Connecting parents
  78447. var currentMesh;
  78448. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78449. currentMesh = scene.meshes[index];
  78450. if (currentMesh._waitingParentId) {
  78451. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  78452. currentMesh._waitingParentId = null;
  78453. }
  78454. }
  78455. // freeze and compute world matrix application
  78456. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78457. currentMesh = scene.meshes[index];
  78458. if (currentMesh._waitingFreezeWorldMatrix) {
  78459. currentMesh.freezeWorldMatrix();
  78460. currentMesh._waitingFreezeWorldMatrix = null;
  78461. }
  78462. else {
  78463. currentMesh.computeWorldMatrix(true);
  78464. }
  78465. }
  78466. }
  78467. // Particles
  78468. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  78469. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  78470. if (parser) {
  78471. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  78472. var parsedParticleSystem = parsedData.particleSystems[index];
  78473. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  78474. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  78475. }
  78476. }
  78477. }
  78478. }
  78479. return true;
  78480. }
  78481. catch (err) {
  78482. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  78483. if (onError) {
  78484. onError(msg, err);
  78485. }
  78486. else {
  78487. BABYLON.Tools.Log(msg);
  78488. throw err;
  78489. }
  78490. }
  78491. finally {
  78492. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78493. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78494. }
  78495. }
  78496. return false;
  78497. },
  78498. load: function (scene, data, rootUrl, onError) {
  78499. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78500. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78501. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78502. // and avoid problems with multiple concurrent .babylon loads.
  78503. var log = "importScene has failed JSON parse";
  78504. try {
  78505. var parsedData = JSON.parse(data);
  78506. log = "";
  78507. // Scene
  78508. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  78509. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  78510. }
  78511. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  78512. scene.autoClear = parsedData.autoClear;
  78513. }
  78514. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  78515. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  78516. }
  78517. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  78518. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  78519. }
  78520. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  78521. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  78522. }
  78523. // Fog
  78524. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  78525. scene.fogMode = parsedData.fogMode;
  78526. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  78527. scene.fogStart = parsedData.fogStart;
  78528. scene.fogEnd = parsedData.fogEnd;
  78529. scene.fogDensity = parsedData.fogDensity;
  78530. log += "\tFog mode for scene: ";
  78531. switch (scene.fogMode) {
  78532. // getters not compiling, so using hardcoded
  78533. case 1:
  78534. log += "exp\n";
  78535. break;
  78536. case 2:
  78537. log += "exp2\n";
  78538. break;
  78539. case 3:
  78540. log += "linear\n";
  78541. break;
  78542. }
  78543. }
  78544. //Physics
  78545. if (parsedData.physicsEnabled) {
  78546. var physicsPlugin;
  78547. if (parsedData.physicsEngine === "cannon") {
  78548. physicsPlugin = new BABYLON.CannonJSPlugin();
  78549. }
  78550. else if (parsedData.physicsEngine === "oimo") {
  78551. physicsPlugin = new BABYLON.OimoJSPlugin();
  78552. }
  78553. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  78554. //else - default engine, which is currently oimo
  78555. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  78556. scene.enablePhysics(physicsGravity, physicsPlugin);
  78557. }
  78558. // Metadata
  78559. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  78560. scene.metadata = parsedData.metadata;
  78561. }
  78562. //collisions, if defined. otherwise, default is true
  78563. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  78564. scene.collisionsEnabled = parsedData.collisionsEnabled;
  78565. }
  78566. scene.workerCollisions = !!parsedData.workerCollisions;
  78567. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  78568. if (!container) {
  78569. return false;
  78570. }
  78571. if (parsedData.autoAnimate) {
  78572. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  78573. }
  78574. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  78575. scene.setActiveCameraByID(parsedData.activeCameraID);
  78576. }
  78577. // Environment texture
  78578. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  78579. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  78580. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  78581. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  78582. if (parsedData.environmentTextureRotationY) {
  78583. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  78584. }
  78585. scene.environmentTexture = hdrTexture;
  78586. }
  78587. else {
  78588. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  78589. if (parsedData.environmentTextureRotationY) {
  78590. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  78591. }
  78592. scene.environmentTexture = cubeTexture;
  78593. }
  78594. if (parsedData.createDefaultSkybox === true) {
  78595. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  78596. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  78597. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  78598. }
  78599. }
  78600. // Finish
  78601. return true;
  78602. }
  78603. catch (err) {
  78604. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  78605. if (onError) {
  78606. onError(msg, err);
  78607. }
  78608. else {
  78609. BABYLON.Tools.Log(msg);
  78610. throw err;
  78611. }
  78612. }
  78613. finally {
  78614. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78615. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78616. }
  78617. }
  78618. return false;
  78619. },
  78620. loadAssetContainer: function (scene, data, rootUrl, onError) {
  78621. var container = loadAssetContainer(scene, data, rootUrl, onError);
  78622. return container;
  78623. }
  78624. });
  78625. })(BABYLON || (BABYLON = {}));
  78626. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  78627. var BABYLON;
  78628. (function (BABYLON) {
  78629. /**
  78630. * Class used to help managing file picking and drag'n'drop
  78631. */
  78632. var FilesInput = /** @class */ (function () {
  78633. /**
  78634. * Creates a new FilesInput
  78635. * @param engine defines the rendering engine
  78636. * @param scene defines the hosting scene
  78637. * @param sceneLoadedCallback callback called when scene is loaded
  78638. * @param progressCallback callback called to track progress
  78639. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  78640. * @param textureLoadingCallback callback called when a texture is loading
  78641. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  78642. * @param onReloadCallback callback called when a reload is requested
  78643. * @param errorCallback callback call if an error occurs
  78644. */
  78645. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  78646. /**
  78647. * Callback called when a file is processed
  78648. */
  78649. this.onProcessFileCallback = function () { return true; };
  78650. this._engine = engine;
  78651. this._currentScene = scene;
  78652. this._sceneLoadedCallback = sceneLoadedCallback;
  78653. this._progressCallback = progressCallback;
  78654. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  78655. this._textureLoadingCallback = textureLoadingCallback;
  78656. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  78657. this._onReloadCallback = onReloadCallback;
  78658. this._errorCallback = errorCallback;
  78659. }
  78660. /**
  78661. * Calls this function to listen to drag'n'drop events on a specific DOM element
  78662. * @param elementToMonitor defines the DOM element to track
  78663. */
  78664. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  78665. var _this = this;
  78666. if (elementToMonitor) {
  78667. this._elementToMonitor = elementToMonitor;
  78668. this._dragEnterHandler = function (e) { _this.drag(e); };
  78669. this._dragOverHandler = function (e) { _this.drag(e); };
  78670. this._dropHandler = function (e) { _this.drop(e); };
  78671. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  78672. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  78673. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  78674. }
  78675. };
  78676. /**
  78677. * Release all associated resources
  78678. */
  78679. FilesInput.prototype.dispose = function () {
  78680. if (!this._elementToMonitor) {
  78681. return;
  78682. }
  78683. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  78684. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  78685. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  78686. };
  78687. FilesInput.prototype.renderFunction = function () {
  78688. if (this._additionalRenderLoopLogicCallback) {
  78689. this._additionalRenderLoopLogicCallback();
  78690. }
  78691. if (this._currentScene) {
  78692. if (this._textureLoadingCallback) {
  78693. var remaining = this._currentScene.getWaitingItemsCount();
  78694. if (remaining > 0) {
  78695. this._textureLoadingCallback(remaining);
  78696. }
  78697. }
  78698. this._currentScene.render();
  78699. }
  78700. };
  78701. FilesInput.prototype.drag = function (e) {
  78702. e.stopPropagation();
  78703. e.preventDefault();
  78704. };
  78705. FilesInput.prototype.drop = function (eventDrop) {
  78706. eventDrop.stopPropagation();
  78707. eventDrop.preventDefault();
  78708. this.loadFiles(eventDrop);
  78709. };
  78710. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  78711. var _this = this;
  78712. var reader = folder.createReader();
  78713. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  78714. reader.readEntries(function (entries) {
  78715. remaining.count += entries.length;
  78716. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  78717. var entry = entries_1[_i];
  78718. if (entry.isFile) {
  78719. entry.file(function (file) {
  78720. file.correctName = relativePath + file.name;
  78721. files.push(file);
  78722. if (--remaining.count === 0) {
  78723. callback();
  78724. }
  78725. });
  78726. }
  78727. else if (entry.isDirectory) {
  78728. _this._traverseFolder(entry, files, remaining, callback);
  78729. }
  78730. }
  78731. if (--remaining.count) {
  78732. callback();
  78733. }
  78734. });
  78735. };
  78736. FilesInput.prototype._processFiles = function (files) {
  78737. for (var i = 0; i < files.length; i++) {
  78738. var name = files[i].correctName.toLowerCase();
  78739. var extension = name.split('.').pop();
  78740. if (!this.onProcessFileCallback(files[i], name, extension)) {
  78741. continue;
  78742. }
  78743. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  78744. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  78745. this._sceneFileToLoad = files[i];
  78746. }
  78747. FilesInput.FilesToLoad[name] = files[i];
  78748. }
  78749. };
  78750. /**
  78751. * Load files from a drop event
  78752. * @param event defines the drop event to use as source
  78753. */
  78754. FilesInput.prototype.loadFiles = function (event) {
  78755. var _this = this;
  78756. // Handling data transfer via drag'n'drop
  78757. if (event && event.dataTransfer && event.dataTransfer.files) {
  78758. this._filesToLoad = event.dataTransfer.files;
  78759. }
  78760. // Handling files from input files
  78761. if (event && event.target && event.target.files) {
  78762. this._filesToLoad = event.target.files;
  78763. }
  78764. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  78765. return;
  78766. }
  78767. if (this._startingProcessingFilesCallback) {
  78768. this._startingProcessingFilesCallback(this._filesToLoad);
  78769. }
  78770. if (this._filesToLoad && this._filesToLoad.length > 0) {
  78771. var files_1 = new Array();
  78772. var folders = [];
  78773. var items = event.dataTransfer ? event.dataTransfer.items : null;
  78774. for (var i = 0; i < this._filesToLoad.length; i++) {
  78775. var fileToLoad = this._filesToLoad[i];
  78776. var name_1 = fileToLoad.name.toLowerCase();
  78777. var entry = void 0;
  78778. fileToLoad.correctName = name_1;
  78779. if (items) {
  78780. var item = items[i];
  78781. if (item.getAsEntry) {
  78782. entry = item.getAsEntry();
  78783. }
  78784. else if (item.webkitGetAsEntry) {
  78785. entry = item.webkitGetAsEntry();
  78786. }
  78787. }
  78788. if (!entry) {
  78789. files_1.push(fileToLoad);
  78790. }
  78791. else {
  78792. if (entry.isDirectory) {
  78793. folders.push(entry);
  78794. }
  78795. else {
  78796. files_1.push(fileToLoad);
  78797. }
  78798. }
  78799. }
  78800. if (folders.length === 0) {
  78801. this._processFiles(files_1);
  78802. this._processReload();
  78803. }
  78804. else {
  78805. var remaining = { count: folders.length };
  78806. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  78807. var folder = folders_1[_i];
  78808. this._traverseFolder(folder, files_1, remaining, function () {
  78809. _this._processFiles(files_1);
  78810. if (remaining.count === 0) {
  78811. _this._processReload();
  78812. }
  78813. });
  78814. }
  78815. }
  78816. }
  78817. };
  78818. FilesInput.prototype._processReload = function () {
  78819. if (this._onReloadCallback) {
  78820. this._onReloadCallback(this._sceneFileToLoad);
  78821. }
  78822. else {
  78823. this.reload();
  78824. }
  78825. };
  78826. /**
  78827. * Reload the current scene from the loaded files
  78828. */
  78829. FilesInput.prototype.reload = function () {
  78830. var _this = this;
  78831. // If a scene file has been provided
  78832. if (this._sceneFileToLoad) {
  78833. if (this._currentScene) {
  78834. if (BABYLON.Tools.errorsCount > 0) {
  78835. BABYLON.Tools.ClearLogCache();
  78836. }
  78837. this._engine.stopRenderLoop();
  78838. }
  78839. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  78840. if (_this._progressCallback) {
  78841. _this._progressCallback(progress);
  78842. }
  78843. }).then(function (scene) {
  78844. if (_this._currentScene) {
  78845. _this._currentScene.dispose();
  78846. }
  78847. _this._currentScene = scene;
  78848. if (_this._sceneLoadedCallback) {
  78849. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  78850. }
  78851. // Wait for textures and shaders to be ready
  78852. _this._currentScene.executeWhenReady(function () {
  78853. _this._engine.runRenderLoop(function () {
  78854. _this.renderFunction();
  78855. });
  78856. });
  78857. }).catch(function (error) {
  78858. if (_this._errorCallback) {
  78859. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  78860. }
  78861. });
  78862. }
  78863. else {
  78864. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  78865. }
  78866. };
  78867. /**
  78868. * List of files ready to be loaded
  78869. */
  78870. FilesInput.FilesToLoad = {};
  78871. return FilesInput;
  78872. }());
  78873. BABYLON.FilesInput = FilesInput;
  78874. })(BABYLON || (BABYLON = {}));
  78875. //# sourceMappingURL=babylon.filesInput.js.map
  78876. var BABYLON;
  78877. (function (BABYLON) {
  78878. /**
  78879. * Class used to store custom tags
  78880. */
  78881. var Tags = /** @class */ (function () {
  78882. function Tags() {
  78883. }
  78884. /**
  78885. * Adds support for tags on the given object
  78886. * @param obj defines the object to use
  78887. */
  78888. Tags.EnableFor = function (obj) {
  78889. obj._tags = obj._tags || {};
  78890. obj.hasTags = function () {
  78891. return Tags.HasTags(obj);
  78892. };
  78893. obj.addTags = function (tagsString) {
  78894. return Tags.AddTagsTo(obj, tagsString);
  78895. };
  78896. obj.removeTags = function (tagsString) {
  78897. return Tags.RemoveTagsFrom(obj, tagsString);
  78898. };
  78899. obj.matchesTagsQuery = function (tagsQuery) {
  78900. return Tags.MatchesQuery(obj, tagsQuery);
  78901. };
  78902. };
  78903. /**
  78904. * Removes tags support
  78905. * @param obj defines the object to use
  78906. */
  78907. Tags.DisableFor = function (obj) {
  78908. delete obj._tags;
  78909. delete obj.hasTags;
  78910. delete obj.addTags;
  78911. delete obj.removeTags;
  78912. delete obj.matchesTagsQuery;
  78913. };
  78914. /**
  78915. * Gets a boolean indicating if the given object has tags
  78916. * @param obj defines the object to use
  78917. * @returns a boolean
  78918. */
  78919. Tags.HasTags = function (obj) {
  78920. if (!obj._tags) {
  78921. return false;
  78922. }
  78923. return !BABYLON.Tools.IsEmpty(obj._tags);
  78924. };
  78925. /**
  78926. * Gets the tags available on a given object
  78927. * @param obj defines the object to use
  78928. * @param asString defines if the tags must be returned as a string instead of an array of strings
  78929. * @returns the tags
  78930. */
  78931. Tags.GetTags = function (obj, asString) {
  78932. if (asString === void 0) { asString = true; }
  78933. if (!obj._tags) {
  78934. return null;
  78935. }
  78936. if (asString) {
  78937. var tagsArray = [];
  78938. for (var tag in obj._tags) {
  78939. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  78940. tagsArray.push(tag);
  78941. }
  78942. }
  78943. return tagsArray.join(" ");
  78944. }
  78945. else {
  78946. return obj._tags;
  78947. }
  78948. };
  78949. /**
  78950. * Adds tags to an object
  78951. * @param obj defines the object to use
  78952. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  78953. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  78954. */
  78955. Tags.AddTagsTo = function (obj, tagsString) {
  78956. if (!tagsString) {
  78957. return;
  78958. }
  78959. if (typeof tagsString !== "string") {
  78960. return;
  78961. }
  78962. var tags = tagsString.split(" ");
  78963. tags.forEach(function (tag, index, array) {
  78964. Tags._AddTagTo(obj, tag);
  78965. });
  78966. };
  78967. /**
  78968. * @hidden
  78969. */
  78970. Tags._AddTagTo = function (obj, tag) {
  78971. tag = tag.trim();
  78972. if (tag === "" || tag === "true" || tag === "false") {
  78973. return;
  78974. }
  78975. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  78976. return;
  78977. }
  78978. Tags.EnableFor(obj);
  78979. obj._tags[tag] = true;
  78980. };
  78981. /**
  78982. * Removes specific tags from a specific object
  78983. * @param obj defines the object to use
  78984. * @param tagsString defines the tags to remove
  78985. */
  78986. Tags.RemoveTagsFrom = function (obj, tagsString) {
  78987. if (!Tags.HasTags(obj)) {
  78988. return;
  78989. }
  78990. var tags = tagsString.split(" ");
  78991. for (var t in tags) {
  78992. Tags._RemoveTagFrom(obj, tags[t]);
  78993. }
  78994. };
  78995. /**
  78996. * @hidden
  78997. */
  78998. Tags._RemoveTagFrom = function (obj, tag) {
  78999. delete obj._tags[tag];
  79000. };
  79001. /**
  79002. * Defines if tags hosted on an object match a given query
  79003. * @param obj defines the object to use
  79004. * @param tagsQuery defines the tag query
  79005. * @returns a boolean
  79006. */
  79007. Tags.MatchesQuery = function (obj, tagsQuery) {
  79008. if (tagsQuery === undefined) {
  79009. return true;
  79010. }
  79011. if (tagsQuery === "") {
  79012. return Tags.HasTags(obj);
  79013. }
  79014. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  79015. };
  79016. return Tags;
  79017. }());
  79018. BABYLON.Tags = Tags;
  79019. })(BABYLON || (BABYLON = {}));
  79020. //# sourceMappingURL=babylon.tags.js.map
  79021. var BABYLON;
  79022. (function (BABYLON) {
  79023. /**
  79024. * Class used to evalaute queries containing `and` and `or` operators
  79025. */
  79026. var AndOrNotEvaluator = /** @class */ (function () {
  79027. function AndOrNotEvaluator() {
  79028. }
  79029. /**
  79030. * Evaluate a query
  79031. * @param query defines the query to evaluate
  79032. * @param evaluateCallback defines the callback used to filter result
  79033. * @returns true if the query matches
  79034. */
  79035. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  79036. if (!query.match(/\([^\(\)]*\)/g)) {
  79037. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  79038. }
  79039. else {
  79040. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  79041. // remove parenthesis
  79042. r = r.slice(1, r.length - 1);
  79043. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  79044. });
  79045. }
  79046. if (query === "true") {
  79047. return true;
  79048. }
  79049. if (query === "false") {
  79050. return false;
  79051. }
  79052. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  79053. };
  79054. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  79055. evaluateCallback = evaluateCallback || (function (r) {
  79056. return r === "true" ? true : false;
  79057. });
  79058. var result;
  79059. var or = parenthesisContent.split("||");
  79060. for (var i in or) {
  79061. if (or.hasOwnProperty(i)) {
  79062. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  79063. var and = ori.split("&&");
  79064. if (and.length > 1) {
  79065. for (var j = 0; j < and.length; ++j) {
  79066. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  79067. if (andj !== "true" && andj !== "false") {
  79068. if (andj[0] === "!") {
  79069. result = !evaluateCallback(andj.substring(1));
  79070. }
  79071. else {
  79072. result = evaluateCallback(andj);
  79073. }
  79074. }
  79075. else {
  79076. result = andj === "true" ? true : false;
  79077. }
  79078. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  79079. ori = "false";
  79080. break;
  79081. }
  79082. }
  79083. }
  79084. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  79085. result = true;
  79086. break;
  79087. }
  79088. // result equals false (or undefined)
  79089. if (ori !== "true" && ori !== "false") {
  79090. if (ori[0] === "!") {
  79091. result = !evaluateCallback(ori.substring(1));
  79092. }
  79093. else {
  79094. result = evaluateCallback(ori);
  79095. }
  79096. }
  79097. else {
  79098. result = ori === "true" ? true : false;
  79099. }
  79100. }
  79101. }
  79102. // the whole parenthesis scope is replaced by 'true' or 'false'
  79103. return result ? "true" : "false";
  79104. };
  79105. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  79106. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  79107. // remove whitespaces
  79108. r = r.replace(/[\s]/g, function () { return ""; });
  79109. return r.length % 2 ? "!" : "";
  79110. });
  79111. booleanString = booleanString.trim();
  79112. if (booleanString === "!true") {
  79113. booleanString = "false";
  79114. }
  79115. else if (booleanString === "!false") {
  79116. booleanString = "true";
  79117. }
  79118. return booleanString;
  79119. };
  79120. return AndOrNotEvaluator;
  79121. }());
  79122. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  79123. })(BABYLON || (BABYLON = {}));
  79124. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  79125. var BABYLON;
  79126. (function (BABYLON) {
  79127. // Sets the default offline provider to Babylon.js
  79128. BABYLON.Engine.OfflineProviderFactory = function (urlToScene, callbackManifestChecked, disableManifestCheck) {
  79129. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  79130. return new Database(urlToScene, callbackManifestChecked, disableManifestCheck);
  79131. };
  79132. /**
  79133. * Class used to enable access to IndexedDB
  79134. * @see http://doc.babylonjs.com/how_to/caching_resources_in_indexeddb
  79135. */
  79136. var Database = /** @class */ (function () {
  79137. /**
  79138. * Creates a new Database
  79139. * @param urlToScene defines the url to load the scene
  79140. * @param callbackManifestChecked defines the callback to use when manifest is checked
  79141. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  79142. */
  79143. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  79144. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  79145. var _this = this;
  79146. // Handling various flavors of prefixed version of IndexedDB
  79147. this._idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  79148. this._callbackManifestChecked = callbackManifestChecked;
  79149. this._currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  79150. this._db = null;
  79151. this._enableSceneOffline = false;
  79152. this._enableTexturesOffline = false;
  79153. this._manifestVersionFound = 0;
  79154. this._mustUpdateRessources = false;
  79155. this._hasReachedQuota = false;
  79156. if (!Database.IDBStorageEnabled) {
  79157. this._callbackManifestChecked(true);
  79158. }
  79159. else {
  79160. if (disableManifestCheck) {
  79161. this._enableSceneOffline = true;
  79162. this._enableTexturesOffline = true;
  79163. this._manifestVersionFound = 1;
  79164. BABYLON.Tools.SetImmediate(function () {
  79165. _this._callbackManifestChecked(true);
  79166. });
  79167. }
  79168. else {
  79169. this._checkManifestFile();
  79170. }
  79171. }
  79172. }
  79173. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  79174. /**
  79175. * Gets a boolean indicating if scene must be saved in the database
  79176. */
  79177. get: function () {
  79178. return this._enableSceneOffline;
  79179. },
  79180. enumerable: true,
  79181. configurable: true
  79182. });
  79183. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  79184. /**
  79185. * Gets a boolean indicating if textures must be saved in the database
  79186. */
  79187. get: function () {
  79188. return this._enableTexturesOffline;
  79189. },
  79190. enumerable: true,
  79191. configurable: true
  79192. });
  79193. Database.prototype._checkManifestFile = function () {
  79194. var _this = this;
  79195. var noManifestFile = function () {
  79196. _this._enableSceneOffline = false;
  79197. _this._enableTexturesOffline = false;
  79198. _this._callbackManifestChecked(false);
  79199. };
  79200. var timeStampUsed = false;
  79201. var manifestURL = this._currentSceneUrl + ".manifest";
  79202. var xhr = new XMLHttpRequest();
  79203. if (navigator.onLine) {
  79204. // Adding a timestamp to by-pass browsers' cache
  79205. timeStampUsed = true;
  79206. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  79207. }
  79208. xhr.open("GET", manifestURL, true);
  79209. xhr.addEventListener("load", function () {
  79210. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  79211. try {
  79212. var manifestFile = JSON.parse(xhr.response);
  79213. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  79214. _this._enableTexturesOffline = manifestFile.enableTexturesOffline && Database.IsUASupportingBlobStorage;
  79215. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  79216. _this._manifestVersionFound = manifestFile.version;
  79217. }
  79218. if (_this._callbackManifestChecked) {
  79219. _this._callbackManifestChecked(true);
  79220. }
  79221. }
  79222. catch (ex) {
  79223. noManifestFile();
  79224. }
  79225. }
  79226. else {
  79227. noManifestFile();
  79228. }
  79229. }, false);
  79230. xhr.addEventListener("error", function (event) {
  79231. if (timeStampUsed) {
  79232. timeStampUsed = false;
  79233. // Let's retry without the timeStamp
  79234. // It could fail when coupled with HTML5 Offline API
  79235. var retryManifestURL = _this._currentSceneUrl + ".manifest";
  79236. xhr.open("GET", retryManifestURL, true);
  79237. xhr.send();
  79238. }
  79239. else {
  79240. noManifestFile();
  79241. }
  79242. }, false);
  79243. try {
  79244. xhr.send();
  79245. }
  79246. catch (ex) {
  79247. BABYLON.Tools.Error("Error on XHR send request.");
  79248. this._callbackManifestChecked(false);
  79249. }
  79250. };
  79251. /**
  79252. * Open the database and make it available
  79253. * @param successCallback defines the callback to call on success
  79254. * @param errorCallback defines the callback to call on error
  79255. */
  79256. Database.prototype.open = function (successCallback, errorCallback) {
  79257. var _this = this;
  79258. var handleError = function () {
  79259. _this._isSupported = false;
  79260. if (errorCallback) {
  79261. errorCallback();
  79262. }
  79263. };
  79264. if (!this._idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  79265. // Your browser doesn't support IndexedDB
  79266. this._isSupported = false;
  79267. if (errorCallback) {
  79268. errorCallback();
  79269. }
  79270. }
  79271. else {
  79272. // If the DB hasn't been opened or created yet
  79273. if (!this._db) {
  79274. this._hasReachedQuota = false;
  79275. this._isSupported = true;
  79276. var request = this._idbFactory.open("babylonjs", 1);
  79277. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  79278. request.onerror = function (event) {
  79279. handleError();
  79280. };
  79281. // executes when a version change transaction cannot complete due to other active transactions
  79282. request.onblocked = function (event) {
  79283. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  79284. handleError();
  79285. };
  79286. // DB has been opened successfully
  79287. request.onsuccess = function (event) {
  79288. _this._db = request.result;
  79289. successCallback();
  79290. };
  79291. // Initialization of the DB. Creating Scenes & Textures stores
  79292. request.onupgradeneeded = function (event) {
  79293. _this._db = (event.target).result;
  79294. if (_this._db) {
  79295. try {
  79296. _this._db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  79297. _this._db.createObjectStore("versions", { keyPath: "sceneUrl" });
  79298. _this._db.createObjectStore("textures", { keyPath: "textureUrl" });
  79299. }
  79300. catch (ex) {
  79301. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  79302. handleError();
  79303. }
  79304. }
  79305. };
  79306. }
  79307. // DB has already been created and opened
  79308. else {
  79309. if (successCallback) {
  79310. successCallback();
  79311. }
  79312. }
  79313. }
  79314. };
  79315. /**
  79316. * Loads an image from the database
  79317. * @param url defines the url to load from
  79318. * @param image defines the target DOM image
  79319. */
  79320. Database.prototype.loadImage = function (url, image) {
  79321. var _this = this;
  79322. var completeURL = Database._ReturnFullUrlLocation(url);
  79323. var saveAndLoadImage = function () {
  79324. if (!_this._hasReachedQuota && _this._db !== null) {
  79325. // the texture is not yet in the DB, let's try to save it
  79326. _this._saveImageIntoDBAsync(completeURL, image);
  79327. }
  79328. // If the texture is not in the DB and we've reached the DB quota limit
  79329. // let's load it directly from the web
  79330. else {
  79331. image.src = url;
  79332. }
  79333. };
  79334. if (!this._mustUpdateRessources) {
  79335. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  79336. }
  79337. // First time we're download the images or update requested in the manifest file by a version change
  79338. else {
  79339. saveAndLoadImage();
  79340. }
  79341. };
  79342. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  79343. if (this._isSupported && this._db !== null) {
  79344. var texture;
  79345. var transaction = this._db.transaction(["textures"]);
  79346. transaction.onabort = function (event) {
  79347. image.src = url;
  79348. };
  79349. transaction.oncomplete = function (event) {
  79350. var blobTextureURL;
  79351. if (texture) {
  79352. var URL = window.URL || window.webkitURL;
  79353. blobTextureURL = URL.createObjectURL(texture.data);
  79354. image.onerror = function () {
  79355. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  79356. image.src = url;
  79357. };
  79358. image.src = blobTextureURL;
  79359. }
  79360. else {
  79361. notInDBCallback();
  79362. }
  79363. };
  79364. var getRequest = transaction.objectStore("textures").get(url);
  79365. getRequest.onsuccess = function (event) {
  79366. texture = (event.target).result;
  79367. };
  79368. getRequest.onerror = function (event) {
  79369. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  79370. image.src = url;
  79371. };
  79372. }
  79373. else {
  79374. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79375. image.src = url;
  79376. }
  79377. };
  79378. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  79379. var _this = this;
  79380. if (this._isSupported) {
  79381. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  79382. var generateBlobUrl = function () {
  79383. var blobTextureURL;
  79384. if (blob) {
  79385. var URL = window.URL || window.webkitURL;
  79386. try {
  79387. blobTextureURL = URL.createObjectURL(blob);
  79388. }
  79389. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  79390. catch (ex) {
  79391. blobTextureURL = URL.createObjectURL(blob);
  79392. }
  79393. }
  79394. if (blobTextureURL) {
  79395. image.src = blobTextureURL;
  79396. }
  79397. };
  79398. if (Database.IsUASupportingBlobStorage) { // Create XHR
  79399. var xhr = new XMLHttpRequest(), blob;
  79400. xhr.open("GET", url, true);
  79401. xhr.responseType = "blob";
  79402. xhr.addEventListener("load", function () {
  79403. if (xhr.status === 200 && _this._db) {
  79404. // Blob as response (XHR2)
  79405. blob = xhr.response;
  79406. var transaction = _this._db.transaction(["textures"], "readwrite");
  79407. // the transaction could abort because of a QuotaExceededError error
  79408. transaction.onabort = function (event) {
  79409. try {
  79410. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79411. var srcElement = (event.srcElement || event.target);
  79412. var error = srcElement.error;
  79413. if (error && error.name === "QuotaExceededError") {
  79414. _this._hasReachedQuota = true;
  79415. }
  79416. }
  79417. catch (ex) { }
  79418. generateBlobUrl();
  79419. };
  79420. transaction.oncomplete = function (event) {
  79421. generateBlobUrl();
  79422. };
  79423. var newTexture = { textureUrl: url, data: blob };
  79424. try {
  79425. // Put the blob into the dabase
  79426. var addRequest = transaction.objectStore("textures").put(newTexture);
  79427. addRequest.onsuccess = function (event) {
  79428. };
  79429. addRequest.onerror = function (event) {
  79430. generateBlobUrl();
  79431. };
  79432. }
  79433. catch (ex) {
  79434. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  79435. if (ex.code === 25) {
  79436. Database.IsUASupportingBlobStorage = false;
  79437. _this._enableTexturesOffline = false;
  79438. }
  79439. image.src = url;
  79440. }
  79441. }
  79442. else {
  79443. image.src = url;
  79444. }
  79445. }, false);
  79446. xhr.addEventListener("error", function (event) {
  79447. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  79448. image.src = url;
  79449. }, false);
  79450. xhr.send();
  79451. }
  79452. else {
  79453. image.src = url;
  79454. }
  79455. }
  79456. else {
  79457. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79458. image.src = url;
  79459. }
  79460. };
  79461. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  79462. var _this = this;
  79463. var updateVersion = function () {
  79464. // the version is not yet in the DB or we need to update it
  79465. _this._saveVersionIntoDBAsync(url, versionLoaded);
  79466. };
  79467. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  79468. };
  79469. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  79470. var _this = this;
  79471. if (this._isSupported && this._db) {
  79472. var version;
  79473. try {
  79474. var transaction = this._db.transaction(["versions"]);
  79475. transaction.oncomplete = function (event) {
  79476. if (version) {
  79477. // If the version in the JSON file is different from the version in DB
  79478. if (_this._manifestVersionFound !== version.data) {
  79479. _this._mustUpdateRessources = true;
  79480. updateInDBCallback();
  79481. }
  79482. else {
  79483. callback(version.data);
  79484. }
  79485. }
  79486. // version was not found in DB
  79487. else {
  79488. _this._mustUpdateRessources = true;
  79489. updateInDBCallback();
  79490. }
  79491. };
  79492. transaction.onabort = function (event) {
  79493. callback(-1);
  79494. };
  79495. var getRequest = transaction.objectStore("versions").get(url);
  79496. getRequest.onsuccess = function (event) {
  79497. version = (event.target).result;
  79498. };
  79499. getRequest.onerror = function (event) {
  79500. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  79501. callback(-1);
  79502. };
  79503. }
  79504. catch (ex) {
  79505. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  79506. callback(-1);
  79507. }
  79508. }
  79509. else {
  79510. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79511. callback(-1);
  79512. }
  79513. };
  79514. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  79515. var _this = this;
  79516. if (this._isSupported && !this._hasReachedQuota && this._db) {
  79517. try {
  79518. // Open a transaction to the database
  79519. var transaction = this._db.transaction(["versions"], "readwrite");
  79520. // the transaction could abort because of a QuotaExceededError error
  79521. transaction.onabort = function (event) {
  79522. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79523. var error = event.srcElement['error'];
  79524. if (error && error.name === "QuotaExceededError") {
  79525. _this._hasReachedQuota = true;
  79526. }
  79527. }
  79528. catch (ex) { }
  79529. callback(-1);
  79530. };
  79531. transaction.oncomplete = function (event) {
  79532. callback(_this._manifestVersionFound);
  79533. };
  79534. var newVersion = { sceneUrl: url, data: this._manifestVersionFound };
  79535. // Put the scene into the database
  79536. var addRequest = transaction.objectStore("versions").put(newVersion);
  79537. addRequest.onsuccess = function (event) {
  79538. };
  79539. addRequest.onerror = function (event) {
  79540. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  79541. };
  79542. }
  79543. catch (ex) {
  79544. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  79545. callback(-1);
  79546. }
  79547. }
  79548. else {
  79549. callback(-1);
  79550. }
  79551. };
  79552. /**
  79553. * Loads a file from database
  79554. * @param url defines the URL to load from
  79555. * @param sceneLoaded defines a callback to call on success
  79556. * @param progressCallBack defines a callback to call when progress changed
  79557. * @param errorCallback defines a callback to call on error
  79558. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  79559. */
  79560. Database.prototype.loadFile = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  79561. var _this = this;
  79562. var completeUrl = Database._ReturnFullUrlLocation(url);
  79563. var saveAndLoadFile = function () {
  79564. // the scene is not yet in the DB, let's try to save it
  79565. _this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  79566. };
  79567. this._checkVersionFromDB(completeUrl, function (version) {
  79568. if (version !== -1) {
  79569. if (!_this._mustUpdateRessources) {
  79570. _this._loadFileAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  79571. }
  79572. else {
  79573. _this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  79574. }
  79575. }
  79576. else {
  79577. if (errorCallback) {
  79578. errorCallback();
  79579. }
  79580. }
  79581. });
  79582. };
  79583. Database.prototype._loadFileAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  79584. if (this._isSupported && this._db) {
  79585. var targetStore;
  79586. if (url.indexOf(".babylon") !== -1) {
  79587. targetStore = "scenes";
  79588. }
  79589. else {
  79590. targetStore = "textures";
  79591. }
  79592. var file;
  79593. var transaction = this._db.transaction([targetStore]);
  79594. transaction.oncomplete = function (event) {
  79595. if (file) {
  79596. callback(file.data);
  79597. }
  79598. // file was not found in DB
  79599. else {
  79600. notInDBCallback();
  79601. }
  79602. };
  79603. transaction.onabort = function (event) {
  79604. notInDBCallback();
  79605. };
  79606. var getRequest = transaction.objectStore(targetStore).get(url);
  79607. getRequest.onsuccess = function (event) {
  79608. file = (event.target).result;
  79609. };
  79610. getRequest.onerror = function (event) {
  79611. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  79612. notInDBCallback();
  79613. };
  79614. }
  79615. else {
  79616. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79617. callback();
  79618. }
  79619. };
  79620. Database.prototype._saveFileAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  79621. var _this = this;
  79622. if (this._isSupported) {
  79623. var targetStore;
  79624. if (url.indexOf(".babylon") !== -1) {
  79625. targetStore = "scenes";
  79626. }
  79627. else {
  79628. targetStore = "textures";
  79629. }
  79630. // Create XHR
  79631. var xhr = new XMLHttpRequest();
  79632. var fileData;
  79633. xhr.open("GET", url + "?" + Date.now(), true);
  79634. if (useArrayBuffer) {
  79635. xhr.responseType = "arraybuffer";
  79636. }
  79637. if (progressCallback) {
  79638. xhr.onprogress = progressCallback;
  79639. }
  79640. xhr.addEventListener("load", function () {
  79641. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  79642. // Blob as response (XHR2)
  79643. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  79644. if (!_this._hasReachedQuota && _this._db) {
  79645. // Open a transaction to the database
  79646. var transaction = _this._db.transaction([targetStore], "readwrite");
  79647. // the transaction could abort because of a QuotaExceededError error
  79648. transaction.onabort = function (event) {
  79649. try {
  79650. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79651. var error = event.srcElement['error'];
  79652. if (error && error.name === "QuotaExceededError") {
  79653. _this._hasReachedQuota = true;
  79654. }
  79655. }
  79656. catch (ex) { }
  79657. callback(fileData);
  79658. };
  79659. transaction.oncomplete = function (event) {
  79660. callback(fileData);
  79661. };
  79662. var newFile;
  79663. if (targetStore === "scenes") {
  79664. newFile = { sceneUrl: url, data: fileData, version: _this._manifestVersionFound };
  79665. }
  79666. else {
  79667. newFile = { textureUrl: url, data: fileData };
  79668. }
  79669. try {
  79670. // Put the scene into the database
  79671. var addRequest = transaction.objectStore(targetStore).put(newFile);
  79672. addRequest.onsuccess = function (event) {
  79673. };
  79674. addRequest.onerror = function (event) {
  79675. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  79676. };
  79677. }
  79678. catch (ex) {
  79679. callback(fileData);
  79680. }
  79681. }
  79682. else {
  79683. callback(fileData);
  79684. }
  79685. }
  79686. else {
  79687. if (xhr.status >= 400 && errorCallback) {
  79688. errorCallback(xhr);
  79689. }
  79690. else {
  79691. callback();
  79692. }
  79693. }
  79694. }, false);
  79695. xhr.addEventListener("error", function (event) {
  79696. BABYLON.Tools.Error("error on XHR request.");
  79697. callback();
  79698. }, false);
  79699. xhr.send();
  79700. }
  79701. else {
  79702. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or Babylon.js Database is not open.");
  79703. callback();
  79704. }
  79705. };
  79706. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  79707. Database.IsUASupportingBlobStorage = true;
  79708. /**
  79709. * Gets a boolean indicating if Database storate is enabled (off by default)
  79710. */
  79711. Database.IDBStorageEnabled = false;
  79712. Database._ParseURL = function (url) {
  79713. var a = document.createElement('a');
  79714. a.href = url;
  79715. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  79716. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  79717. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  79718. return absLocation;
  79719. };
  79720. Database._ReturnFullUrlLocation = function (url) {
  79721. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  79722. return (Database._ParseURL(window.location.href) + url);
  79723. }
  79724. else {
  79725. return url;
  79726. }
  79727. };
  79728. return Database;
  79729. }());
  79730. BABYLON.Database = Database;
  79731. })(BABYLON || (BABYLON = {}));
  79732. //# sourceMappingURL=babylon.database.js.map
  79733. var BABYLON;
  79734. (function (BABYLON) {
  79735. /**
  79736. * This represents all the required information to add a fresnel effect on a material:
  79737. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  79738. */
  79739. var FresnelParameters = /** @class */ (function () {
  79740. function FresnelParameters() {
  79741. this._isEnabled = true;
  79742. /**
  79743. * Define the color used on edges (grazing angle)
  79744. */
  79745. this.leftColor = BABYLON.Color3.White();
  79746. /**
  79747. * Define the color used on center
  79748. */
  79749. this.rightColor = BABYLON.Color3.Black();
  79750. /**
  79751. * Define bias applied to computed fresnel term
  79752. */
  79753. this.bias = 0;
  79754. /**
  79755. * Defined the power exponent applied to fresnel term
  79756. */
  79757. this.power = 1;
  79758. }
  79759. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  79760. /**
  79761. * Define if the fresnel effect is enable or not.
  79762. */
  79763. get: function () {
  79764. return this._isEnabled;
  79765. },
  79766. set: function (value) {
  79767. if (this._isEnabled === value) {
  79768. return;
  79769. }
  79770. this._isEnabled = value;
  79771. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  79772. },
  79773. enumerable: true,
  79774. configurable: true
  79775. });
  79776. /**
  79777. * Clones the current fresnel and its valuues
  79778. * @returns a clone fresnel configuration
  79779. */
  79780. FresnelParameters.prototype.clone = function () {
  79781. var newFresnelParameters = new FresnelParameters();
  79782. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  79783. return newFresnelParameters;
  79784. };
  79785. /**
  79786. * Serializes the current fresnel parameters to a JSON representation.
  79787. * @return the JSON serialization
  79788. */
  79789. FresnelParameters.prototype.serialize = function () {
  79790. var serializationObject = {};
  79791. serializationObject.isEnabled = this.isEnabled;
  79792. serializationObject.leftColor = this.leftColor.asArray();
  79793. serializationObject.rightColor = this.rightColor.asArray();
  79794. serializationObject.bias = this.bias;
  79795. serializationObject.power = this.power;
  79796. return serializationObject;
  79797. };
  79798. /**
  79799. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  79800. * @param parsedFresnelParameters Define the JSON representation
  79801. * @returns the parsed parameters
  79802. */
  79803. FresnelParameters.Parse = function (parsedFresnelParameters) {
  79804. var fresnelParameters = new FresnelParameters();
  79805. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  79806. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  79807. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  79808. fresnelParameters.bias = parsedFresnelParameters.bias;
  79809. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  79810. return fresnelParameters;
  79811. };
  79812. return FresnelParameters;
  79813. }());
  79814. BABYLON.FresnelParameters = FresnelParameters;
  79815. })(BABYLON || (BABYLON = {}));
  79816. //# sourceMappingURL=babylon.fresnelParameters.js.map
  79817. var BABYLON;
  79818. (function (BABYLON) {
  79819. /**
  79820. * A multi-material is used to apply different materials to different parts of the same object without the need of
  79821. * separate meshes. This can be use to improve performances.
  79822. * @see http://doc.babylonjs.com/how_to/multi_materials
  79823. */
  79824. var MultiMaterial = /** @class */ (function (_super) {
  79825. __extends(MultiMaterial, _super);
  79826. /**
  79827. * Instantiates a new Multi Material
  79828. * A multi-material is used to apply different materials to different parts of the same object without the need of
  79829. * separate meshes. This can be use to improve performances.
  79830. * @see http://doc.babylonjs.com/how_to/multi_materials
  79831. * @param name Define the name in the scene
  79832. * @param scene Define the scene the material belongs to
  79833. */
  79834. function MultiMaterial(name, scene) {
  79835. var _this = _super.call(this, name, scene, true) || this;
  79836. scene.multiMaterials.push(_this);
  79837. _this.subMaterials = new Array();
  79838. _this._storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  79839. return _this;
  79840. }
  79841. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  79842. /**
  79843. * Gets or Sets the list of Materials used within the multi material.
  79844. * They need to be ordered according to the submeshes order in the associated mesh
  79845. */
  79846. get: function () {
  79847. return this._subMaterials;
  79848. },
  79849. set: function (value) {
  79850. this._subMaterials = value;
  79851. this._hookArray(value);
  79852. },
  79853. enumerable: true,
  79854. configurable: true
  79855. });
  79856. MultiMaterial.prototype._hookArray = function (array) {
  79857. var _this = this;
  79858. var oldPush = array.push;
  79859. array.push = function () {
  79860. var items = [];
  79861. for (var _i = 0; _i < arguments.length; _i++) {
  79862. items[_i] = arguments[_i];
  79863. }
  79864. var result = oldPush.apply(array, items);
  79865. _this._markAllSubMeshesAsTexturesDirty();
  79866. return result;
  79867. };
  79868. var oldSplice = array.splice;
  79869. array.splice = function (index, deleteCount) {
  79870. var deleted = oldSplice.apply(array, [index, deleteCount]);
  79871. _this._markAllSubMeshesAsTexturesDirty();
  79872. return deleted;
  79873. };
  79874. };
  79875. /**
  79876. * Get one of the submaterial by its index in the submaterials array
  79877. * @param index The index to look the sub material at
  79878. * @returns The Material if the index has been defined
  79879. */
  79880. MultiMaterial.prototype.getSubMaterial = function (index) {
  79881. if (index < 0 || index >= this.subMaterials.length) {
  79882. return this.getScene().defaultMaterial;
  79883. }
  79884. return this.subMaterials[index];
  79885. };
  79886. /**
  79887. * Get the list of active textures for the whole sub materials list.
  79888. * @returns All the textures that will be used during the rendering
  79889. */
  79890. MultiMaterial.prototype.getActiveTextures = function () {
  79891. var _a;
  79892. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  79893. if (subMaterial) {
  79894. return subMaterial.getActiveTextures();
  79895. }
  79896. else {
  79897. return [];
  79898. }
  79899. }));
  79900. };
  79901. /**
  79902. * Gets the current class name of the material e.g. "MultiMaterial"
  79903. * Mainly use in serialization.
  79904. * @returns the class name
  79905. */
  79906. MultiMaterial.prototype.getClassName = function () {
  79907. return "MultiMaterial";
  79908. };
  79909. /**
  79910. * Checks if the material is ready to render the requested sub mesh
  79911. * @param mesh Define the mesh the submesh belongs to
  79912. * @param subMesh Define the sub mesh to look readyness for
  79913. * @param useInstances Define whether or not the material is used with instances
  79914. * @returns true if ready, otherwise false
  79915. */
  79916. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  79917. for (var index = 0; index < this.subMaterials.length; index++) {
  79918. var subMaterial = this.subMaterials[index];
  79919. if (subMaterial) {
  79920. if (subMaterial._storeEffectOnSubMeshes) {
  79921. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  79922. return false;
  79923. }
  79924. continue;
  79925. }
  79926. if (!subMaterial.isReady(mesh)) {
  79927. return false;
  79928. }
  79929. }
  79930. }
  79931. return true;
  79932. };
  79933. /**
  79934. * Clones the current material and its related sub materials
  79935. * @param name Define the name of the newly cloned material
  79936. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  79937. * @returns the cloned material
  79938. */
  79939. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  79940. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  79941. for (var index = 0; index < this.subMaterials.length; index++) {
  79942. var subMaterial = null;
  79943. var current = this.subMaterials[index];
  79944. if (cloneChildren && current) {
  79945. subMaterial = current.clone(name + "-" + current.name);
  79946. }
  79947. else {
  79948. subMaterial = this.subMaterials[index];
  79949. }
  79950. newMultiMaterial.subMaterials.push(subMaterial);
  79951. }
  79952. return newMultiMaterial;
  79953. };
  79954. /**
  79955. * Serializes the materials into a JSON representation.
  79956. * @returns the JSON representation
  79957. */
  79958. MultiMaterial.prototype.serialize = function () {
  79959. var serializationObject = {};
  79960. serializationObject.name = this.name;
  79961. serializationObject.id = this.id;
  79962. if (BABYLON.Tags) {
  79963. serializationObject.tags = BABYLON.Tags.GetTags(this);
  79964. }
  79965. serializationObject.materials = [];
  79966. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  79967. var subMat = this.subMaterials[matIndex];
  79968. if (subMat) {
  79969. serializationObject.materials.push(subMat.id);
  79970. }
  79971. else {
  79972. serializationObject.materials.push(null);
  79973. }
  79974. }
  79975. return serializationObject;
  79976. };
  79977. /**
  79978. * Dispose the material and release its associated resources
  79979. * @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)
  79980. * @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)
  79981. */
  79982. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  79983. var scene = this.getScene();
  79984. if (!scene) {
  79985. return;
  79986. }
  79987. var index = scene.multiMaterials.indexOf(this);
  79988. if (index >= 0) {
  79989. scene.multiMaterials.splice(index, 1);
  79990. }
  79991. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  79992. };
  79993. return MultiMaterial;
  79994. }(BABYLON.Material));
  79995. BABYLON.MultiMaterial = MultiMaterial;
  79996. })(BABYLON || (BABYLON = {}));
  79997. //# sourceMappingURL=babylon.multiMaterial.js.map
  79998. var BABYLON;
  79999. (function (BABYLON) {
  80000. /**
  80001. * Manage the touch inputs to control the movement of a free camera.
  80002. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  80003. */
  80004. var FreeCameraTouchInput = /** @class */ (function () {
  80005. function FreeCameraTouchInput() {
  80006. /**
  80007. * Defines the touch sensibility for rotation.
  80008. * The higher the faster.
  80009. */
  80010. this.touchAngularSensibility = 200000.0;
  80011. /**
  80012. * Defines the touch sensibility for move.
  80013. * The higher the faster.
  80014. */
  80015. this.touchMoveSensibility = 250.0;
  80016. this._offsetX = null;
  80017. this._offsetY = null;
  80018. this._pointerPressed = new Array();
  80019. }
  80020. /**
  80021. * Attach the input controls to a specific dom element to get the input from.
  80022. * @param element Defines the element the controls should be listened from
  80023. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  80024. */
  80025. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  80026. var _this = this;
  80027. var previousPosition = null;
  80028. if (this._pointerInput === undefined) {
  80029. this._onLostFocus = function (evt) {
  80030. _this._offsetX = null;
  80031. _this._offsetY = null;
  80032. };
  80033. this._pointerInput = function (p, s) {
  80034. var evt = p.event;
  80035. if (evt.pointerType === "mouse") {
  80036. return;
  80037. }
  80038. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  80039. if (!noPreventDefault) {
  80040. evt.preventDefault();
  80041. }
  80042. _this._pointerPressed.push(evt.pointerId);
  80043. if (_this._pointerPressed.length !== 1) {
  80044. return;
  80045. }
  80046. previousPosition = {
  80047. x: evt.clientX,
  80048. y: evt.clientY
  80049. };
  80050. }
  80051. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  80052. if (!noPreventDefault) {
  80053. evt.preventDefault();
  80054. }
  80055. var index = _this._pointerPressed.indexOf(evt.pointerId);
  80056. if (index === -1) {
  80057. return;
  80058. }
  80059. _this._pointerPressed.splice(index, 1);
  80060. if (index != 0) {
  80061. return;
  80062. }
  80063. previousPosition = null;
  80064. _this._offsetX = null;
  80065. _this._offsetY = null;
  80066. }
  80067. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  80068. if (!noPreventDefault) {
  80069. evt.preventDefault();
  80070. }
  80071. if (!previousPosition) {
  80072. return;
  80073. }
  80074. var index = _this._pointerPressed.indexOf(evt.pointerId);
  80075. if (index != 0) {
  80076. return;
  80077. }
  80078. _this._offsetX = evt.clientX - previousPosition.x;
  80079. _this._offsetY = -(evt.clientY - previousPosition.y);
  80080. }
  80081. };
  80082. }
  80083. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  80084. if (this._onLostFocus) {
  80085. element.addEventListener("blur", this._onLostFocus);
  80086. }
  80087. };
  80088. /**
  80089. * Detach the current controls from the specified dom element.
  80090. * @param element Defines the element to stop listening the inputs from
  80091. */
  80092. FreeCameraTouchInput.prototype.detachControl = function (element) {
  80093. if (this._pointerInput && element) {
  80094. if (this._observer) {
  80095. this.camera.getScene().onPointerObservable.remove(this._observer);
  80096. this._observer = null;
  80097. }
  80098. if (this._onLostFocus) {
  80099. element.removeEventListener("blur", this._onLostFocus);
  80100. this._onLostFocus = null;
  80101. }
  80102. this._pointerPressed = [];
  80103. this._offsetX = null;
  80104. this._offsetY = null;
  80105. }
  80106. };
  80107. /**
  80108. * Update the current camera state depending on the inputs that have been used this frame.
  80109. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  80110. */
  80111. FreeCameraTouchInput.prototype.checkInputs = function () {
  80112. if (this._offsetX && this._offsetY) {
  80113. var camera = this.camera;
  80114. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  80115. if (this._pointerPressed.length > 1) {
  80116. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  80117. }
  80118. else {
  80119. var speed = camera._computeLocalCameraSpeed();
  80120. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  80121. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  80122. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  80123. }
  80124. }
  80125. };
  80126. /**
  80127. * Gets the class name of the current intput.
  80128. * @returns the class name
  80129. */
  80130. FreeCameraTouchInput.prototype.getClassName = function () {
  80131. return "FreeCameraTouchInput";
  80132. };
  80133. /**
  80134. * Get the friendly name associated with the input class.
  80135. * @returns the input friendly name
  80136. */
  80137. FreeCameraTouchInput.prototype.getSimpleName = function () {
  80138. return "touch";
  80139. };
  80140. __decorate([
  80141. BABYLON.serialize()
  80142. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  80143. __decorate([
  80144. BABYLON.serialize()
  80145. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  80146. return FreeCameraTouchInput;
  80147. }());
  80148. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  80149. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  80150. })(BABYLON || (BABYLON = {}));
  80151. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  80152. var BABYLON;
  80153. (function (BABYLON) {
  80154. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  80155. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  80156. });
  80157. /**
  80158. * This represents a FPS type of camera controlled by touch.
  80159. * This is like a universal camera minus the Gamepad controls.
  80160. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80161. */
  80162. var TouchCamera = /** @class */ (function (_super) {
  80163. __extends(TouchCamera, _super);
  80164. /**
  80165. * Instantiates a new touch camera.
  80166. * This represents a FPS type of camera controlled by touch.
  80167. * This is like a universal camera minus the Gamepad controls.
  80168. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80169. * @param name Define the name of the camera in the scene
  80170. * @param position Define the start position of the camera in the scene
  80171. * @param scene Define the scene the camera belongs to
  80172. */
  80173. function TouchCamera(name, position, scene) {
  80174. var _this = _super.call(this, name, position, scene) || this;
  80175. _this.inputs.addTouch();
  80176. _this._setupInputs();
  80177. return _this;
  80178. }
  80179. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  80180. /**
  80181. * Defines the touch sensibility for rotation.
  80182. * The higher the faster.
  80183. */
  80184. get: function () {
  80185. var touch = this.inputs.attached["touch"];
  80186. if (touch) {
  80187. return touch.touchAngularSensibility;
  80188. }
  80189. return 0;
  80190. },
  80191. set: function (value) {
  80192. var touch = this.inputs.attached["touch"];
  80193. if (touch) {
  80194. touch.touchAngularSensibility = value;
  80195. }
  80196. },
  80197. enumerable: true,
  80198. configurable: true
  80199. });
  80200. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  80201. /**
  80202. * Defines the touch sensibility for move.
  80203. * The higher the faster.
  80204. */
  80205. get: function () {
  80206. var touch = this.inputs.attached["touch"];
  80207. if (touch) {
  80208. return touch.touchMoveSensibility;
  80209. }
  80210. return 0;
  80211. },
  80212. set: function (value) {
  80213. var touch = this.inputs.attached["touch"];
  80214. if (touch) {
  80215. touch.touchMoveSensibility = value;
  80216. }
  80217. },
  80218. enumerable: true,
  80219. configurable: true
  80220. });
  80221. /**
  80222. * Gets the current object class name.
  80223. * @return the class name
  80224. */
  80225. TouchCamera.prototype.getClassName = function () {
  80226. return "TouchCamera";
  80227. };
  80228. /** @hidden */
  80229. TouchCamera.prototype._setupInputs = function () {
  80230. var mouse = this.inputs.attached["mouse"];
  80231. if (mouse) {
  80232. mouse.touchEnabled = false;
  80233. }
  80234. };
  80235. return TouchCamera;
  80236. }(BABYLON.FreeCamera));
  80237. BABYLON.TouchCamera = TouchCamera;
  80238. })(BABYLON || (BABYLON = {}));
  80239. //# sourceMappingURL=babylon.touchCamera.js.map
  80240. var BABYLON;
  80241. (function (BABYLON) {
  80242. /**
  80243. * 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.
  80244. * This is the base class of any Procedural texture and contains most of the shareable code.
  80245. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  80246. */
  80247. var ProceduralTexture = /** @class */ (function (_super) {
  80248. __extends(ProceduralTexture, _super);
  80249. /**
  80250. * Instantiates a new procedural texture.
  80251. * 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.
  80252. * This is the base class of any Procedural texture and contains most of the shareable code.
  80253. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  80254. * @param name Define the name of the texture
  80255. * @param size Define the size of the texture to create
  80256. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  80257. * @param scene Define the scene the texture belongs to
  80258. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  80259. * @param generateMipMaps Define if the texture should creates mip maps or not
  80260. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  80261. */
  80262. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  80263. if (fallbackTexture === void 0) { fallbackTexture = null; }
  80264. if (generateMipMaps === void 0) { generateMipMaps = true; }
  80265. if (isCube === void 0) { isCube = false; }
  80266. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  80267. _this.isCube = isCube;
  80268. /**
  80269. * Define if the texture is enabled or not (disabled texture will not render)
  80270. */
  80271. _this.isEnabled = true;
  80272. /**
  80273. * Define if the texture must be cleared before rendering (default is true)
  80274. */
  80275. _this.autoClear = true;
  80276. /**
  80277. * Event raised when the texture is generated
  80278. */
  80279. _this.onGeneratedObservable = new BABYLON.Observable();
  80280. /** @hidden */
  80281. _this._textures = {};
  80282. _this._currentRefreshId = -1;
  80283. _this._refreshRate = 1;
  80284. _this._vertexBuffers = {};
  80285. _this._uniforms = new Array();
  80286. _this._samplers = new Array();
  80287. _this._floats = {};
  80288. _this._ints = {};
  80289. _this._floatsArrays = {};
  80290. _this._colors3 = {};
  80291. _this._colors4 = {};
  80292. _this._vectors2 = {};
  80293. _this._vectors3 = {};
  80294. _this._matrices = {};
  80295. _this._fallbackTextureUsed = false;
  80296. _this._cachedDefines = "";
  80297. _this._contentUpdateId = -1;
  80298. scene = _this.getScene();
  80299. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  80300. if (!component) {
  80301. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  80302. scene._addComponent(component);
  80303. }
  80304. scene.proceduralTextures.push(_this);
  80305. _this._engine = scene.getEngine();
  80306. _this.name = name;
  80307. _this.isRenderTarget = true;
  80308. _this._size = size;
  80309. _this._generateMipMaps = generateMipMaps;
  80310. _this.setFragment(fragment);
  80311. _this._fallbackTexture = fallbackTexture;
  80312. if (isCube) {
  80313. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  80314. _this.setFloat("face", 0);
  80315. }
  80316. else {
  80317. _this._texture = _this._engine.createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  80318. }
  80319. // VBO
  80320. var vertices = [];
  80321. vertices.push(1, 1);
  80322. vertices.push(-1, 1);
  80323. vertices.push(-1, -1);
  80324. vertices.push(1, -1);
  80325. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80326. _this._createIndexBuffer();
  80327. return _this;
  80328. }
  80329. /**
  80330. * The effect that is created when initializing the post process.
  80331. * @returns The created effect corrisponding the the postprocess.
  80332. */
  80333. ProceduralTexture.prototype.getEffect = function () {
  80334. return this._effect;
  80335. };
  80336. /**
  80337. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  80338. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  80339. */
  80340. ProceduralTexture.prototype.getContent = function () {
  80341. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  80342. return this._contentData;
  80343. }
  80344. this._contentData = this.readPixels(0, 0, this._contentData);
  80345. this._contentUpdateId = this._currentRefreshId;
  80346. return this._contentData;
  80347. };
  80348. ProceduralTexture.prototype._createIndexBuffer = function () {
  80349. var engine = this._engine;
  80350. // Indices
  80351. var indices = [];
  80352. indices.push(0);
  80353. indices.push(1);
  80354. indices.push(2);
  80355. indices.push(0);
  80356. indices.push(2);
  80357. indices.push(3);
  80358. this._indexBuffer = engine.createIndexBuffer(indices);
  80359. };
  80360. /** @hidden */
  80361. ProceduralTexture.prototype._rebuild = function () {
  80362. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80363. if (vb) {
  80364. vb._rebuild();
  80365. }
  80366. this._createIndexBuffer();
  80367. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  80368. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  80369. }
  80370. };
  80371. /**
  80372. * Resets the texture in order to recreate its associated resources.
  80373. * This can be called in case of context loss
  80374. */
  80375. ProceduralTexture.prototype.reset = function () {
  80376. if (this._effect === undefined) {
  80377. return;
  80378. }
  80379. var engine = this._engine;
  80380. engine._releaseEffect(this._effect);
  80381. };
  80382. ProceduralTexture.prototype._getDefines = function () {
  80383. return "";
  80384. };
  80385. /**
  80386. * Is the texture ready to be used ? (rendered at least once)
  80387. * @returns true if ready, otherwise, false.
  80388. */
  80389. ProceduralTexture.prototype.isReady = function () {
  80390. var _this = this;
  80391. var engine = this._engine;
  80392. var shaders;
  80393. if (!this._fragment) {
  80394. return false;
  80395. }
  80396. if (this._fallbackTextureUsed) {
  80397. return true;
  80398. }
  80399. var defines = this._getDefines();
  80400. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  80401. return true;
  80402. }
  80403. if (this._fragment.fragmentElement !== undefined) {
  80404. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  80405. }
  80406. else {
  80407. shaders = { vertex: "procedural", fragment: this._fragment };
  80408. }
  80409. this._cachedDefines = defines;
  80410. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  80411. _this.releaseInternalTexture();
  80412. if (_this._fallbackTexture) {
  80413. _this._texture = _this._fallbackTexture._texture;
  80414. if (_this._texture) {
  80415. _this._texture.incrementReferences();
  80416. }
  80417. }
  80418. _this._fallbackTextureUsed = true;
  80419. });
  80420. return this._effect.isReady();
  80421. };
  80422. /**
  80423. * Resets the refresh counter of the texture and start bak from scratch.
  80424. * Could be usefull to regenerate the texture if it is setup to render only once.
  80425. */
  80426. ProceduralTexture.prototype.resetRefreshCounter = function () {
  80427. this._currentRefreshId = -1;
  80428. };
  80429. /**
  80430. * Set the fragment shader to use in order to render the texture.
  80431. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  80432. */
  80433. ProceduralTexture.prototype.setFragment = function (fragment) {
  80434. this._fragment = fragment;
  80435. };
  80436. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  80437. /**
  80438. * Define the refresh rate of the texture or the rendering frequency.
  80439. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  80440. */
  80441. get: function () {
  80442. return this._refreshRate;
  80443. },
  80444. set: function (value) {
  80445. this._refreshRate = value;
  80446. this.resetRefreshCounter();
  80447. },
  80448. enumerable: true,
  80449. configurable: true
  80450. });
  80451. /** @hidden */
  80452. ProceduralTexture.prototype._shouldRender = function () {
  80453. if (!this.isEnabled || !this.isReady() || !this._texture) {
  80454. if (this._texture) {
  80455. this._texture.isReady = false;
  80456. }
  80457. return false;
  80458. }
  80459. if (this._fallbackTextureUsed) {
  80460. return false;
  80461. }
  80462. if (this._currentRefreshId === -1) { // At least render once
  80463. this._currentRefreshId = 1;
  80464. return true;
  80465. }
  80466. if (this.refreshRate === this._currentRefreshId) {
  80467. this._currentRefreshId = 1;
  80468. return true;
  80469. }
  80470. this._currentRefreshId++;
  80471. return false;
  80472. };
  80473. /**
  80474. * Get the size the texture is rendering at.
  80475. * @returns the size (texture is always squared)
  80476. */
  80477. ProceduralTexture.prototype.getRenderSize = function () {
  80478. return this._size;
  80479. };
  80480. /**
  80481. * Resize the texture to new value.
  80482. * @param size Define the new size the texture should have
  80483. * @param generateMipMaps Define whether the new texture should create mip maps
  80484. */
  80485. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  80486. if (this._fallbackTextureUsed) {
  80487. return;
  80488. }
  80489. this.releaseInternalTexture();
  80490. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  80491. // Update properties
  80492. this._size = size;
  80493. this._generateMipMaps = generateMipMaps;
  80494. };
  80495. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  80496. if (this._uniforms.indexOf(uniformName) === -1) {
  80497. this._uniforms.push(uniformName);
  80498. }
  80499. };
  80500. /**
  80501. * Set a texture in the shader program used to render.
  80502. * @param name Define the name of the uniform samplers as defined in the shader
  80503. * @param texture Define the texture to bind to this sampler
  80504. * @return the texture itself allowing "fluent" like uniform updates
  80505. */
  80506. ProceduralTexture.prototype.setTexture = function (name, texture) {
  80507. if (this._samplers.indexOf(name) === -1) {
  80508. this._samplers.push(name);
  80509. }
  80510. this._textures[name] = texture;
  80511. return this;
  80512. };
  80513. /**
  80514. * Set a float in the shader.
  80515. * @param name Define the name of the uniform as defined in the shader
  80516. * @param value Define the value to give to the uniform
  80517. * @return the texture itself allowing "fluent" like uniform updates
  80518. */
  80519. ProceduralTexture.prototype.setFloat = function (name, value) {
  80520. this._checkUniform(name);
  80521. this._floats[name] = value;
  80522. return this;
  80523. };
  80524. /**
  80525. * Set a int in the shader.
  80526. * @param name Define the name of the uniform as defined in the shader
  80527. * @param value Define the value to give to the uniform
  80528. * @return the texture itself allowing "fluent" like uniform updates
  80529. */
  80530. ProceduralTexture.prototype.setInt = function (name, value) {
  80531. this._checkUniform(name);
  80532. this._ints[name] = value;
  80533. return this;
  80534. };
  80535. /**
  80536. * Set an array of floats in the shader.
  80537. * @param name Define the name of the uniform as defined in the shader
  80538. * @param value Define the value to give to the uniform
  80539. * @return the texture itself allowing "fluent" like uniform updates
  80540. */
  80541. ProceduralTexture.prototype.setFloats = function (name, value) {
  80542. this._checkUniform(name);
  80543. this._floatsArrays[name] = value;
  80544. return this;
  80545. };
  80546. /**
  80547. * Set a vec3 in the shader from a Color3.
  80548. * @param name Define the name of the uniform as defined in the shader
  80549. * @param value Define the value to give to the uniform
  80550. * @return the texture itself allowing "fluent" like uniform updates
  80551. */
  80552. ProceduralTexture.prototype.setColor3 = function (name, value) {
  80553. this._checkUniform(name);
  80554. this._colors3[name] = value;
  80555. return this;
  80556. };
  80557. /**
  80558. * Set a vec4 in the shader from a Color4.
  80559. * @param name Define the name of the uniform as defined in the shader
  80560. * @param value Define the value to give to the uniform
  80561. * @return the texture itself allowing "fluent" like uniform updates
  80562. */
  80563. ProceduralTexture.prototype.setColor4 = function (name, value) {
  80564. this._checkUniform(name);
  80565. this._colors4[name] = value;
  80566. return this;
  80567. };
  80568. /**
  80569. * Set a vec2 in the shader from a Vector2.
  80570. * @param name Define the name of the uniform as defined in the shader
  80571. * @param value Define the value to give to the uniform
  80572. * @return the texture itself allowing "fluent" like uniform updates
  80573. */
  80574. ProceduralTexture.prototype.setVector2 = function (name, value) {
  80575. this._checkUniform(name);
  80576. this._vectors2[name] = value;
  80577. return this;
  80578. };
  80579. /**
  80580. * Set a vec3 in the shader from a Vector3.
  80581. * @param name Define the name of the uniform as defined in the shader
  80582. * @param value Define the value to give to the uniform
  80583. * @return the texture itself allowing "fluent" like uniform updates
  80584. */
  80585. ProceduralTexture.prototype.setVector3 = function (name, value) {
  80586. this._checkUniform(name);
  80587. this._vectors3[name] = value;
  80588. return this;
  80589. };
  80590. /**
  80591. * Set a mat4 in the shader from a MAtrix.
  80592. * @param name Define the name of the uniform as defined in the shader
  80593. * @param value Define the value to give to the uniform
  80594. * @return the texture itself allowing "fluent" like uniform updates
  80595. */
  80596. ProceduralTexture.prototype.setMatrix = function (name, value) {
  80597. this._checkUniform(name);
  80598. this._matrices[name] = value;
  80599. return this;
  80600. };
  80601. /**
  80602. * Render the texture to its associated render target.
  80603. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  80604. */
  80605. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  80606. var scene = this.getScene();
  80607. if (!scene) {
  80608. return;
  80609. }
  80610. var engine = this._engine;
  80611. // Render
  80612. engine.enableEffect(this._effect);
  80613. engine.setState(false);
  80614. // Texture
  80615. for (var name in this._textures) {
  80616. this._effect.setTexture(name, this._textures[name]);
  80617. }
  80618. // Float
  80619. for (name in this._ints) {
  80620. this._effect.setInt(name, this._ints[name]);
  80621. }
  80622. // Float
  80623. for (name in this._floats) {
  80624. this._effect.setFloat(name, this._floats[name]);
  80625. }
  80626. // Floats
  80627. for (name in this._floatsArrays) {
  80628. this._effect.setArray(name, this._floatsArrays[name]);
  80629. }
  80630. // Color3
  80631. for (name in this._colors3) {
  80632. this._effect.setColor3(name, this._colors3[name]);
  80633. }
  80634. // Color4
  80635. for (name in this._colors4) {
  80636. var color = this._colors4[name];
  80637. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  80638. }
  80639. // Vector2
  80640. for (name in this._vectors2) {
  80641. this._effect.setVector2(name, this._vectors2[name]);
  80642. }
  80643. // Vector3
  80644. for (name in this._vectors3) {
  80645. this._effect.setVector3(name, this._vectors3[name]);
  80646. }
  80647. // Matrix
  80648. for (name in this._matrices) {
  80649. this._effect.setMatrix(name, this._matrices[name]);
  80650. }
  80651. if (!this._texture) {
  80652. return;
  80653. }
  80654. if (this.isCube) {
  80655. for (var face = 0; face < 6; face++) {
  80656. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  80657. // VBOs
  80658. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80659. this._effect.setFloat("face", face);
  80660. // Clear
  80661. if (this.autoClear) {
  80662. engine.clear(scene.clearColor, true, false, false);
  80663. }
  80664. // Draw order
  80665. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80666. // Mipmaps
  80667. if (face === 5) {
  80668. engine.generateMipMapsForCubemap(this._texture);
  80669. }
  80670. }
  80671. }
  80672. else {
  80673. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  80674. // VBOs
  80675. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80676. // Clear
  80677. if (this.autoClear) {
  80678. engine.clear(scene.clearColor, true, false, false);
  80679. }
  80680. // Draw order
  80681. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80682. }
  80683. // Unbind
  80684. engine.unBindFramebuffer(this._texture, this.isCube);
  80685. if (this.onGenerated) {
  80686. this.onGenerated();
  80687. }
  80688. this.onGeneratedObservable.notifyObservers(this);
  80689. };
  80690. /**
  80691. * Clone the texture.
  80692. * @returns the cloned texture
  80693. */
  80694. ProceduralTexture.prototype.clone = function () {
  80695. var textureSize = this.getSize();
  80696. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  80697. // Base texture
  80698. newTexture.hasAlpha = this.hasAlpha;
  80699. newTexture.level = this.level;
  80700. // RenderTarget Texture
  80701. newTexture.coordinatesMode = this.coordinatesMode;
  80702. return newTexture;
  80703. };
  80704. /**
  80705. * Dispose the texture and release its asoociated resources.
  80706. */
  80707. ProceduralTexture.prototype.dispose = function () {
  80708. var scene = this.getScene();
  80709. if (!scene) {
  80710. return;
  80711. }
  80712. var index = scene.proceduralTextures.indexOf(this);
  80713. if (index >= 0) {
  80714. scene.proceduralTextures.splice(index, 1);
  80715. }
  80716. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80717. if (vertexBuffer) {
  80718. vertexBuffer.dispose();
  80719. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80720. }
  80721. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  80722. this._indexBuffer = null;
  80723. }
  80724. _super.prototype.dispose.call(this);
  80725. };
  80726. __decorate([
  80727. BABYLON.serialize()
  80728. ], ProceduralTexture.prototype, "isEnabled", void 0);
  80729. __decorate([
  80730. BABYLON.serialize()
  80731. ], ProceduralTexture.prototype, "autoClear", void 0);
  80732. __decorate([
  80733. BABYLON.serialize()
  80734. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  80735. __decorate([
  80736. BABYLON.serialize()
  80737. ], ProceduralTexture.prototype, "_size", void 0);
  80738. __decorate([
  80739. BABYLON.serialize()
  80740. ], ProceduralTexture.prototype, "refreshRate", null);
  80741. return ProceduralTexture;
  80742. }(BABYLON.Texture));
  80743. BABYLON.ProceduralTexture = ProceduralTexture;
  80744. })(BABYLON || (BABYLON = {}));
  80745. //# sourceMappingURL=babylon.proceduralTexture.js.map
  80746. var BABYLON;
  80747. (function (BABYLON) {
  80748. /**
  80749. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  80750. * in a given scene.
  80751. */
  80752. var ProceduralTextureSceneComponent = /** @class */ (function () {
  80753. /**
  80754. * Creates a new instance of the component for the given scene
  80755. * @param scene Defines the scene to register the component in
  80756. */
  80757. function ProceduralTextureSceneComponent(scene) {
  80758. /**
  80759. * The component name helpfull to identify the component in the list of scene components.
  80760. */
  80761. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  80762. this.scene = scene;
  80763. this.scene.proceduralTextures = new Array();
  80764. scene.layers = new Array();
  80765. }
  80766. /**
  80767. * Registers the component in a given scene
  80768. */
  80769. ProceduralTextureSceneComponent.prototype.register = function () {
  80770. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  80771. };
  80772. /**
  80773. * Rebuilds the elements related to this component in case of
  80774. * context lost for instance.
  80775. */
  80776. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  80777. // Nothing to do here.
  80778. };
  80779. /**
  80780. * Disposes the component and the associated ressources.
  80781. */
  80782. ProceduralTextureSceneComponent.prototype.dispose = function () {
  80783. // Nothing to do here.
  80784. };
  80785. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  80786. if (this.scene.proceduralTexturesEnabled) {
  80787. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  80788. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  80789. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  80790. if (proceduralTexture._shouldRender()) {
  80791. proceduralTexture.render();
  80792. }
  80793. }
  80794. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  80795. }
  80796. };
  80797. return ProceduralTextureSceneComponent;
  80798. }());
  80799. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  80800. })(BABYLON || (BABYLON = {}));
  80801. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  80802. var BABYLON;
  80803. (function (BABYLON) {
  80804. /**
  80805. * 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.
  80806. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  80807. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  80808. */
  80809. var CustomProceduralTexture = /** @class */ (function (_super) {
  80810. __extends(CustomProceduralTexture, _super);
  80811. /**
  80812. * Instantiates a new Custom Procedural Texture.
  80813. * 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.
  80814. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  80815. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  80816. * @param name Define the name of the texture
  80817. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  80818. * @param size Define the size of the texture to create
  80819. * @param scene Define the scene the texture belongs to
  80820. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  80821. * @param generateMipMaps Define if the texture should creates mip maps or not
  80822. */
  80823. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  80824. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  80825. _this._animate = true;
  80826. _this._time = 0;
  80827. _this._texturePath = texturePath;
  80828. //Try to load json
  80829. _this._loadJson(texturePath);
  80830. _this.refreshRate = 1;
  80831. return _this;
  80832. }
  80833. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  80834. var _this = this;
  80835. var noConfigFile = function () {
  80836. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  80837. try {
  80838. _this.setFragment(_this._texturePath);
  80839. }
  80840. catch (ex) {
  80841. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  80842. }
  80843. };
  80844. var configFileUrl = jsonUrl + "/config.json";
  80845. var xhr = new XMLHttpRequest();
  80846. xhr.open("GET", configFileUrl, true);
  80847. xhr.addEventListener("load", function () {
  80848. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  80849. try {
  80850. _this._config = JSON.parse(xhr.response);
  80851. _this.updateShaderUniforms();
  80852. _this.updateTextures();
  80853. _this.setFragment(_this._texturePath + "/custom");
  80854. _this._animate = _this._config.animate;
  80855. _this.refreshRate = _this._config.refreshrate;
  80856. }
  80857. catch (ex) {
  80858. noConfigFile();
  80859. }
  80860. }
  80861. else {
  80862. noConfigFile();
  80863. }
  80864. }, false);
  80865. xhr.addEventListener("error", function () {
  80866. noConfigFile();
  80867. }, false);
  80868. try {
  80869. xhr.send();
  80870. }
  80871. catch (ex) {
  80872. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  80873. }
  80874. };
  80875. /**
  80876. * Is the texture ready to be used ? (rendered at least once)
  80877. * @returns true if ready, otherwise, false.
  80878. */
  80879. CustomProceduralTexture.prototype.isReady = function () {
  80880. if (!_super.prototype.isReady.call(this)) {
  80881. return false;
  80882. }
  80883. for (var name in this._textures) {
  80884. var texture = this._textures[name];
  80885. if (!texture.isReady()) {
  80886. return false;
  80887. }
  80888. }
  80889. return true;
  80890. };
  80891. /**
  80892. * Render the texture to its associated render target.
  80893. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  80894. */
  80895. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  80896. var scene = this.getScene();
  80897. if (this._animate && scene) {
  80898. this._time += scene.getAnimationRatio() * 0.03;
  80899. this.updateShaderUniforms();
  80900. }
  80901. _super.prototype.render.call(this, useCameraPostProcess);
  80902. };
  80903. /**
  80904. * Update the list of dependant textures samplers in the shader.
  80905. */
  80906. CustomProceduralTexture.prototype.updateTextures = function () {
  80907. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  80908. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  80909. }
  80910. };
  80911. /**
  80912. * Update the uniform values of the procedural texture in the shader.
  80913. */
  80914. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  80915. if (this._config) {
  80916. for (var j = 0; j < this._config.uniforms.length; j++) {
  80917. var uniform = this._config.uniforms[j];
  80918. switch (uniform.type) {
  80919. case "float":
  80920. this.setFloat(uniform.name, uniform.value);
  80921. break;
  80922. case "color3":
  80923. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  80924. break;
  80925. case "color4":
  80926. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  80927. break;
  80928. case "vector2":
  80929. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  80930. break;
  80931. case "vector3":
  80932. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  80933. break;
  80934. }
  80935. }
  80936. }
  80937. this.setFloat("time", this._time);
  80938. };
  80939. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  80940. /**
  80941. * Define if the texture animates or not.
  80942. */
  80943. get: function () {
  80944. return this._animate;
  80945. },
  80946. set: function (value) {
  80947. this._animate = value;
  80948. },
  80949. enumerable: true,
  80950. configurable: true
  80951. });
  80952. return CustomProceduralTexture;
  80953. }(BABYLON.ProceduralTexture));
  80954. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  80955. })(BABYLON || (BABYLON = {}));
  80956. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  80957. var BABYLON;
  80958. (function (BABYLON) {
  80959. /**
  80960. * Manage the gamepad inputs to control a free camera.
  80961. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  80962. */
  80963. var FreeCameraGamepadInput = /** @class */ (function () {
  80964. function FreeCameraGamepadInput() {
  80965. /**
  80966. * Defines the gamepad rotation sensiblity.
  80967. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  80968. */
  80969. this.gamepadAngularSensibility = 200;
  80970. /**
  80971. * Defines the gamepad move sensiblity.
  80972. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  80973. */
  80974. this.gamepadMoveSensibility = 40;
  80975. this._cameraTransform = BABYLON.Matrix.Identity();
  80976. this._deltaTransform = BABYLON.Vector3.Zero();
  80977. this._vector3 = BABYLON.Vector3.Zero();
  80978. this._vector2 = BABYLON.Vector2.Zero();
  80979. }
  80980. /**
  80981. * Attach the input controls to a specific dom element to get the input from.
  80982. * @param element Defines the element the controls should be listened from
  80983. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  80984. */
  80985. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  80986. var _this = this;
  80987. var manager = this.camera.getScene().gamepadManager;
  80988. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80989. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80990. // prioritize XBOX gamepads.
  80991. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  80992. _this.gamepad = gamepad;
  80993. }
  80994. }
  80995. });
  80996. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80997. if (_this.gamepad === gamepad) {
  80998. _this.gamepad = null;
  80999. }
  81000. });
  81001. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  81002. };
  81003. /**
  81004. * Detach the current controls from the specified dom element.
  81005. * @param element Defines the element to stop listening the inputs from
  81006. */
  81007. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  81008. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81009. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81010. this.gamepad = null;
  81011. };
  81012. /**
  81013. * Update the current camera state depending on the inputs that have been used this frame.
  81014. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  81015. */
  81016. FreeCameraGamepadInput.prototype.checkInputs = function () {
  81017. if (this.gamepad && this.gamepad.leftStick) {
  81018. var camera = this.camera;
  81019. var LSValues = this.gamepad.leftStick;
  81020. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  81021. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  81022. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  81023. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  81024. var RSValues = this.gamepad.rightStick;
  81025. if (RSValues) {
  81026. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  81027. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  81028. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  81029. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  81030. }
  81031. else {
  81032. RSValues = { x: 0, y: 0 };
  81033. }
  81034. if (!camera.rotationQuaternion) {
  81035. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  81036. }
  81037. else {
  81038. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  81039. }
  81040. var speed = camera._computeLocalCameraSpeed() * 50.0;
  81041. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  81042. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  81043. camera.cameraDirection.addInPlace(this._deltaTransform);
  81044. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  81045. camera.cameraRotation.addInPlace(this._vector2);
  81046. }
  81047. };
  81048. /**
  81049. * Gets the class name of the current intput.
  81050. * @returns the class name
  81051. */
  81052. FreeCameraGamepadInput.prototype.getClassName = function () {
  81053. return "FreeCameraGamepadInput";
  81054. };
  81055. /**
  81056. * Get the friendly name associated with the input class.
  81057. * @returns the input friendly name
  81058. */
  81059. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  81060. return "gamepad";
  81061. };
  81062. __decorate([
  81063. BABYLON.serialize()
  81064. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  81065. __decorate([
  81066. BABYLON.serialize()
  81067. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  81068. return FreeCameraGamepadInput;
  81069. }());
  81070. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  81071. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  81072. })(BABYLON || (BABYLON = {}));
  81073. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  81074. var BABYLON;
  81075. (function (BABYLON) {
  81076. /**
  81077. * Manage the gamepad inputs to control an arc rotate camera.
  81078. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  81079. */
  81080. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  81081. function ArcRotateCameraGamepadInput() {
  81082. /**
  81083. * Defines the gamepad rotation sensiblity.
  81084. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  81085. */
  81086. this.gamepadRotationSensibility = 80;
  81087. /**
  81088. * Defines the gamepad move sensiblity.
  81089. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81090. */
  81091. this.gamepadMoveSensibility = 40;
  81092. }
  81093. /**
  81094. * Attach the input controls to a specific dom element to get the input from.
  81095. * @param element Defines the element the controls should be listened from
  81096. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  81097. */
  81098. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  81099. var _this = this;
  81100. var manager = this.camera.getScene().gamepadManager;
  81101. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81102. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81103. // prioritize XBOX gamepads.
  81104. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  81105. _this.gamepad = gamepad;
  81106. }
  81107. }
  81108. });
  81109. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81110. if (_this.gamepad === gamepad) {
  81111. _this.gamepad = null;
  81112. }
  81113. });
  81114. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  81115. };
  81116. /**
  81117. * Detach the current controls from the specified dom element.
  81118. * @param element Defines the element to stop listening the inputs from
  81119. */
  81120. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  81121. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81122. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81123. this.gamepad = null;
  81124. };
  81125. /**
  81126. * Update the current camera state depending on the inputs that have been used this frame.
  81127. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  81128. */
  81129. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  81130. if (this.gamepad) {
  81131. var camera = this.camera;
  81132. var RSValues = this.gamepad.rightStick;
  81133. if (RSValues) {
  81134. if (RSValues.x != 0) {
  81135. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  81136. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  81137. camera.inertialAlphaOffset += normalizedRX;
  81138. }
  81139. }
  81140. if (RSValues.y != 0) {
  81141. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  81142. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  81143. camera.inertialBetaOffset += normalizedRY;
  81144. }
  81145. }
  81146. }
  81147. var LSValues = this.gamepad.leftStick;
  81148. if (LSValues && LSValues.y != 0) {
  81149. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  81150. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  81151. this.camera.inertialRadiusOffset -= normalizedLY;
  81152. }
  81153. }
  81154. }
  81155. };
  81156. /**
  81157. * Gets the class name of the current intput.
  81158. * @returns the class name
  81159. */
  81160. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  81161. return "ArcRotateCameraGamepadInput";
  81162. };
  81163. /**
  81164. * Get the friendly name associated with the input class.
  81165. * @returns the input friendly name
  81166. */
  81167. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  81168. return "gamepad";
  81169. };
  81170. __decorate([
  81171. BABYLON.serialize()
  81172. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  81173. __decorate([
  81174. BABYLON.serialize()
  81175. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  81176. return ArcRotateCameraGamepadInput;
  81177. }());
  81178. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  81179. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  81180. })(BABYLON || (BABYLON = {}));
  81181. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  81182. var BABYLON;
  81183. (function (BABYLON) {
  81184. /**
  81185. * Manager for handling gamepads
  81186. */
  81187. var GamepadManager = /** @class */ (function () {
  81188. /**
  81189. * Initializes the gamepad manager
  81190. * @param _scene BabylonJS scene
  81191. */
  81192. function GamepadManager(_scene) {
  81193. var _this = this;
  81194. this._scene = _scene;
  81195. this._babylonGamepads = [];
  81196. this._oneGamepadConnected = false;
  81197. /** @hidden */
  81198. this._isMonitoring = false;
  81199. /**
  81200. * observable to be triggered when the gamepad controller has been disconnected
  81201. */
  81202. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  81203. if (!BABYLON.Tools.IsWindowObjectExist()) {
  81204. this._gamepadEventSupported = false;
  81205. }
  81206. else {
  81207. this._gamepadEventSupported = 'GamepadEvent' in window;
  81208. this._gamepadSupport = (navigator.getGamepads ||
  81209. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  81210. }
  81211. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  81212. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  81213. for (var i in _this._babylonGamepads) {
  81214. var gamepad = _this._babylonGamepads[i];
  81215. if (gamepad && gamepad._isConnected) {
  81216. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  81217. }
  81218. }
  81219. });
  81220. this._onGamepadConnectedEvent = function (evt) {
  81221. var gamepad = evt.gamepad;
  81222. if (gamepad.index in _this._babylonGamepads) {
  81223. if (_this._babylonGamepads[gamepad.index].isConnected) {
  81224. return;
  81225. }
  81226. }
  81227. var newGamepad;
  81228. if (_this._babylonGamepads[gamepad.index]) {
  81229. newGamepad = _this._babylonGamepads[gamepad.index];
  81230. newGamepad.browserGamepad = gamepad;
  81231. newGamepad._isConnected = true;
  81232. }
  81233. else {
  81234. newGamepad = _this._addNewGamepad(gamepad);
  81235. }
  81236. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  81237. _this._startMonitoringGamepads();
  81238. };
  81239. this._onGamepadDisconnectedEvent = function (evt) {
  81240. var gamepad = evt.gamepad;
  81241. // Remove the gamepad from the list of gamepads to monitor.
  81242. for (var i in _this._babylonGamepads) {
  81243. if (_this._babylonGamepads[i].index === gamepad.index) {
  81244. var disconnectedGamepad = _this._babylonGamepads[i];
  81245. disconnectedGamepad._isConnected = false;
  81246. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  81247. break;
  81248. }
  81249. }
  81250. };
  81251. if (this._gamepadSupport) {
  81252. //first add already-connected gamepads
  81253. this._updateGamepadObjects();
  81254. if (this._babylonGamepads.length) {
  81255. this._startMonitoringGamepads();
  81256. }
  81257. // Checking if the gamepad connected event is supported (like in Firefox)
  81258. if (this._gamepadEventSupported) {
  81259. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  81260. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  81261. }
  81262. else {
  81263. this._startMonitoringGamepads();
  81264. }
  81265. }
  81266. }
  81267. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  81268. /**
  81269. * The gamepads in the game pad manager
  81270. */
  81271. get: function () {
  81272. return this._babylonGamepads;
  81273. },
  81274. enumerable: true,
  81275. configurable: true
  81276. });
  81277. /**
  81278. * Get the gamepad controllers based on type
  81279. * @param type The type of gamepad controller
  81280. * @returns Nullable gamepad
  81281. */
  81282. GamepadManager.prototype.getGamepadByType = function (type) {
  81283. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  81284. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  81285. var gamepad = _a[_i];
  81286. if (gamepad && gamepad.type === type) {
  81287. return gamepad;
  81288. }
  81289. }
  81290. return null;
  81291. };
  81292. /**
  81293. * Disposes the gamepad manager
  81294. */
  81295. GamepadManager.prototype.dispose = function () {
  81296. if (this._gamepadEventSupported) {
  81297. if (this._onGamepadConnectedEvent) {
  81298. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  81299. }
  81300. if (this._onGamepadDisconnectedEvent) {
  81301. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  81302. }
  81303. this._onGamepadConnectedEvent = null;
  81304. this._onGamepadDisconnectedEvent = null;
  81305. }
  81306. this._babylonGamepads.forEach(function (gamepad) {
  81307. gamepad.dispose();
  81308. });
  81309. this.onGamepadConnectedObservable.clear();
  81310. this.onGamepadDisconnectedObservable.clear();
  81311. this._oneGamepadConnected = false;
  81312. this._stopMonitoringGamepads();
  81313. this._babylonGamepads = [];
  81314. };
  81315. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  81316. if (!this._oneGamepadConnected) {
  81317. this._oneGamepadConnected = true;
  81318. }
  81319. var newGamepad;
  81320. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  81321. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  81322. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  81323. }
  81324. // if pose is supported, use the (WebVR) pose enabled controller
  81325. else if (gamepad.pose) {
  81326. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  81327. }
  81328. else {
  81329. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  81330. }
  81331. this._babylonGamepads[newGamepad.index] = newGamepad;
  81332. return newGamepad;
  81333. };
  81334. GamepadManager.prototype._startMonitoringGamepads = function () {
  81335. if (!this._isMonitoring) {
  81336. this._isMonitoring = true;
  81337. //back-comp
  81338. if (!this._scene) {
  81339. this._checkGamepadsStatus();
  81340. }
  81341. }
  81342. };
  81343. GamepadManager.prototype._stopMonitoringGamepads = function () {
  81344. this._isMonitoring = false;
  81345. };
  81346. /** @hidden */
  81347. GamepadManager.prototype._checkGamepadsStatus = function () {
  81348. var _this = this;
  81349. // Hack to be compatible Chrome
  81350. this._updateGamepadObjects();
  81351. for (var i in this._babylonGamepads) {
  81352. var gamepad = this._babylonGamepads[i];
  81353. if (!gamepad || !gamepad.isConnected) {
  81354. continue;
  81355. }
  81356. gamepad.update();
  81357. }
  81358. if (this._isMonitoring && !this._scene) {
  81359. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  81360. }
  81361. };
  81362. // This function is called only on Chrome, which does not properly support
  81363. // connection/disconnection events and forces you to recopy again the gamepad object
  81364. GamepadManager.prototype._updateGamepadObjects = function () {
  81365. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  81366. for (var i = 0; i < gamepads.length; i++) {
  81367. var gamepad = gamepads[i];
  81368. if (gamepad) {
  81369. if (!this._babylonGamepads[gamepad.index]) {
  81370. var newGamepad = this._addNewGamepad(gamepad);
  81371. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  81372. }
  81373. else {
  81374. // Forced to copy again this object for Chrome for unknown reason
  81375. this._babylonGamepads[i].browserGamepad = gamepad;
  81376. if (!this._babylonGamepads[i].isConnected) {
  81377. this._babylonGamepads[i]._isConnected = true;
  81378. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  81379. }
  81380. }
  81381. }
  81382. }
  81383. };
  81384. return GamepadManager;
  81385. }());
  81386. BABYLON.GamepadManager = GamepadManager;
  81387. })(BABYLON || (BABYLON = {}));
  81388. //# sourceMappingURL=babylon.gamepadManager.js.map
  81389. var BABYLON;
  81390. (function (BABYLON) {
  81391. /**
  81392. * Represents a gamepad control stick position
  81393. */
  81394. var StickValues = /** @class */ (function () {
  81395. /**
  81396. * Initializes the gamepad x and y control stick values
  81397. * @param x The x component of the gamepad control stick value
  81398. * @param y The y component of the gamepad control stick value
  81399. */
  81400. function StickValues(
  81401. /**
  81402. * The x component of the control stick
  81403. */
  81404. x,
  81405. /**
  81406. * The y component of the control stick
  81407. */
  81408. y) {
  81409. this.x = x;
  81410. this.y = y;
  81411. }
  81412. return StickValues;
  81413. }());
  81414. BABYLON.StickValues = StickValues;
  81415. /**
  81416. * Represents a gamepad
  81417. */
  81418. var Gamepad = /** @class */ (function () {
  81419. /**
  81420. * Initializes the gamepad
  81421. * @param id The id of the gamepad
  81422. * @param index The index of the gamepad
  81423. * @param browserGamepad The browser gamepad
  81424. * @param leftStickX The x component of the left joystick
  81425. * @param leftStickY The y component of the left joystick
  81426. * @param rightStickX The x component of the right joystick
  81427. * @param rightStickY The y component of the right joystick
  81428. */
  81429. function Gamepad(
  81430. /**
  81431. * The id of the gamepad
  81432. */
  81433. id,
  81434. /**
  81435. * The index of the gamepad
  81436. */
  81437. index,
  81438. /**
  81439. * The browser gamepad
  81440. */
  81441. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  81442. if (leftStickX === void 0) { leftStickX = 0; }
  81443. if (leftStickY === void 0) { leftStickY = 1; }
  81444. if (rightStickX === void 0) { rightStickX = 2; }
  81445. if (rightStickY === void 0) { rightStickY = 3; }
  81446. this.id = id;
  81447. this.index = index;
  81448. this.browserGamepad = browserGamepad;
  81449. this._leftStick = { x: 0, y: 0 };
  81450. this._rightStick = { x: 0, y: 0 };
  81451. /** @hidden */
  81452. this._isConnected = true;
  81453. /**
  81454. * Specifies whether the left control stick should be Y-inverted
  81455. */
  81456. this._invertLeftStickY = false;
  81457. this.type = Gamepad.GAMEPAD;
  81458. this._leftStickAxisX = leftStickX;
  81459. this._leftStickAxisY = leftStickY;
  81460. this._rightStickAxisX = rightStickX;
  81461. this._rightStickAxisY = rightStickY;
  81462. if (this.browserGamepad.axes.length >= 2) {
  81463. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  81464. }
  81465. if (this.browserGamepad.axes.length >= 4) {
  81466. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  81467. }
  81468. }
  81469. Object.defineProperty(Gamepad.prototype, "isConnected", {
  81470. /**
  81471. * Specifies if the gamepad has been connected
  81472. */
  81473. get: function () {
  81474. return this._isConnected;
  81475. },
  81476. enumerable: true,
  81477. configurable: true
  81478. });
  81479. /**
  81480. * Callback triggered when the left joystick has changed
  81481. * @param callback
  81482. */
  81483. Gamepad.prototype.onleftstickchanged = function (callback) {
  81484. this._onleftstickchanged = callback;
  81485. };
  81486. /**
  81487. * Callback triggered when the right joystick has changed
  81488. * @param callback
  81489. */
  81490. Gamepad.prototype.onrightstickchanged = function (callback) {
  81491. this._onrightstickchanged = callback;
  81492. };
  81493. Object.defineProperty(Gamepad.prototype, "leftStick", {
  81494. /**
  81495. * Gets the left joystick
  81496. */
  81497. get: function () {
  81498. return this._leftStick;
  81499. },
  81500. /**
  81501. * Sets the left joystick values
  81502. */
  81503. set: function (newValues) {
  81504. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  81505. this._onleftstickchanged(newValues);
  81506. }
  81507. this._leftStick = newValues;
  81508. },
  81509. enumerable: true,
  81510. configurable: true
  81511. });
  81512. Object.defineProperty(Gamepad.prototype, "rightStick", {
  81513. /**
  81514. * Gets the right joystick
  81515. */
  81516. get: function () {
  81517. return this._rightStick;
  81518. },
  81519. /**
  81520. * Sets the right joystick value
  81521. */
  81522. set: function (newValues) {
  81523. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  81524. this._onrightstickchanged(newValues);
  81525. }
  81526. this._rightStick = newValues;
  81527. },
  81528. enumerable: true,
  81529. configurable: true
  81530. });
  81531. /**
  81532. * Updates the gamepad joystick positions
  81533. */
  81534. Gamepad.prototype.update = function () {
  81535. if (this._leftStick) {
  81536. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  81537. if (this._invertLeftStickY) {
  81538. this.leftStick.y *= -1;
  81539. }
  81540. }
  81541. if (this._rightStick) {
  81542. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  81543. }
  81544. };
  81545. /**
  81546. * Disposes the gamepad
  81547. */
  81548. Gamepad.prototype.dispose = function () {
  81549. };
  81550. /**
  81551. * Represents a gamepad controller
  81552. */
  81553. Gamepad.GAMEPAD = 0;
  81554. /**
  81555. * Represents a generic controller
  81556. */
  81557. Gamepad.GENERIC = 1;
  81558. /**
  81559. * Represents an XBox controller
  81560. */
  81561. Gamepad.XBOX = 2;
  81562. /**
  81563. * Represents a pose-enabled controller
  81564. */
  81565. Gamepad.POSE_ENABLED = 3;
  81566. return Gamepad;
  81567. }());
  81568. BABYLON.Gamepad = Gamepad;
  81569. /**
  81570. * Represents a generic gamepad
  81571. */
  81572. var GenericPad = /** @class */ (function (_super) {
  81573. __extends(GenericPad, _super);
  81574. /**
  81575. * Initializes the generic gamepad
  81576. * @param id The id of the generic gamepad
  81577. * @param index The index of the generic gamepad
  81578. * @param browserGamepad The browser gamepad
  81579. */
  81580. function GenericPad(id, index, browserGamepad) {
  81581. var _this = _super.call(this, id, index, browserGamepad) || this;
  81582. /**
  81583. * Observable triggered when a button has been pressed
  81584. */
  81585. _this.onButtonDownObservable = new BABYLON.Observable();
  81586. /**
  81587. * Observable triggered when a button has been released
  81588. */
  81589. _this.onButtonUpObservable = new BABYLON.Observable();
  81590. _this.type = Gamepad.GENERIC;
  81591. _this._buttons = new Array(browserGamepad.buttons.length);
  81592. return _this;
  81593. }
  81594. /**
  81595. * Callback triggered when a button has been pressed
  81596. * @param callback Called when a button has been pressed
  81597. */
  81598. GenericPad.prototype.onbuttondown = function (callback) {
  81599. this._onbuttondown = callback;
  81600. };
  81601. /**
  81602. * Callback triggered when a button has been released
  81603. * @param callback Called when a button has been released
  81604. */
  81605. GenericPad.prototype.onbuttonup = function (callback) {
  81606. this._onbuttonup = callback;
  81607. };
  81608. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  81609. if (newValue !== currentValue) {
  81610. if (newValue === 1) {
  81611. if (this._onbuttondown) {
  81612. this._onbuttondown(buttonIndex);
  81613. }
  81614. this.onButtonDownObservable.notifyObservers(buttonIndex);
  81615. }
  81616. if (newValue === 0) {
  81617. if (this._onbuttonup) {
  81618. this._onbuttonup(buttonIndex);
  81619. }
  81620. this.onButtonUpObservable.notifyObservers(buttonIndex);
  81621. }
  81622. }
  81623. return newValue;
  81624. };
  81625. /**
  81626. * Updates the generic gamepad
  81627. */
  81628. GenericPad.prototype.update = function () {
  81629. _super.prototype.update.call(this);
  81630. for (var index = 0; index < this._buttons.length; index++) {
  81631. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  81632. }
  81633. };
  81634. /**
  81635. * Disposes the generic gamepad
  81636. */
  81637. GenericPad.prototype.dispose = function () {
  81638. _super.prototype.dispose.call(this);
  81639. this.onButtonDownObservable.clear();
  81640. this.onButtonUpObservable.clear();
  81641. };
  81642. return GenericPad;
  81643. }(Gamepad));
  81644. BABYLON.GenericPad = GenericPad;
  81645. })(BABYLON || (BABYLON = {}));
  81646. //# sourceMappingURL=babylon.gamepad.js.map
  81647. var BABYLON;
  81648. (function (BABYLON) {
  81649. /**
  81650. * Defines supported buttons for XBox360 compatible gamepads
  81651. */
  81652. var Xbox360Button;
  81653. (function (Xbox360Button) {
  81654. /** A */
  81655. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  81656. /** B */
  81657. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  81658. /** X */
  81659. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  81660. /** Y */
  81661. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  81662. /** Start */
  81663. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  81664. /** Back */
  81665. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  81666. /** Left button */
  81667. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  81668. /** Right button */
  81669. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  81670. /** Left stick */
  81671. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  81672. /** Right stick */
  81673. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  81674. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  81675. /** Defines values for XBox360 DPad */
  81676. var Xbox360Dpad;
  81677. (function (Xbox360Dpad) {
  81678. /** Up */
  81679. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  81680. /** Down */
  81681. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  81682. /** Left */
  81683. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  81684. /** Right */
  81685. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  81686. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  81687. /**
  81688. * Defines a XBox360 gamepad
  81689. */
  81690. var Xbox360Pad = /** @class */ (function (_super) {
  81691. __extends(Xbox360Pad, _super);
  81692. /**
  81693. * Creates a new XBox360 gamepad object
  81694. * @param id defines the id of this gamepad
  81695. * @param index defines its index
  81696. * @param gamepad defines the internal HTML gamepad object
  81697. * @param xboxOne defines if it is a XBox One gamepad
  81698. */
  81699. function Xbox360Pad(id, index, gamepad, xboxOne) {
  81700. if (xboxOne === void 0) { xboxOne = false; }
  81701. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  81702. _this._leftTrigger = 0;
  81703. _this._rightTrigger = 0;
  81704. /** Observable raised when a button is pressed */
  81705. _this.onButtonDownObservable = new BABYLON.Observable();
  81706. /** Observable raised when a button is released */
  81707. _this.onButtonUpObservable = new BABYLON.Observable();
  81708. /** Observable raised when a pad is pressed */
  81709. _this.onPadDownObservable = new BABYLON.Observable();
  81710. /** Observable raised when a pad is released */
  81711. _this.onPadUpObservable = new BABYLON.Observable();
  81712. _this._buttonA = 0;
  81713. _this._buttonB = 0;
  81714. _this._buttonX = 0;
  81715. _this._buttonY = 0;
  81716. _this._buttonBack = 0;
  81717. _this._buttonStart = 0;
  81718. _this._buttonLB = 0;
  81719. _this._buttonRB = 0;
  81720. _this._buttonLeftStick = 0;
  81721. _this._buttonRightStick = 0;
  81722. _this._dPadUp = 0;
  81723. _this._dPadDown = 0;
  81724. _this._dPadLeft = 0;
  81725. _this._dPadRight = 0;
  81726. _this._isXboxOnePad = false;
  81727. _this.type = BABYLON.Gamepad.XBOX;
  81728. _this._isXboxOnePad = xboxOne;
  81729. return _this;
  81730. }
  81731. /**
  81732. * Defines the callback to call when left trigger is pressed
  81733. * @param callback defines the callback to use
  81734. */
  81735. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  81736. this._onlefttriggerchanged = callback;
  81737. };
  81738. /**
  81739. * Defines the callback to call when right trigger is pressed
  81740. * @param callback defines the callback to use
  81741. */
  81742. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  81743. this._onrighttriggerchanged = callback;
  81744. };
  81745. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  81746. /**
  81747. * Gets the left trigger value
  81748. */
  81749. get: function () {
  81750. return this._leftTrigger;
  81751. },
  81752. /**
  81753. * Sets the left trigger value
  81754. */
  81755. set: function (newValue) {
  81756. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  81757. this._onlefttriggerchanged(newValue);
  81758. }
  81759. this._leftTrigger = newValue;
  81760. },
  81761. enumerable: true,
  81762. configurable: true
  81763. });
  81764. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  81765. /**
  81766. * Gets the right trigger value
  81767. */
  81768. get: function () {
  81769. return this._rightTrigger;
  81770. },
  81771. /**
  81772. * Sets the right trigger value
  81773. */
  81774. set: function (newValue) {
  81775. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  81776. this._onrighttriggerchanged(newValue);
  81777. }
  81778. this._rightTrigger = newValue;
  81779. },
  81780. enumerable: true,
  81781. configurable: true
  81782. });
  81783. /**
  81784. * Defines the callback to call when a button is pressed
  81785. * @param callback defines the callback to use
  81786. */
  81787. Xbox360Pad.prototype.onbuttondown = function (callback) {
  81788. this._onbuttondown = callback;
  81789. };
  81790. /**
  81791. * Defines the callback to call when a button is released
  81792. * @param callback defines the callback to use
  81793. */
  81794. Xbox360Pad.prototype.onbuttonup = function (callback) {
  81795. this._onbuttonup = callback;
  81796. };
  81797. /**
  81798. * Defines the callback to call when a pad is pressed
  81799. * @param callback defines the callback to use
  81800. */
  81801. Xbox360Pad.prototype.ondpaddown = function (callback) {
  81802. this._ondpaddown = callback;
  81803. };
  81804. /**
  81805. * Defines the callback to call when a pad is released
  81806. * @param callback defines the callback to use
  81807. */
  81808. Xbox360Pad.prototype.ondpadup = function (callback) {
  81809. this._ondpadup = callback;
  81810. };
  81811. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  81812. if (newValue !== currentValue) {
  81813. if (newValue === 1) {
  81814. if (this._onbuttondown) {
  81815. this._onbuttondown(buttonType);
  81816. }
  81817. this.onButtonDownObservable.notifyObservers(buttonType);
  81818. }
  81819. if (newValue === 0) {
  81820. if (this._onbuttonup) {
  81821. this._onbuttonup(buttonType);
  81822. }
  81823. this.onButtonUpObservable.notifyObservers(buttonType);
  81824. }
  81825. }
  81826. return newValue;
  81827. };
  81828. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  81829. if (newValue !== currentValue) {
  81830. if (newValue === 1) {
  81831. if (this._ondpaddown) {
  81832. this._ondpaddown(buttonType);
  81833. }
  81834. this.onPadDownObservable.notifyObservers(buttonType);
  81835. }
  81836. if (newValue === 0) {
  81837. if (this._ondpadup) {
  81838. this._ondpadup(buttonType);
  81839. }
  81840. this.onPadUpObservable.notifyObservers(buttonType);
  81841. }
  81842. }
  81843. return newValue;
  81844. };
  81845. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  81846. /**
  81847. * Gets the value of the `A` button
  81848. */
  81849. get: function () {
  81850. return this._buttonA;
  81851. },
  81852. /**
  81853. * Sets the value of the `A` button
  81854. */
  81855. set: function (value) {
  81856. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  81857. },
  81858. enumerable: true,
  81859. configurable: true
  81860. });
  81861. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  81862. /**
  81863. * Gets the value of the `B` button
  81864. */
  81865. get: function () {
  81866. return this._buttonB;
  81867. },
  81868. /**
  81869. * Sets the value of the `B` button
  81870. */
  81871. set: function (value) {
  81872. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  81873. },
  81874. enumerable: true,
  81875. configurable: true
  81876. });
  81877. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  81878. /**
  81879. * Gets the value of the `X` button
  81880. */
  81881. get: function () {
  81882. return this._buttonX;
  81883. },
  81884. /**
  81885. * Sets the value of the `X` button
  81886. */
  81887. set: function (value) {
  81888. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  81889. },
  81890. enumerable: true,
  81891. configurable: true
  81892. });
  81893. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  81894. /**
  81895. * Gets the value of the `Y` button
  81896. */
  81897. get: function () {
  81898. return this._buttonY;
  81899. },
  81900. /**
  81901. * Sets the value of the `Y` button
  81902. */
  81903. set: function (value) {
  81904. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  81905. },
  81906. enumerable: true,
  81907. configurable: true
  81908. });
  81909. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  81910. /**
  81911. * Gets the value of the `Start` button
  81912. */
  81913. get: function () {
  81914. return this._buttonStart;
  81915. },
  81916. /**
  81917. * Sets the value of the `Start` button
  81918. */
  81919. set: function (value) {
  81920. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  81921. },
  81922. enumerable: true,
  81923. configurable: true
  81924. });
  81925. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  81926. /**
  81927. * Gets the value of the `Back` button
  81928. */
  81929. get: function () {
  81930. return this._buttonBack;
  81931. },
  81932. /**
  81933. * Sets the value of the `Back` button
  81934. */
  81935. set: function (value) {
  81936. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  81937. },
  81938. enumerable: true,
  81939. configurable: true
  81940. });
  81941. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  81942. /**
  81943. * Gets the value of the `Left` button
  81944. */
  81945. get: function () {
  81946. return this._buttonLB;
  81947. },
  81948. /**
  81949. * Sets the value of the `Left` button
  81950. */
  81951. set: function (value) {
  81952. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  81953. },
  81954. enumerable: true,
  81955. configurable: true
  81956. });
  81957. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  81958. /**
  81959. * Gets the value of the `Right` button
  81960. */
  81961. get: function () {
  81962. return this._buttonRB;
  81963. },
  81964. /**
  81965. * Sets the value of the `Right` button
  81966. */
  81967. set: function (value) {
  81968. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  81969. },
  81970. enumerable: true,
  81971. configurable: true
  81972. });
  81973. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  81974. /**
  81975. * Gets the value of the Left joystick
  81976. */
  81977. get: function () {
  81978. return this._buttonLeftStick;
  81979. },
  81980. /**
  81981. * Sets the value of the Left joystick
  81982. */
  81983. set: function (value) {
  81984. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  81985. },
  81986. enumerable: true,
  81987. configurable: true
  81988. });
  81989. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  81990. /**
  81991. * Gets the value of the Right joystick
  81992. */
  81993. get: function () {
  81994. return this._buttonRightStick;
  81995. },
  81996. /**
  81997. * Sets the value of the Right joystick
  81998. */
  81999. set: function (value) {
  82000. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  82001. },
  82002. enumerable: true,
  82003. configurable: true
  82004. });
  82005. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  82006. /**
  82007. * Gets the value of D-pad up
  82008. */
  82009. get: function () {
  82010. return this._dPadUp;
  82011. },
  82012. /**
  82013. * Sets the value of D-pad up
  82014. */
  82015. set: function (value) {
  82016. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  82017. },
  82018. enumerable: true,
  82019. configurable: true
  82020. });
  82021. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  82022. /**
  82023. * Gets the value of D-pad down
  82024. */
  82025. get: function () {
  82026. return this._dPadDown;
  82027. },
  82028. /**
  82029. * Sets the value of D-pad down
  82030. */
  82031. set: function (value) {
  82032. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  82033. },
  82034. enumerable: true,
  82035. configurable: true
  82036. });
  82037. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  82038. /**
  82039. * Gets the value of D-pad left
  82040. */
  82041. get: function () {
  82042. return this._dPadLeft;
  82043. },
  82044. /**
  82045. * Sets the value of D-pad left
  82046. */
  82047. set: function (value) {
  82048. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  82049. },
  82050. enumerable: true,
  82051. configurable: true
  82052. });
  82053. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  82054. /**
  82055. * Gets the value of D-pad right
  82056. */
  82057. get: function () {
  82058. return this._dPadRight;
  82059. },
  82060. /**
  82061. * Sets the value of D-pad right
  82062. */
  82063. set: function (value) {
  82064. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  82065. },
  82066. enumerable: true,
  82067. configurable: true
  82068. });
  82069. /**
  82070. * Force the gamepad to synchronize with device values
  82071. */
  82072. Xbox360Pad.prototype.update = function () {
  82073. _super.prototype.update.call(this);
  82074. if (this._isXboxOnePad) {
  82075. this.buttonA = this.browserGamepad.buttons[0].value;
  82076. this.buttonB = this.browserGamepad.buttons[1].value;
  82077. this.buttonX = this.browserGamepad.buttons[2].value;
  82078. this.buttonY = this.browserGamepad.buttons[3].value;
  82079. this.buttonLB = this.browserGamepad.buttons[4].value;
  82080. this.buttonRB = this.browserGamepad.buttons[5].value;
  82081. this.leftTrigger = this.browserGamepad.axes[2];
  82082. this.rightTrigger = this.browserGamepad.axes[5];
  82083. this.buttonBack = this.browserGamepad.buttons[9].value;
  82084. this.buttonStart = this.browserGamepad.buttons[8].value;
  82085. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  82086. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  82087. this.dPadUp = this.browserGamepad.buttons[11].value;
  82088. this.dPadDown = this.browserGamepad.buttons[12].value;
  82089. this.dPadLeft = this.browserGamepad.buttons[13].value;
  82090. this.dPadRight = this.browserGamepad.buttons[14].value;
  82091. }
  82092. else {
  82093. this.buttonA = this.browserGamepad.buttons[0].value;
  82094. this.buttonB = this.browserGamepad.buttons[1].value;
  82095. this.buttonX = this.browserGamepad.buttons[2].value;
  82096. this.buttonY = this.browserGamepad.buttons[3].value;
  82097. this.buttonLB = this.browserGamepad.buttons[4].value;
  82098. this.buttonRB = this.browserGamepad.buttons[5].value;
  82099. this.leftTrigger = this.browserGamepad.buttons[6].value;
  82100. this.rightTrigger = this.browserGamepad.buttons[7].value;
  82101. this.buttonBack = this.browserGamepad.buttons[8].value;
  82102. this.buttonStart = this.browserGamepad.buttons[9].value;
  82103. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  82104. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  82105. this.dPadUp = this.browserGamepad.buttons[12].value;
  82106. this.dPadDown = this.browserGamepad.buttons[13].value;
  82107. this.dPadLeft = this.browserGamepad.buttons[14].value;
  82108. this.dPadRight = this.browserGamepad.buttons[15].value;
  82109. }
  82110. };
  82111. /**
  82112. * Disposes the gamepad
  82113. */
  82114. Xbox360Pad.prototype.dispose = function () {
  82115. _super.prototype.dispose.call(this);
  82116. this.onButtonDownObservable.clear();
  82117. this.onButtonUpObservable.clear();
  82118. this.onPadDownObservable.clear();
  82119. this.onPadUpObservable.clear();
  82120. };
  82121. return Xbox360Pad;
  82122. }(BABYLON.Gamepad));
  82123. BABYLON.Xbox360Pad = Xbox360Pad;
  82124. })(BABYLON || (BABYLON = {}));
  82125. //# sourceMappingURL=babylon.xboxGamepad.js.map
  82126. var BABYLON;
  82127. (function (BABYLON) {
  82128. /**
  82129. * Defines the types of pose enabled controllers that are supported
  82130. */
  82131. var PoseEnabledControllerType;
  82132. (function (PoseEnabledControllerType) {
  82133. /**
  82134. * HTC Vive
  82135. */
  82136. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  82137. /**
  82138. * Oculus Rift
  82139. */
  82140. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  82141. /**
  82142. * Windows mixed reality
  82143. */
  82144. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  82145. /**
  82146. * Samsung gear VR
  82147. */
  82148. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  82149. /**
  82150. * Google Daydream
  82151. */
  82152. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  82153. /**
  82154. * Generic
  82155. */
  82156. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  82157. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  82158. /**
  82159. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  82160. */
  82161. var PoseEnabledControllerHelper = /** @class */ (function () {
  82162. function PoseEnabledControllerHelper() {
  82163. }
  82164. /**
  82165. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  82166. * @param vrGamepad the gamepad to initialized
  82167. * @returns a vr controller of the type the gamepad identified as
  82168. */
  82169. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  82170. // Oculus Touch
  82171. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  82172. return new BABYLON.OculusTouchController(vrGamepad);
  82173. }
  82174. // Windows Mixed Reality controllers
  82175. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  82176. return new BABYLON.WindowsMotionController(vrGamepad);
  82177. }
  82178. // HTC Vive
  82179. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  82180. return new BABYLON.ViveController(vrGamepad);
  82181. }
  82182. // Samsung/Oculus Gear VR or Oculus Go
  82183. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  82184. return new BABYLON.GearVRController(vrGamepad);
  82185. }
  82186. // Google Daydream
  82187. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  82188. return new BABYLON.DaydreamController(vrGamepad);
  82189. }
  82190. // Generic
  82191. else {
  82192. return new BABYLON.GenericController(vrGamepad);
  82193. }
  82194. };
  82195. return PoseEnabledControllerHelper;
  82196. }());
  82197. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  82198. /**
  82199. * Defines the PoseEnabledController object that contains state of a vr capable controller
  82200. */
  82201. var PoseEnabledController = /** @class */ (function (_super) {
  82202. __extends(PoseEnabledController, _super);
  82203. /**
  82204. * Creates a new PoseEnabledController from a gamepad
  82205. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  82206. */
  82207. function PoseEnabledController(browserGamepad) {
  82208. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  82209. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  82210. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  82211. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  82212. /**
  82213. * The device position in babylon space
  82214. */
  82215. _this.devicePosition = BABYLON.Vector3.Zero();
  82216. /**
  82217. * The device rotation in babylon space
  82218. */
  82219. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  82220. /**
  82221. * The scale factor of the device in babylon space
  82222. */
  82223. _this.deviceScaleFactor = 1;
  82224. // Used to convert 6dof controllers to 3dof
  82225. _this._trackPosition = true;
  82226. _this._maxRotationDistFromHeadset = Math.PI / 5;
  82227. _this._draggedRoomRotation = 0;
  82228. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  82229. /**
  82230. * Internal, matrix used to convert room space to babylon space
  82231. * @hidden
  82232. */
  82233. _this._deviceToWorld = BABYLON.Matrix.Identity();
  82234. /**
  82235. * Node to be used when casting a ray from the controller
  82236. * @hidden
  82237. */
  82238. _this._pointingPoseNode = null;
  82239. _this._workingMatrix = BABYLON.Matrix.Identity();
  82240. /**
  82241. * @hidden
  82242. */
  82243. _this._meshAttachedObservable = new BABYLON.Observable();
  82244. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  82245. _this.controllerType = PoseEnabledControllerType.GENERIC;
  82246. _this.position = BABYLON.Vector3.Zero();
  82247. _this.rotationQuaternion = new BABYLON.Quaternion();
  82248. _this._calculatedPosition = BABYLON.Vector3.Zero();
  82249. _this._calculatedRotation = new BABYLON.Quaternion();
  82250. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  82251. return _this;
  82252. }
  82253. /**
  82254. * @hidden
  82255. */
  82256. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  82257. if (this._trackPosition) {
  82258. this._calculatedPosition.copyFrom(fixedPosition);
  82259. this._trackPosition = false;
  82260. }
  82261. };
  82262. /**
  82263. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  82264. */
  82265. PoseEnabledController.prototype.update = function () {
  82266. _super.prototype.update.call(this);
  82267. this._updatePoseAndMesh();
  82268. };
  82269. /**
  82270. * Updates only the pose device and mesh without doing any button event checking
  82271. */
  82272. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  82273. var pose = this.browserGamepad.pose;
  82274. this.updateFromDevice(pose);
  82275. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  82276. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  82277. camera._computeDevicePosition();
  82278. this._deviceToWorld.setTranslation(camera.devicePosition);
  82279. if (camera.deviceRotationQuaternion) {
  82280. var camera = camera;
  82281. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  82282. // Find the radian distance away that the headset is from the controllers rotation
  82283. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  82284. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  82285. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  82286. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  82287. this._draggedRoomRotation += rotationAmount;
  82288. // Rotate controller around headset
  82289. var sin = Math.sin(-rotationAmount);
  82290. var cos = Math.cos(-rotationAmount);
  82291. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  82292. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  82293. }
  82294. }
  82295. }
  82296. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  82297. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  82298. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82299. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  82300. if (this._mesh) {
  82301. this._mesh.position.copyFrom(this.devicePosition);
  82302. if (this._mesh.rotationQuaternion) {
  82303. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  82304. }
  82305. }
  82306. };
  82307. /**
  82308. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  82309. * @param poseData raw pose fromthe device
  82310. */
  82311. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  82312. if (poseData) {
  82313. this.rawPose = poseData;
  82314. if (poseData.position) {
  82315. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  82316. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  82317. this._deviceRoomPosition.z *= -1;
  82318. }
  82319. if (this._trackPosition) {
  82320. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  82321. }
  82322. this._calculatedPosition.addInPlace(this.position);
  82323. }
  82324. var pose = this.rawPose;
  82325. if (poseData.orientation && pose.orientation) {
  82326. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  82327. if (this._mesh) {
  82328. if (this._mesh.getScene().useRightHandedSystem) {
  82329. this._deviceRoomRotationQuaternion.z *= -1;
  82330. this._deviceRoomRotationQuaternion.w *= -1;
  82331. }
  82332. else {
  82333. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  82334. }
  82335. }
  82336. // if the camera is set, rotate to the camera's rotation
  82337. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  82338. }
  82339. }
  82340. };
  82341. /**
  82342. * Attaches a mesh to the controller
  82343. * @param mesh the mesh to be attached
  82344. */
  82345. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  82346. if (this._mesh) {
  82347. this._mesh.parent = null;
  82348. }
  82349. this._mesh = mesh;
  82350. if (this._poseControlledCamera) {
  82351. this._mesh.parent = this._poseControlledCamera;
  82352. }
  82353. if (!this._mesh.rotationQuaternion) {
  82354. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  82355. }
  82356. // 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
  82357. this._updatePoseAndMesh();
  82358. if (this._pointingPoseNode) {
  82359. var parents = [];
  82360. var obj = this._pointingPoseNode;
  82361. while (obj.parent) {
  82362. parents.push(obj.parent);
  82363. obj = obj.parent;
  82364. }
  82365. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  82366. }
  82367. this._meshAttachedObservable.notifyObservers(mesh);
  82368. };
  82369. /**
  82370. * Attaches the controllers mesh to a camera
  82371. * @param camera the camera the mesh should be attached to
  82372. */
  82373. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  82374. this._poseControlledCamera = camera;
  82375. if (this._mesh) {
  82376. this._mesh.parent = this._poseControlledCamera;
  82377. }
  82378. };
  82379. /**
  82380. * Disposes of the controller
  82381. */
  82382. PoseEnabledController.prototype.dispose = function () {
  82383. if (this._mesh) {
  82384. this._mesh.dispose();
  82385. }
  82386. this._mesh = null;
  82387. _super.prototype.dispose.call(this);
  82388. };
  82389. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  82390. /**
  82391. * The mesh that is attached to the controller
  82392. */
  82393. get: function () {
  82394. return this._mesh;
  82395. },
  82396. enumerable: true,
  82397. configurable: true
  82398. });
  82399. /**
  82400. * Gets the ray of the controller in the direction the controller is pointing
  82401. * @param length the length the resulting ray should be
  82402. * @returns a ray in the direction the controller is pointing
  82403. */
  82404. PoseEnabledController.prototype.getForwardRay = function (length) {
  82405. if (length === void 0) { length = 100; }
  82406. if (!this.mesh) {
  82407. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  82408. }
  82409. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  82410. var origin = m.getTranslation();
  82411. var forward = new BABYLON.Vector3(0, 0, -1);
  82412. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  82413. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  82414. return new BABYLON.Ray(origin, direction, length);
  82415. };
  82416. /**
  82417. * Name of the child mesh that can be used to cast a ray from the controller
  82418. */
  82419. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  82420. return PoseEnabledController;
  82421. }(BABYLON.Gamepad));
  82422. BABYLON.PoseEnabledController = PoseEnabledController;
  82423. })(BABYLON || (BABYLON = {}));
  82424. //# sourceMappingURL=babylon.poseEnabledController.js.map
  82425. var BABYLON;
  82426. (function (BABYLON) {
  82427. /**
  82428. * Defines the WebVRController object that represents controllers tracked in 3D space
  82429. */
  82430. var WebVRController = /** @class */ (function (_super) {
  82431. __extends(WebVRController, _super);
  82432. /**
  82433. * Creates a new WebVRController from a gamepad
  82434. * @param vrGamepad the gamepad that the WebVRController should be created from
  82435. */
  82436. function WebVRController(vrGamepad) {
  82437. var _this = _super.call(this, vrGamepad) || this;
  82438. // Observables
  82439. /**
  82440. * Fired when the trigger state has changed
  82441. */
  82442. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  82443. /**
  82444. * Fired when the main button state has changed
  82445. */
  82446. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  82447. /**
  82448. * Fired when the secondary button state has changed
  82449. */
  82450. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  82451. /**
  82452. * Fired when the pad state has changed
  82453. */
  82454. _this.onPadStateChangedObservable = new BABYLON.Observable();
  82455. /**
  82456. * Fired when controllers stick values have changed
  82457. */
  82458. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  82459. /**
  82460. * X and Y axis corrisponding to the controllers joystick
  82461. */
  82462. _this.pad = { x: 0, y: 0 };
  82463. // avoid GC, store state in a tmp object
  82464. _this._changes = {
  82465. pressChanged: false,
  82466. touchChanged: false,
  82467. valueChanged: false,
  82468. changed: false
  82469. };
  82470. _this._buttons = new Array(vrGamepad.buttons.length);
  82471. _this.hand = vrGamepad.hand;
  82472. return _this;
  82473. }
  82474. /**
  82475. * Fired when a controller button's state has changed
  82476. * @param callback the callback containing the button that was modified
  82477. */
  82478. WebVRController.prototype.onButtonStateChange = function (callback) {
  82479. this._onButtonStateChange = callback;
  82480. };
  82481. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  82482. /**
  82483. * The default controller model for the controller
  82484. */
  82485. get: function () {
  82486. return this._defaultModel;
  82487. },
  82488. enumerable: true,
  82489. configurable: true
  82490. });
  82491. /**
  82492. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  82493. */
  82494. WebVRController.prototype.update = function () {
  82495. _super.prototype.update.call(this);
  82496. for (var index = 0; index < this._buttons.length; index++) {
  82497. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  82498. }
  82499. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  82500. this.pad.x = this.leftStick.x;
  82501. this.pad.y = this.leftStick.y;
  82502. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  82503. }
  82504. };
  82505. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  82506. if (!newState) {
  82507. newState = {
  82508. pressed: false,
  82509. touched: false,
  82510. value: 0
  82511. };
  82512. }
  82513. if (!currentState) {
  82514. this._buttons[buttonIndex] = {
  82515. pressed: newState.pressed,
  82516. touched: newState.touched,
  82517. value: newState.value
  82518. };
  82519. return;
  82520. }
  82521. this._checkChanges(newState, currentState);
  82522. if (this._changes.changed) {
  82523. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  82524. this._handleButtonChange(buttonIndex, newState, this._changes);
  82525. }
  82526. this._buttons[buttonIndex].pressed = newState.pressed;
  82527. this._buttons[buttonIndex].touched = newState.touched;
  82528. // oculus triggers are never 0, thou not touched.
  82529. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  82530. };
  82531. WebVRController.prototype._checkChanges = function (newState, currentState) {
  82532. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  82533. this._changes.touchChanged = newState.touched !== currentState.touched;
  82534. this._changes.valueChanged = newState.value !== currentState.value;
  82535. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  82536. return this._changes;
  82537. };
  82538. /**
  82539. * Disposes of th webVRCOntroller
  82540. */
  82541. WebVRController.prototype.dispose = function () {
  82542. _super.prototype.dispose.call(this);
  82543. this.onTriggerStateChangedObservable.clear();
  82544. this.onMainButtonStateChangedObservable.clear();
  82545. this.onSecondaryButtonStateChangedObservable.clear();
  82546. this.onPadStateChangedObservable.clear();
  82547. this.onPadValuesChangedObservable.clear();
  82548. };
  82549. return WebVRController;
  82550. }(BABYLON.PoseEnabledController));
  82551. BABYLON.WebVRController = WebVRController;
  82552. })(BABYLON || (BABYLON = {}));
  82553. //# sourceMappingURL=babylon.webVRController.js.map
  82554. var BABYLON;
  82555. (function (BABYLON) {
  82556. /**
  82557. * Oculus Touch Controller
  82558. */
  82559. var OculusTouchController = /** @class */ (function (_super) {
  82560. __extends(OculusTouchController, _super);
  82561. /**
  82562. * Creates a new OculusTouchController from a gamepad
  82563. * @param vrGamepad the gamepad that the controller should be created from
  82564. */
  82565. function OculusTouchController(vrGamepad) {
  82566. var _this = _super.call(this, vrGamepad) || this;
  82567. /**
  82568. * Fired when the secondary trigger on this controller is modified
  82569. */
  82570. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  82571. /**
  82572. * Fired when the thumb rest on this controller is modified
  82573. */
  82574. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  82575. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  82576. return _this;
  82577. }
  82578. /**
  82579. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82580. * @param scene scene in which to add meshes
  82581. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82582. */
  82583. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82584. var _this = this;
  82585. var meshName;
  82586. // Hand
  82587. if (this.hand === 'left') {
  82588. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  82589. }
  82590. else { // Right is the default if no hand is specified
  82591. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  82592. }
  82593. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  82594. /*
  82595. Parent Mesh name: oculus_touch_left
  82596. - body
  82597. - trigger
  82598. - thumbstick
  82599. - grip
  82600. - button_y
  82601. - button_x
  82602. - button_enter
  82603. */
  82604. _this._defaultModel = newMeshes[1];
  82605. _this.attachToMesh(_this._defaultModel);
  82606. if (meshLoaded) {
  82607. meshLoaded(_this._defaultModel);
  82608. }
  82609. });
  82610. };
  82611. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  82612. /**
  82613. * Fired when the A button on this controller is modified
  82614. */
  82615. get: function () {
  82616. if (this.hand === 'right') {
  82617. return this.onMainButtonStateChangedObservable;
  82618. }
  82619. else {
  82620. throw new Error('No A button on left hand');
  82621. }
  82622. },
  82623. enumerable: true,
  82624. configurable: true
  82625. });
  82626. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  82627. /**
  82628. * Fired when the B button on this controller is modified
  82629. */
  82630. get: function () {
  82631. if (this.hand === 'right') {
  82632. return this.onSecondaryButtonStateChangedObservable;
  82633. }
  82634. else {
  82635. throw new Error('No B button on left hand');
  82636. }
  82637. },
  82638. enumerable: true,
  82639. configurable: true
  82640. });
  82641. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  82642. /**
  82643. * Fired when the X button on this controller is modified
  82644. */
  82645. get: function () {
  82646. if (this.hand === 'left') {
  82647. return this.onMainButtonStateChangedObservable;
  82648. }
  82649. else {
  82650. throw new Error('No X button on right hand');
  82651. }
  82652. },
  82653. enumerable: true,
  82654. configurable: true
  82655. });
  82656. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  82657. /**
  82658. * Fired when the Y button on this controller is modified
  82659. */
  82660. get: function () {
  82661. if (this.hand === 'left') {
  82662. return this.onSecondaryButtonStateChangedObservable;
  82663. }
  82664. else {
  82665. throw new Error('No Y button on right hand');
  82666. }
  82667. },
  82668. enumerable: true,
  82669. configurable: true
  82670. });
  82671. /**
  82672. * Called once for each button that changed state since the last frame
  82673. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  82674. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  82675. * 2) secondary trigger (same)
  82676. * 3) A (right) X (left), touch, pressed = value
  82677. * 4) B / Y
  82678. * 5) thumb rest
  82679. * @param buttonIdx Which button index changed
  82680. * @param state New state of the button
  82681. * @param changes Which properties on the state changed since last frame
  82682. */
  82683. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82684. var notifyObject = state; //{ state: state, changes: changes };
  82685. var triggerDirection = this.hand === 'right' ? -1 : 1;
  82686. switch (buttonIdx) {
  82687. case 0:
  82688. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  82689. return;
  82690. case 1: // index trigger
  82691. if (this._defaultModel) {
  82692. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  82693. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  82694. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  82695. }
  82696. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  82697. return;
  82698. case 2: // secondary trigger
  82699. if (this._defaultModel) {
  82700. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  82701. }
  82702. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  82703. return;
  82704. case 3:
  82705. if (this._defaultModel) {
  82706. if (notifyObject.pressed) {
  82707. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  82708. }
  82709. else {
  82710. (this._defaultModel.getChildren()[1]).position.y = 0;
  82711. }
  82712. }
  82713. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  82714. return;
  82715. case 4:
  82716. if (this._defaultModel) {
  82717. if (notifyObject.pressed) {
  82718. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  82719. }
  82720. else {
  82721. (this._defaultModel.getChildren()[2]).position.y = 0;
  82722. }
  82723. }
  82724. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  82725. return;
  82726. case 5:
  82727. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  82728. return;
  82729. }
  82730. };
  82731. /**
  82732. * Base Url for the controller model.
  82733. */
  82734. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  82735. /**
  82736. * File name for the left controller model.
  82737. */
  82738. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  82739. /**
  82740. * File name for the right controller model.
  82741. */
  82742. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  82743. return OculusTouchController;
  82744. }(BABYLON.WebVRController));
  82745. BABYLON.OculusTouchController = OculusTouchController;
  82746. })(BABYLON || (BABYLON = {}));
  82747. //# sourceMappingURL=babylon.oculusTouchController.js.map
  82748. var BABYLON;
  82749. (function (BABYLON) {
  82750. /**
  82751. * Vive Controller
  82752. */
  82753. var ViveController = /** @class */ (function (_super) {
  82754. __extends(ViveController, _super);
  82755. /**
  82756. * Creates a new ViveController from a gamepad
  82757. * @param vrGamepad the gamepad that the controller should be created from
  82758. */
  82759. function ViveController(vrGamepad) {
  82760. var _this = _super.call(this, vrGamepad) || this;
  82761. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  82762. _this._invertLeftStickY = true;
  82763. return _this;
  82764. }
  82765. /**
  82766. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82767. * @param scene scene in which to add meshes
  82768. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82769. */
  82770. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82771. var _this = this;
  82772. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  82773. /*
  82774. Parent Mesh name: ViveWand
  82775. - body
  82776. - r_gripper
  82777. - l_gripper
  82778. - menu_button
  82779. - system_button
  82780. - trackpad
  82781. - trigger
  82782. - LED
  82783. */
  82784. _this._defaultModel = newMeshes[1];
  82785. _this.attachToMesh(_this._defaultModel);
  82786. if (meshLoaded) {
  82787. meshLoaded(_this._defaultModel);
  82788. }
  82789. });
  82790. };
  82791. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  82792. /**
  82793. * Fired when the left button on this controller is modified
  82794. */
  82795. get: function () {
  82796. return this.onMainButtonStateChangedObservable;
  82797. },
  82798. enumerable: true,
  82799. configurable: true
  82800. });
  82801. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  82802. /**
  82803. * Fired when the right button on this controller is modified
  82804. */
  82805. get: function () {
  82806. return this.onMainButtonStateChangedObservable;
  82807. },
  82808. enumerable: true,
  82809. configurable: true
  82810. });
  82811. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  82812. /**
  82813. * Fired when the menu button on this controller is modified
  82814. */
  82815. get: function () {
  82816. return this.onSecondaryButtonStateChangedObservable;
  82817. },
  82818. enumerable: true,
  82819. configurable: true
  82820. });
  82821. /**
  82822. * Called once for each button that changed state since the last frame
  82823. * Vive mapping:
  82824. * 0: touchpad
  82825. * 1: trigger
  82826. * 2: left AND right buttons
  82827. * 3: menu button
  82828. * @param buttonIdx Which button index changed
  82829. * @param state New state of the button
  82830. * @param changes Which properties on the state changed since last frame
  82831. */
  82832. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82833. var notifyObject = state; //{ state: state, changes: changes };
  82834. switch (buttonIdx) {
  82835. case 0:
  82836. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  82837. return;
  82838. case 1: // index trigger
  82839. if (this._defaultModel) {
  82840. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  82841. }
  82842. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  82843. return;
  82844. case 2: // left AND right button
  82845. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  82846. return;
  82847. case 3:
  82848. if (this._defaultModel) {
  82849. if (notifyObject.pressed) {
  82850. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  82851. }
  82852. else {
  82853. (this._defaultModel.getChildren()[2]).position.y = 0;
  82854. }
  82855. }
  82856. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  82857. return;
  82858. }
  82859. };
  82860. /**
  82861. * Base Url for the controller model.
  82862. */
  82863. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  82864. /**
  82865. * File name for the controller model.
  82866. */
  82867. ViveController.MODEL_FILENAME = 'wand.babylon';
  82868. return ViveController;
  82869. }(BABYLON.WebVRController));
  82870. BABYLON.ViveController = ViveController;
  82871. })(BABYLON || (BABYLON = {}));
  82872. //# sourceMappingURL=babylon.viveController.js.map
  82873. var BABYLON;
  82874. (function (BABYLON) {
  82875. /**
  82876. * Generic Controller
  82877. */
  82878. var GenericController = /** @class */ (function (_super) {
  82879. __extends(GenericController, _super);
  82880. /**
  82881. * Creates a new GenericController from a gamepad
  82882. * @param vrGamepad the gamepad that the controller should be created from
  82883. */
  82884. function GenericController(vrGamepad) {
  82885. return _super.call(this, vrGamepad) || this;
  82886. }
  82887. /**
  82888. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82889. * @param scene scene in which to add meshes
  82890. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82891. */
  82892. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82893. var _this = this;
  82894. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  82895. _this._defaultModel = newMeshes[1];
  82896. _this.attachToMesh(_this._defaultModel);
  82897. if (meshLoaded) {
  82898. meshLoaded(_this._defaultModel);
  82899. }
  82900. });
  82901. };
  82902. /**
  82903. * Called once for each button that changed state since the last frame
  82904. * @param buttonIdx Which button index changed
  82905. * @param state New state of the button
  82906. * @param changes Which properties on the state changed since last frame
  82907. */
  82908. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82909. console.log("Button id: " + buttonIdx + "state: ");
  82910. console.dir(state);
  82911. };
  82912. /**
  82913. * Base Url for the controller model.
  82914. */
  82915. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82916. /**
  82917. * File name for the controller model.
  82918. */
  82919. GenericController.MODEL_FILENAME = 'generic.babylon';
  82920. return GenericController;
  82921. }(BABYLON.WebVRController));
  82922. BABYLON.GenericController = GenericController;
  82923. })(BABYLON || (BABYLON = {}));
  82924. //# sourceMappingURL=babylon.genericController.js.map
  82925. var BABYLON;
  82926. (function (BABYLON) {
  82927. /**
  82928. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  82929. */
  82930. var LoadedMeshInfo = /** @class */ (function () {
  82931. function LoadedMeshInfo() {
  82932. /**
  82933. * Map of the button meshes contained in the controller
  82934. */
  82935. this.buttonMeshes = {};
  82936. /**
  82937. * Map of the axis meshes contained in the controller
  82938. */
  82939. this.axisMeshes = {};
  82940. }
  82941. return LoadedMeshInfo;
  82942. }());
  82943. /**
  82944. * Defines the WindowsMotionController object that the state of the windows motion controller
  82945. */
  82946. var WindowsMotionController = /** @class */ (function (_super) {
  82947. __extends(WindowsMotionController, _super);
  82948. /**
  82949. * Creates a new WindowsMotionController from a gamepad
  82950. * @param vrGamepad the gamepad that the controller should be created from
  82951. */
  82952. function WindowsMotionController(vrGamepad) {
  82953. var _this = _super.call(this, vrGamepad) || this;
  82954. _this._mapping = {
  82955. // Semantic button names
  82956. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  82957. // A mapping of the button name to glTF model node name
  82958. // that should be transformed by button value.
  82959. buttonMeshNames: {
  82960. 'trigger': 'SELECT',
  82961. 'menu': 'MENU',
  82962. 'grip': 'GRASP',
  82963. 'thumbstick': 'THUMBSTICK_PRESS',
  82964. 'trackpad': 'TOUCHPAD_PRESS'
  82965. },
  82966. // This mapping is used to translate from the Motion Controller to Babylon semantics
  82967. buttonObservableNames: {
  82968. 'trigger': 'onTriggerStateChangedObservable',
  82969. 'menu': 'onSecondaryButtonStateChangedObservable',
  82970. 'grip': 'onMainButtonStateChangedObservable',
  82971. 'thumbstick': 'onPadStateChangedObservable',
  82972. 'trackpad': 'onTrackpadChangedObservable'
  82973. },
  82974. // A mapping of the axis name to glTF model node name
  82975. // that should be transformed by axis value.
  82976. // This array mirrors the browserGamepad.axes array, such that
  82977. // the mesh corresponding to axis 0 is in this array index 0.
  82978. axisMeshNames: [
  82979. 'THUMBSTICK_X',
  82980. 'THUMBSTICK_Y',
  82981. 'TOUCHPAD_TOUCH_X',
  82982. 'TOUCHPAD_TOUCH_Y'
  82983. ],
  82984. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  82985. };
  82986. /**
  82987. * Fired when the trackpad on this controller is clicked
  82988. */
  82989. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  82990. /**
  82991. * Fired when the trackpad on this controller is modified
  82992. */
  82993. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  82994. /**
  82995. * The current x and y values of this controller's trackpad
  82996. */
  82997. _this.trackpad = { x: 0, y: 0 };
  82998. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  82999. _this._loadedMeshInfo = null;
  83000. return _this;
  83001. }
  83002. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  83003. /**
  83004. * Fired when the trigger on this controller is modified
  83005. */
  83006. get: function () {
  83007. return this.onTriggerStateChangedObservable;
  83008. },
  83009. enumerable: true,
  83010. configurable: true
  83011. });
  83012. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  83013. /**
  83014. * Fired when the menu button on this controller is modified
  83015. */
  83016. get: function () {
  83017. return this.onSecondaryButtonStateChangedObservable;
  83018. },
  83019. enumerable: true,
  83020. configurable: true
  83021. });
  83022. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  83023. /**
  83024. * Fired when the grip button on this controller is modified
  83025. */
  83026. get: function () {
  83027. return this.onMainButtonStateChangedObservable;
  83028. },
  83029. enumerable: true,
  83030. configurable: true
  83031. });
  83032. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  83033. /**
  83034. * Fired when the thumbstick button on this controller is modified
  83035. */
  83036. get: function () {
  83037. return this.onPadStateChangedObservable;
  83038. },
  83039. enumerable: true,
  83040. configurable: true
  83041. });
  83042. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  83043. /**
  83044. * Fired when the touchpad button on this controller is modified
  83045. */
  83046. get: function () {
  83047. return this.onTrackpadChangedObservable;
  83048. },
  83049. enumerable: true,
  83050. configurable: true
  83051. });
  83052. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  83053. /**
  83054. * Fired when the touchpad values on this controller are modified
  83055. */
  83056. get: function () {
  83057. return this.onTrackpadValuesChangedObservable;
  83058. },
  83059. enumerable: true,
  83060. configurable: true
  83061. });
  83062. WindowsMotionController.prototype._updateTrackpad = function () {
  83063. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  83064. this.trackpad.x = this.browserGamepad["axes"][2];
  83065. this.trackpad.y = this.browserGamepad["axes"][3];
  83066. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  83067. }
  83068. };
  83069. /**
  83070. * Called once per frame by the engine.
  83071. */
  83072. WindowsMotionController.prototype.update = function () {
  83073. _super.prototype.update.call(this);
  83074. if (this.browserGamepad.axes) {
  83075. this._updateTrackpad();
  83076. // Only need to animate axes if there is a loaded mesh
  83077. if (this._loadedMeshInfo) {
  83078. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  83079. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  83080. }
  83081. }
  83082. }
  83083. };
  83084. /**
  83085. * Called once for each button that changed state since the last frame
  83086. * @param buttonIdx Which button index changed
  83087. * @param state New state of the button
  83088. * @param changes Which properties on the state changed since last frame
  83089. */
  83090. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83091. var buttonName = this._mapping.buttons[buttonIdx];
  83092. if (!buttonName) {
  83093. return;
  83094. }
  83095. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  83096. this._updateTrackpad();
  83097. // Only emit events for buttons that we know how to map from index to name
  83098. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  83099. if (observable) {
  83100. observable.notifyObservers(state);
  83101. }
  83102. this._lerpButtonTransform(buttonName, state.value);
  83103. };
  83104. /**
  83105. * Moves the buttons on the controller mesh based on their current state
  83106. * @param buttonName the name of the button to move
  83107. * @param buttonValue the value of the button which determines the buttons new position
  83108. */
  83109. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  83110. // If there is no loaded mesh, there is nothing to transform.
  83111. if (!this._loadedMeshInfo) {
  83112. return;
  83113. }
  83114. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  83115. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  83116. return;
  83117. }
  83118. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  83119. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  83120. };
  83121. /**
  83122. * Moves the axis on the controller mesh based on its current state
  83123. * @param axis the index of the axis
  83124. * @param axisValue the value of the axis which determines the meshes new position
  83125. * @hidden
  83126. */
  83127. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  83128. if (!this._loadedMeshInfo) {
  83129. return;
  83130. }
  83131. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  83132. if (!meshInfo) {
  83133. return;
  83134. }
  83135. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  83136. return;
  83137. }
  83138. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  83139. var lerpValue = axisValue * 0.5 + 0.5;
  83140. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  83141. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  83142. };
  83143. /**
  83144. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83145. * @param scene scene in which to add meshes
  83146. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83147. */
  83148. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  83149. var _this = this;
  83150. if (forceDefault === void 0) { forceDefault = false; }
  83151. var path;
  83152. var filename;
  83153. // Checking if GLB loader is present
  83154. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  83155. // Determine the device specific folder based on the ID suffix
  83156. var device = 'default';
  83157. if (this.id && !forceDefault) {
  83158. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  83159. device = ((match && match[0]) || device);
  83160. }
  83161. // Hand
  83162. if (this.hand === 'left') {
  83163. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  83164. }
  83165. else { // Right is the default if no hand is specified
  83166. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  83167. }
  83168. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  83169. }
  83170. else {
  83171. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  83172. path = BABYLON.GenericController.MODEL_BASE_URL;
  83173. filename = BABYLON.GenericController.MODEL_FILENAME;
  83174. }
  83175. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  83176. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  83177. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  83178. if (!_this._loadedMeshInfo) {
  83179. return;
  83180. }
  83181. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  83182. _this.attachToMesh(_this._defaultModel);
  83183. if (meshLoaded) {
  83184. meshLoaded(_this._defaultModel);
  83185. }
  83186. }, null, function (scene, message) {
  83187. BABYLON.Tools.Log(message);
  83188. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  83189. if (!forceDefault) {
  83190. _this.initControllerMesh(scene, meshLoaded, true);
  83191. }
  83192. });
  83193. };
  83194. /**
  83195. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  83196. * can be transformed by button presses and axes values, based on this._mapping.
  83197. *
  83198. * @param scene scene in which the meshes exist
  83199. * @param meshes list of meshes that make up the controller model to process
  83200. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  83201. */
  83202. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  83203. var loadedMeshInfo = null;
  83204. // Create a new mesh to contain the glTF hierarchy
  83205. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  83206. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  83207. var childMesh = null;
  83208. for (var i = 0; i < meshes.length; i++) {
  83209. var mesh = meshes[i];
  83210. if (!mesh.parent) {
  83211. // Exclude controller meshes from picking results
  83212. mesh.isPickable = false;
  83213. // Handle root node, attach to the new parentMesh
  83214. childMesh = mesh;
  83215. break;
  83216. }
  83217. }
  83218. if (childMesh) {
  83219. childMesh.setParent(parentMesh);
  83220. // Create our mesh info. Note that this method will always return non-null.
  83221. loadedMeshInfo = this.createMeshInfo(parentMesh);
  83222. }
  83223. else {
  83224. BABYLON.Tools.Warn('Could not find root node in model file.');
  83225. }
  83226. return loadedMeshInfo;
  83227. };
  83228. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  83229. var loadedMeshInfo = new LoadedMeshInfo();
  83230. var i;
  83231. loadedMeshInfo.rootNode = rootNode;
  83232. // Reset the caches
  83233. loadedMeshInfo.buttonMeshes = {};
  83234. loadedMeshInfo.axisMeshes = {};
  83235. // Button Meshes
  83236. for (i = 0; i < this._mapping.buttons.length; i++) {
  83237. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  83238. if (!buttonMeshName) {
  83239. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  83240. continue;
  83241. }
  83242. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  83243. if (!buttonMesh) {
  83244. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  83245. continue;
  83246. }
  83247. var buttonMeshInfo = {
  83248. index: i,
  83249. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  83250. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  83251. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  83252. };
  83253. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  83254. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  83255. }
  83256. else {
  83257. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  83258. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  83259. '(VALUE: ' + !!buttonMeshInfo.value +
  83260. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  83261. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  83262. ')');
  83263. }
  83264. }
  83265. // Axis Meshes
  83266. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  83267. var axisMeshName = this._mapping.axisMeshNames[i];
  83268. if (!axisMeshName) {
  83269. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  83270. continue;
  83271. }
  83272. var axisMesh = getChildByName(rootNode, axisMeshName);
  83273. if (!axisMesh) {
  83274. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  83275. continue;
  83276. }
  83277. var axisMeshInfo = {
  83278. index: i,
  83279. value: getImmediateChildByName(axisMesh, 'VALUE'),
  83280. min: getImmediateChildByName(axisMesh, 'MIN'),
  83281. max: getImmediateChildByName(axisMesh, 'MAX')
  83282. };
  83283. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  83284. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  83285. }
  83286. else {
  83287. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  83288. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  83289. '(VALUE: ' + !!axisMeshInfo.value +
  83290. ', MIN: ' + !!axisMeshInfo.min +
  83291. ', MAX:' + !!axisMeshInfo.max +
  83292. ')');
  83293. }
  83294. }
  83295. // Pointing Ray
  83296. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  83297. if (!loadedMeshInfo.pointingPoseNode) {
  83298. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  83299. }
  83300. else {
  83301. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  83302. }
  83303. return loadedMeshInfo;
  83304. // Look through all children recursively. This will return null if no mesh exists with the given name.
  83305. function getChildByName(node, name) {
  83306. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  83307. }
  83308. // Look through only immediate children. This will return null if no mesh exists with the given name.
  83309. function getImmediateChildByName(node, name) {
  83310. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  83311. }
  83312. };
  83313. /**
  83314. * Gets the ray of the controller in the direction the controller is pointing
  83315. * @param length the length the resulting ray should be
  83316. * @returns a ray in the direction the controller is pointing
  83317. */
  83318. WindowsMotionController.prototype.getForwardRay = function (length) {
  83319. if (length === void 0) { length = 100; }
  83320. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  83321. return _super.prototype.getForwardRay.call(this, length);
  83322. }
  83323. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  83324. var origin = m.getTranslation();
  83325. var forward = new BABYLON.Vector3(0, 0, -1);
  83326. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  83327. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  83328. return new BABYLON.Ray(origin, direction, length);
  83329. };
  83330. /**
  83331. * Disposes of the controller
  83332. */
  83333. WindowsMotionController.prototype.dispose = function () {
  83334. _super.prototype.dispose.call(this);
  83335. this.onTrackpadChangedObservable.clear();
  83336. };
  83337. /**
  83338. * The base url used to load the left and right controller models
  83339. */
  83340. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  83341. /**
  83342. * The name of the left controller model file
  83343. */
  83344. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  83345. /**
  83346. * The name of the right controller model file
  83347. */
  83348. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  83349. /**
  83350. * The controller name prefix for this controller type
  83351. */
  83352. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  83353. /**
  83354. * The controller id pattern for this controller type
  83355. */
  83356. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  83357. return WindowsMotionController;
  83358. }(BABYLON.WebVRController));
  83359. BABYLON.WindowsMotionController = WindowsMotionController;
  83360. })(BABYLON || (BABYLON = {}));
  83361. //# sourceMappingURL=babylon.windowsMotionController.js.map
  83362. var BABYLON;
  83363. (function (BABYLON) {
  83364. /**
  83365. * Gear VR Controller
  83366. */
  83367. var GearVRController = /** @class */ (function (_super) {
  83368. __extends(GearVRController, _super);
  83369. /**
  83370. * Creates a new GearVRController from a gamepad
  83371. * @param vrGamepad the gamepad that the controller should be created from
  83372. */
  83373. function GearVRController(vrGamepad) {
  83374. var _this = _super.call(this, vrGamepad) || this;
  83375. _this._buttonIndexToObservableNameMap = [
  83376. 'onTrackpadChangedObservable',
  83377. 'onTriggerStateChangedObservable' // Trigger
  83378. ];
  83379. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  83380. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  83381. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  83382. _this._disableTrackPosition(_this._calculatedPosition);
  83383. return _this;
  83384. }
  83385. /**
  83386. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83387. * @param scene scene in which to add meshes
  83388. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83389. */
  83390. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83391. var _this = this;
  83392. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  83393. // Offset the controller so it will rotate around the users wrist
  83394. var mesh = new BABYLON.Mesh("", scene);
  83395. newMeshes[1].parent = mesh;
  83396. newMeshes[1].position.z = -0.15;
  83397. _this._defaultModel = mesh;
  83398. _this.attachToMesh(_this._defaultModel);
  83399. if (meshLoaded) {
  83400. meshLoaded(_this._defaultModel);
  83401. }
  83402. });
  83403. };
  83404. /**
  83405. * Called once for each button that changed state since the last frame
  83406. * @param buttonIdx Which button index changed
  83407. * @param state New state of the button
  83408. * @param changes Which properties on the state changed since last frame
  83409. */
  83410. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83411. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  83412. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  83413. // Only emit events for buttons that we know how to map from index to observable
  83414. var observable = this[observableName];
  83415. if (observable) {
  83416. observable.notifyObservers(state);
  83417. }
  83418. }
  83419. };
  83420. /**
  83421. * Base Url for the controller model.
  83422. */
  83423. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  83424. /**
  83425. * File name for the controller model.
  83426. */
  83427. GearVRController.MODEL_FILENAME = 'generic.babylon';
  83428. /**
  83429. * Gamepad Id prefix used to identify this controller.
  83430. */
  83431. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  83432. return GearVRController;
  83433. }(BABYLON.WebVRController));
  83434. BABYLON.GearVRController = GearVRController;
  83435. })(BABYLON || (BABYLON = {}));
  83436. //# sourceMappingURL=babylon.gearVRController.js.map
  83437. var BABYLON;
  83438. (function (BABYLON) {
  83439. /**
  83440. * Google Daydream controller
  83441. */
  83442. var DaydreamController = /** @class */ (function (_super) {
  83443. __extends(DaydreamController, _super);
  83444. /**
  83445. * Creates a new DaydreamController from a gamepad
  83446. * @param vrGamepad the gamepad that the controller should be created from
  83447. */
  83448. function DaydreamController(vrGamepad) {
  83449. var _this = _super.call(this, vrGamepad) || this;
  83450. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  83451. return _this;
  83452. }
  83453. /**
  83454. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83455. * @param scene scene in which to add meshes
  83456. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83457. */
  83458. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83459. var _this = this;
  83460. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  83461. _this._defaultModel = newMeshes[1];
  83462. _this.attachToMesh(_this._defaultModel);
  83463. if (meshLoaded) {
  83464. meshLoaded(_this._defaultModel);
  83465. }
  83466. });
  83467. };
  83468. /**
  83469. * Called once for each button that changed state since the last frame
  83470. * @param buttonIdx Which button index changed
  83471. * @param state New state of the button
  83472. * @param changes Which properties on the state changed since last frame
  83473. */
  83474. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83475. // Daydream controller only has 1 GamepadButton (on the trackpad).
  83476. if (buttonIdx === 0) {
  83477. var observable = this.onTriggerStateChangedObservable;
  83478. if (observable) {
  83479. observable.notifyObservers(state);
  83480. }
  83481. }
  83482. else {
  83483. // If the app or home buttons are ever made available
  83484. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  83485. }
  83486. };
  83487. /**
  83488. * Base Url for the controller model.
  83489. */
  83490. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  83491. /**
  83492. * File name for the controller model.
  83493. */
  83494. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  83495. /**
  83496. * Gamepad Id prefix used to identify Daydream Controller.
  83497. */
  83498. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  83499. return DaydreamController;
  83500. }(BABYLON.WebVRController));
  83501. BABYLON.DaydreamController = DaydreamController;
  83502. })(BABYLON || (BABYLON = {}));
  83503. //# sourceMappingURL=babylon.daydreamController.js.map
  83504. var BABYLON;
  83505. (function (BABYLON) {
  83506. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  83507. get: function () {
  83508. if (!this._gamepadManager) {
  83509. this._gamepadManager = new BABYLON.GamepadManager(this);
  83510. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  83511. if (!component) {
  83512. component = new GamepadSystemSceneComponent(this);
  83513. this._addComponent(component);
  83514. }
  83515. }
  83516. return this._gamepadManager;
  83517. },
  83518. enumerable: true,
  83519. configurable: true
  83520. });
  83521. /**
  83522. * Adds a gamepad to the free camera inputs manager
  83523. */
  83524. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  83525. this.add(new BABYLON.FreeCameraGamepadInput());
  83526. return this;
  83527. };
  83528. /**
  83529. * Adds a gamepad to the arc rotate camera inputs manager
  83530. */
  83531. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  83532. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  83533. return this;
  83534. };
  83535. /**
  83536. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  83537. */
  83538. var GamepadSystemSceneComponent = /** @class */ (function () {
  83539. /**
  83540. * Creates a new instance of the component for the given scene
  83541. * @param scene Defines the scene to register the component in
  83542. */
  83543. function GamepadSystemSceneComponent(scene) {
  83544. /**
  83545. * The component name helpfull to identify the component in the list of scene components.
  83546. */
  83547. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  83548. this.scene = scene;
  83549. }
  83550. /**
  83551. * Registers the component in a given scene
  83552. */
  83553. GamepadSystemSceneComponent.prototype.register = function () {
  83554. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  83555. };
  83556. /**
  83557. * Rebuilds the elements related to this component in case of
  83558. * context lost for instance.
  83559. */
  83560. GamepadSystemSceneComponent.prototype.rebuild = function () {
  83561. // Nothing to do for gamepads
  83562. };
  83563. /**
  83564. * Disposes the component and the associated ressources
  83565. */
  83566. GamepadSystemSceneComponent.prototype.dispose = function () {
  83567. var gamepadManager = this.scene._gamepadManager;
  83568. if (gamepadManager) {
  83569. gamepadManager.dispose();
  83570. this.scene._gamepadManager = null;
  83571. }
  83572. };
  83573. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  83574. var gamepadManager = this.scene._gamepadManager;
  83575. if (gamepadManager && gamepadManager._isMonitoring) {
  83576. gamepadManager._checkGamepadsStatus();
  83577. }
  83578. };
  83579. return GamepadSystemSceneComponent;
  83580. }());
  83581. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  83582. })(BABYLON || (BABYLON = {}));
  83583. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  83584. var BABYLON;
  83585. (function (BABYLON) {
  83586. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  83587. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  83588. });
  83589. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  83590. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  83591. });
  83592. /**
  83593. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  83594. * an arc rotate version arcFollowCamera are available.
  83595. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83596. */
  83597. var FollowCamera = /** @class */ (function (_super) {
  83598. __extends(FollowCamera, _super);
  83599. /**
  83600. * Instantiates the follow camera.
  83601. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83602. * @param name Define the name of the camera in the scene
  83603. * @param position Define the position of the camera
  83604. * @param scene Define the scene the camera belong to
  83605. * @param lockedTarget Define the target of the camera
  83606. */
  83607. function FollowCamera(name, position, scene, lockedTarget) {
  83608. if (lockedTarget === void 0) { lockedTarget = null; }
  83609. var _this = _super.call(this, name, position, scene) || this;
  83610. /**
  83611. * Distance the follow camera should follow an object at
  83612. */
  83613. _this.radius = 12;
  83614. /**
  83615. * Define a rotation offset between the camera and the object it follows
  83616. */
  83617. _this.rotationOffset = 0;
  83618. /**
  83619. * Define a height offset between the camera and the object it follows.
  83620. * It can help following an object from the top (like a car chaing a plane)
  83621. */
  83622. _this.heightOffset = 4;
  83623. /**
  83624. * Define how fast the camera can accelerate to follow it s target.
  83625. */
  83626. _this.cameraAcceleration = 0.05;
  83627. /**
  83628. * Define the speed limit of the camera following an object.
  83629. */
  83630. _this.maxCameraSpeed = 20;
  83631. _this.lockedTarget = lockedTarget;
  83632. return _this;
  83633. }
  83634. FollowCamera.prototype._follow = function (cameraTarget) {
  83635. if (!cameraTarget) {
  83636. return;
  83637. }
  83638. var yRotation;
  83639. if (cameraTarget.rotationQuaternion) {
  83640. var rotMatrix = new BABYLON.Matrix();
  83641. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  83642. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  83643. }
  83644. else {
  83645. yRotation = cameraTarget.rotation.y;
  83646. }
  83647. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  83648. var targetPosition = cameraTarget.getAbsolutePosition();
  83649. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  83650. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  83651. var dx = targetX - this.position.x;
  83652. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  83653. var dz = (targetZ) - this.position.z;
  83654. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  83655. var vy = dy * this.cameraAcceleration;
  83656. var vz = dz * this.cameraAcceleration * 2;
  83657. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  83658. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83659. }
  83660. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  83661. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83662. }
  83663. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  83664. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83665. }
  83666. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  83667. this.setTarget(targetPosition);
  83668. };
  83669. /** @hidden */
  83670. FollowCamera.prototype._checkInputs = function () {
  83671. _super.prototype._checkInputs.call(this);
  83672. if (this.lockedTarget) {
  83673. this._follow(this.lockedTarget);
  83674. }
  83675. };
  83676. /**
  83677. * Gets the camera class name.
  83678. * @returns the class name
  83679. */
  83680. FollowCamera.prototype.getClassName = function () {
  83681. return "FollowCamera";
  83682. };
  83683. __decorate([
  83684. BABYLON.serialize()
  83685. ], FollowCamera.prototype, "radius", void 0);
  83686. __decorate([
  83687. BABYLON.serialize()
  83688. ], FollowCamera.prototype, "rotationOffset", void 0);
  83689. __decorate([
  83690. BABYLON.serialize()
  83691. ], FollowCamera.prototype, "heightOffset", void 0);
  83692. __decorate([
  83693. BABYLON.serialize()
  83694. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  83695. __decorate([
  83696. BABYLON.serialize()
  83697. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  83698. __decorate([
  83699. BABYLON.serializeAsMeshReference("lockedTargetId")
  83700. ], FollowCamera.prototype, "lockedTarget", void 0);
  83701. return FollowCamera;
  83702. }(BABYLON.TargetCamera));
  83703. BABYLON.FollowCamera = FollowCamera;
  83704. /**
  83705. * Arc Rotate version of the follow camera.
  83706. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  83707. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83708. */
  83709. var ArcFollowCamera = /** @class */ (function (_super) {
  83710. __extends(ArcFollowCamera, _super);
  83711. /**
  83712. * Instantiates a new ArcFollowCamera
  83713. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83714. * @param name Define the name of the camera
  83715. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  83716. * @param beta Define the rotation angle of the camera around the elevation axis
  83717. * @param radius Define the radius of the camera from its target point
  83718. * @param target Define the target of the camera
  83719. * @param scene Define the scene the camera belongs to
  83720. */
  83721. function ArcFollowCamera(name,
  83722. /** The longitudinal angle of the camera */
  83723. alpha,
  83724. /** The latitudinal angle of the camera */
  83725. beta,
  83726. /** The radius of the camera from its target */
  83727. radius,
  83728. /** Define the camera target (the messh it should follow) */
  83729. target, scene) {
  83730. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  83731. _this.alpha = alpha;
  83732. _this.beta = beta;
  83733. _this.radius = radius;
  83734. _this.target = target;
  83735. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  83736. _this._follow();
  83737. return _this;
  83738. }
  83739. ArcFollowCamera.prototype._follow = function () {
  83740. if (!this.target) {
  83741. return;
  83742. }
  83743. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  83744. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  83745. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  83746. var targetPosition = this.target.getAbsolutePosition();
  83747. this.position = targetPosition.add(this._cartesianCoordinates);
  83748. this.setTarget(targetPosition);
  83749. };
  83750. /** @hidden */
  83751. ArcFollowCamera.prototype._checkInputs = function () {
  83752. _super.prototype._checkInputs.call(this);
  83753. this._follow();
  83754. };
  83755. /**
  83756. * Returns the class name of the object.
  83757. * It is mostly used internally for serialization purposes.
  83758. */
  83759. ArcFollowCamera.prototype.getClassName = function () {
  83760. return "ArcFollowCamera";
  83761. };
  83762. return ArcFollowCamera;
  83763. }(BABYLON.TargetCamera));
  83764. BABYLON.ArcFollowCamera = ArcFollowCamera;
  83765. })(BABYLON || (BABYLON = {}));
  83766. //# sourceMappingURL=babylon.followCamera.js.map
  83767. var BABYLON;
  83768. (function (BABYLON) {
  83769. /**
  83770. * 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,
  83771. * which still works and will still be found in many Playgrounds.
  83772. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83773. */
  83774. var UniversalCamera = /** @class */ (function (_super) {
  83775. __extends(UniversalCamera, _super);
  83776. /**
  83777. * 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,
  83778. * which still works and will still be found in many Playgrounds.
  83779. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83780. * @param name Define the name of the camera in the scene
  83781. * @param position Define the start position of the camera in the scene
  83782. * @param scene Define the scene the camera belongs to
  83783. */
  83784. function UniversalCamera(name, position, scene) {
  83785. var _this = _super.call(this, name, position, scene) || this;
  83786. _this.inputs.addGamepad();
  83787. return _this;
  83788. }
  83789. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  83790. /**
  83791. * Defines the gamepad rotation sensiblity.
  83792. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  83793. */
  83794. get: function () {
  83795. var gamepad = this.inputs.attached["gamepad"];
  83796. if (gamepad) {
  83797. return gamepad.gamepadAngularSensibility;
  83798. }
  83799. return 0;
  83800. },
  83801. set: function (value) {
  83802. var gamepad = this.inputs.attached["gamepad"];
  83803. if (gamepad) {
  83804. gamepad.gamepadAngularSensibility = value;
  83805. }
  83806. },
  83807. enumerable: true,
  83808. configurable: true
  83809. });
  83810. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  83811. /**
  83812. * Defines the gamepad move sensiblity.
  83813. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  83814. */
  83815. get: function () {
  83816. var gamepad = this.inputs.attached["gamepad"];
  83817. if (gamepad) {
  83818. return gamepad.gamepadMoveSensibility;
  83819. }
  83820. return 0;
  83821. },
  83822. set: function (value) {
  83823. var gamepad = this.inputs.attached["gamepad"];
  83824. if (gamepad) {
  83825. gamepad.gamepadMoveSensibility = value;
  83826. }
  83827. },
  83828. enumerable: true,
  83829. configurable: true
  83830. });
  83831. /**
  83832. * Gets the current object class name.
  83833. * @return the class name
  83834. */
  83835. UniversalCamera.prototype.getClassName = function () {
  83836. return "UniversalCamera";
  83837. };
  83838. return UniversalCamera;
  83839. }(BABYLON.TouchCamera));
  83840. BABYLON.UniversalCamera = UniversalCamera;
  83841. })(BABYLON || (BABYLON = {}));
  83842. //# sourceMappingURL=babylon.universalCamera.js.map
  83843. var BABYLON;
  83844. (function (BABYLON) {
  83845. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  83846. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  83847. });
  83848. /**
  83849. * This represents a FPS type of camera. This is only here for back compat purpose.
  83850. * Please use the UniversalCamera instead as both are identical.
  83851. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83852. */
  83853. var GamepadCamera = /** @class */ (function (_super) {
  83854. __extends(GamepadCamera, _super);
  83855. /**
  83856. * Instantiates a new Gamepad Camera
  83857. * This represents a FPS type of camera. This is only here for back compat purpose.
  83858. * Please use the UniversalCamera instead as both are identical.
  83859. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83860. * @param name Define the name of the camera in the scene
  83861. * @param position Define the start position of the camera in the scene
  83862. * @param scene Define the scene the camera belongs to
  83863. */
  83864. function GamepadCamera(name, position, scene) {
  83865. return _super.call(this, name, position, scene) || this;
  83866. }
  83867. /**
  83868. * Gets the current object class name.
  83869. * @return the class name
  83870. */
  83871. GamepadCamera.prototype.getClassName = function () {
  83872. return "GamepadCamera";
  83873. };
  83874. return GamepadCamera;
  83875. }(BABYLON.UniversalCamera));
  83876. BABYLON.GamepadCamera = GamepadCamera;
  83877. })(BABYLON || (BABYLON = {}));
  83878. //# sourceMappingURL=babylon.gamepadCamera.js.map
  83879. var BABYLON;
  83880. (function (BABYLON) {
  83881. /**
  83882. * PostProcessRenderPipelineManager class
  83883. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83884. */
  83885. var PostProcessRenderPipelineManager = /** @class */ (function () {
  83886. /**
  83887. * Initializes a PostProcessRenderPipelineManager
  83888. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83889. */
  83890. function PostProcessRenderPipelineManager() {
  83891. this._renderPipelines = {};
  83892. }
  83893. /**
  83894. * Adds a pipeline to the manager
  83895. * @param renderPipeline The pipeline to add
  83896. */
  83897. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  83898. this._renderPipelines[renderPipeline._name] = renderPipeline;
  83899. };
  83900. /**
  83901. * Attaches a camera to the pipeline
  83902. * @param renderPipelineName The name of the pipeline to attach to
  83903. * @param cameras the camera to attach
  83904. * @param unique if the camera can be attached multiple times to the pipeline
  83905. */
  83906. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  83907. if (unique === void 0) { unique = false; }
  83908. var renderPipeline = this._renderPipelines[renderPipelineName];
  83909. if (!renderPipeline) {
  83910. return;
  83911. }
  83912. renderPipeline._attachCameras(cameras, unique);
  83913. };
  83914. /**
  83915. * Detaches a camera from the pipeline
  83916. * @param renderPipelineName The name of the pipeline to detach from
  83917. * @param cameras the camera to detach
  83918. */
  83919. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  83920. var renderPipeline = this._renderPipelines[renderPipelineName];
  83921. if (!renderPipeline) {
  83922. return;
  83923. }
  83924. renderPipeline._detachCameras(cameras);
  83925. };
  83926. /**
  83927. * Enables an effect by name on a pipeline
  83928. * @param renderPipelineName the name of the pipeline to enable the effect in
  83929. * @param renderEffectName the name of the effect to enable
  83930. * @param cameras the cameras that the effect should be enabled on
  83931. */
  83932. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  83933. var renderPipeline = this._renderPipelines[renderPipelineName];
  83934. if (!renderPipeline) {
  83935. return;
  83936. }
  83937. renderPipeline._enableEffect(renderEffectName, cameras);
  83938. };
  83939. /**
  83940. * Disables an effect by name on a pipeline
  83941. * @param renderPipelineName the name of the pipeline to disable the effect in
  83942. * @param renderEffectName the name of the effect to disable
  83943. * @param cameras the cameras that the effect should be disabled on
  83944. */
  83945. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  83946. var renderPipeline = this._renderPipelines[renderPipelineName];
  83947. if (!renderPipeline) {
  83948. return;
  83949. }
  83950. renderPipeline._disableEffect(renderEffectName, cameras);
  83951. };
  83952. /**
  83953. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  83954. */
  83955. PostProcessRenderPipelineManager.prototype.update = function () {
  83956. for (var renderPipelineName in this._renderPipelines) {
  83957. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  83958. var pipeline = this._renderPipelines[renderPipelineName];
  83959. if (!pipeline.isSupported) {
  83960. pipeline.dispose();
  83961. delete this._renderPipelines[renderPipelineName];
  83962. }
  83963. else {
  83964. pipeline._update();
  83965. }
  83966. }
  83967. }
  83968. };
  83969. /** @hidden */
  83970. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  83971. for (var renderPipelineName in this._renderPipelines) {
  83972. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  83973. var pipeline = this._renderPipelines[renderPipelineName];
  83974. pipeline._rebuild();
  83975. }
  83976. }
  83977. };
  83978. /**
  83979. * Disposes of the manager and pipelines
  83980. */
  83981. PostProcessRenderPipelineManager.prototype.dispose = function () {
  83982. for (var renderPipelineName in this._renderPipelines) {
  83983. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  83984. var pipeline = this._renderPipelines[renderPipelineName];
  83985. pipeline.dispose();
  83986. }
  83987. }
  83988. };
  83989. return PostProcessRenderPipelineManager;
  83990. }());
  83991. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  83992. })(BABYLON || (BABYLON = {}));
  83993. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  83994. var BABYLON;
  83995. (function (BABYLON) {
  83996. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  83997. get: function () {
  83998. if (!this._postProcessRenderPipelineManager) {
  83999. // Register the G Buffer component to the scene.
  84000. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  84001. if (!component) {
  84002. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  84003. this._addComponent(component);
  84004. }
  84005. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  84006. }
  84007. return this._postProcessRenderPipelineManager;
  84008. },
  84009. enumerable: true,
  84010. configurable: true
  84011. });
  84012. /**
  84013. * Defines the Render Pipeline scene component responsible to rendering pipelines
  84014. */
  84015. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  84016. /**
  84017. * Creates a new instance of the component for the given scene
  84018. * @param scene Defines the scene to register the component in
  84019. */
  84020. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  84021. /**
  84022. * The component name helpfull to identify the component in the list of scene components.
  84023. */
  84024. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  84025. this.scene = scene;
  84026. }
  84027. /**
  84028. * Registers the component in a given scene
  84029. */
  84030. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  84031. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  84032. };
  84033. /**
  84034. * Rebuilds the elements related to this component in case of
  84035. * context lost for instance.
  84036. */
  84037. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  84038. if (this.scene._postProcessRenderPipelineManager) {
  84039. this.scene._postProcessRenderPipelineManager._rebuild();
  84040. }
  84041. };
  84042. /**
  84043. * Disposes the component and the associated ressources
  84044. */
  84045. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  84046. if (this.scene._postProcessRenderPipelineManager) {
  84047. this.scene._postProcessRenderPipelineManager.dispose();
  84048. }
  84049. };
  84050. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  84051. if (this.scene._postProcessRenderPipelineManager) {
  84052. this.scene._postProcessRenderPipelineManager.update();
  84053. }
  84054. };
  84055. return PostProcessRenderPipelineManagerSceneComponent;
  84056. }());
  84057. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  84058. })(BABYLON || (BABYLON = {}));
  84059. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  84060. var BABYLON;
  84061. (function (BABYLON) {
  84062. /**
  84063. * This represents a set of one or more post processes in Babylon.
  84064. * A post process can be used to apply a shader to a texture after it is rendered.
  84065. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84066. */
  84067. var PostProcessRenderEffect = /** @class */ (function () {
  84068. /**
  84069. * Instantiates a post process render effect.
  84070. * A post process can be used to apply a shader to a texture after it is rendered.
  84071. * @param engine The engine the effect is tied to
  84072. * @param name The name of the effect
  84073. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  84074. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  84075. */
  84076. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  84077. this._name = name;
  84078. this._singleInstance = singleInstance || true;
  84079. this._getPostProcesses = getPostProcesses;
  84080. this._cameras = {};
  84081. this._indicesForCamera = {};
  84082. this._postProcesses = {};
  84083. }
  84084. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  84085. /**
  84086. * Checks if all the post processes in the effect are supported.
  84087. */
  84088. get: function () {
  84089. for (var index in this._postProcesses) {
  84090. if (this._postProcesses.hasOwnProperty(index)) {
  84091. var pps = this._postProcesses[index];
  84092. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  84093. if (!pps[ppIndex].isSupported) {
  84094. return false;
  84095. }
  84096. }
  84097. }
  84098. }
  84099. return true;
  84100. },
  84101. enumerable: true,
  84102. configurable: true
  84103. });
  84104. /**
  84105. * Updates the current state of the effect
  84106. * @hidden
  84107. */
  84108. PostProcessRenderEffect.prototype._update = function () {
  84109. };
  84110. /**
  84111. * Attaches the effect on cameras
  84112. * @param cameras The camera to attach to.
  84113. * @hidden
  84114. */
  84115. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  84116. var _this = this;
  84117. var cameraKey;
  84118. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84119. if (!cams) {
  84120. return;
  84121. }
  84122. for (var i = 0; i < cams.length; i++) {
  84123. var camera = cams[i];
  84124. var cameraName = camera.name;
  84125. if (this._singleInstance) {
  84126. cameraKey = 0;
  84127. }
  84128. else {
  84129. cameraKey = cameraName;
  84130. }
  84131. if (!this._postProcesses[cameraKey]) {
  84132. var postProcess = this._getPostProcesses();
  84133. if (postProcess) {
  84134. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  84135. }
  84136. }
  84137. if (!this._indicesForCamera[cameraName]) {
  84138. this._indicesForCamera[cameraName] = [];
  84139. }
  84140. this._postProcesses[cameraKey].forEach(function (postProcess) {
  84141. var index = camera.attachPostProcess(postProcess);
  84142. _this._indicesForCamera[cameraName].push(index);
  84143. });
  84144. if (!this._cameras[cameraName]) {
  84145. this._cameras[cameraName] = camera;
  84146. }
  84147. }
  84148. };
  84149. /**
  84150. * Detatches the effect on cameras
  84151. * @param cameras The camera to detatch from.
  84152. * @hidden
  84153. */
  84154. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  84155. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84156. if (!cams) {
  84157. return;
  84158. }
  84159. for (var i = 0; i < cams.length; i++) {
  84160. var camera = cams[i];
  84161. var cameraName = camera.name;
  84162. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84163. camera.detachPostProcess(postProcess);
  84164. });
  84165. if (this._cameras[cameraName]) {
  84166. //this._indicesForCamera.splice(index, 1);
  84167. this._cameras[cameraName] = null;
  84168. }
  84169. }
  84170. };
  84171. /**
  84172. * Enables the effect on given cameras
  84173. * @param cameras The camera to enable.
  84174. * @hidden
  84175. */
  84176. PostProcessRenderEffect.prototype._enable = function (cameras) {
  84177. var _this = this;
  84178. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84179. if (!cams) {
  84180. return;
  84181. }
  84182. for (var i = 0; i < cams.length; i++) {
  84183. var camera = cams[i];
  84184. var cameraName = camera.name;
  84185. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  84186. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  84187. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84188. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  84189. });
  84190. }
  84191. }
  84192. }
  84193. };
  84194. /**
  84195. * Disables the effect on the given cameras
  84196. * @param cameras The camera to disable.
  84197. * @hidden
  84198. */
  84199. PostProcessRenderEffect.prototype._disable = function (cameras) {
  84200. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84201. if (!cams) {
  84202. return;
  84203. }
  84204. for (var i = 0; i < cams.length; i++) {
  84205. var camera = cams[i];
  84206. var cameraName = camera.name;
  84207. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84208. camera.detachPostProcess(postProcess);
  84209. });
  84210. }
  84211. };
  84212. /**
  84213. * Gets a list of the post processes contained in the effect.
  84214. * @param camera The camera to get the post processes on.
  84215. * @returns The list of the post processes in the effect.
  84216. */
  84217. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  84218. if (this._singleInstance) {
  84219. return this._postProcesses[0];
  84220. }
  84221. else {
  84222. if (!camera) {
  84223. return null;
  84224. }
  84225. return this._postProcesses[camera.name];
  84226. }
  84227. };
  84228. return PostProcessRenderEffect;
  84229. }());
  84230. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  84231. })(BABYLON || (BABYLON = {}));
  84232. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  84233. var BABYLON;
  84234. (function (BABYLON) {
  84235. /**
  84236. * PostProcessRenderPipeline
  84237. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84238. */
  84239. var PostProcessRenderPipeline = /** @class */ (function () {
  84240. /**
  84241. * Initializes a PostProcessRenderPipeline
  84242. * @param engine engine to add the pipeline to
  84243. * @param name name of the pipeline
  84244. */
  84245. function PostProcessRenderPipeline(engine, name) {
  84246. this.engine = engine;
  84247. this._name = name;
  84248. this._renderEffects = {};
  84249. this._renderEffectsForIsolatedPass = new Array();
  84250. this._cameras = [];
  84251. }
  84252. /**
  84253. * "PostProcessRenderPipeline"
  84254. * @returns "PostProcessRenderPipeline"
  84255. */
  84256. PostProcessRenderPipeline.prototype.getClassName = function () {
  84257. return "PostProcessRenderPipeline";
  84258. };
  84259. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  84260. /**
  84261. * If all the render effects in the pipeline are support
  84262. */
  84263. get: function () {
  84264. for (var renderEffectName in this._renderEffects) {
  84265. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84266. if (!this._renderEffects[renderEffectName].isSupported) {
  84267. return false;
  84268. }
  84269. }
  84270. }
  84271. return true;
  84272. },
  84273. enumerable: true,
  84274. configurable: true
  84275. });
  84276. /**
  84277. * Adds an effect to the pipeline
  84278. * @param renderEffect the effect to add
  84279. */
  84280. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  84281. this._renderEffects[renderEffect._name] = renderEffect;
  84282. };
  84283. // private
  84284. /** @hidden */
  84285. PostProcessRenderPipeline.prototype._rebuild = function () {
  84286. };
  84287. /** @hidden */
  84288. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  84289. var renderEffects = this._renderEffects[renderEffectName];
  84290. if (!renderEffects) {
  84291. return;
  84292. }
  84293. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  84294. };
  84295. /** @hidden */
  84296. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  84297. var renderEffects = this._renderEffects[renderEffectName];
  84298. if (!renderEffects) {
  84299. return;
  84300. }
  84301. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  84302. };
  84303. /** @hidden */
  84304. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  84305. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84306. if (!cams) {
  84307. return;
  84308. }
  84309. var indicesToDelete = [];
  84310. var i;
  84311. for (i = 0; i < cams.length; i++) {
  84312. var camera = cams[i];
  84313. var cameraName = camera.name;
  84314. if (this._cameras.indexOf(camera) === -1) {
  84315. this._cameras[cameraName] = camera;
  84316. }
  84317. else if (unique) {
  84318. indicesToDelete.push(i);
  84319. }
  84320. }
  84321. for (i = 0; i < indicesToDelete.length; i++) {
  84322. cameras.splice(indicesToDelete[i], 1);
  84323. }
  84324. for (var renderEffectName in this._renderEffects) {
  84325. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84326. this._renderEffects[renderEffectName]._attachCameras(cams);
  84327. }
  84328. }
  84329. };
  84330. /** @hidden */
  84331. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  84332. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84333. if (!cams) {
  84334. return;
  84335. }
  84336. for (var renderEffectName in this._renderEffects) {
  84337. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84338. this._renderEffects[renderEffectName]._detachCameras(cams);
  84339. }
  84340. }
  84341. for (var i = 0; i < cams.length; i++) {
  84342. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  84343. }
  84344. };
  84345. /** @hidden */
  84346. PostProcessRenderPipeline.prototype._update = function () {
  84347. for (var renderEffectName in this._renderEffects) {
  84348. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84349. this._renderEffects[renderEffectName]._update();
  84350. }
  84351. }
  84352. for (var i = 0; i < this._cameras.length; i++) {
  84353. var cameraName = this._cameras[i].name;
  84354. if (this._renderEffectsForIsolatedPass[cameraName]) {
  84355. this._renderEffectsForIsolatedPass[cameraName]._update();
  84356. }
  84357. }
  84358. };
  84359. /** @hidden */
  84360. PostProcessRenderPipeline.prototype._reset = function () {
  84361. this._renderEffects = {};
  84362. this._renderEffectsForIsolatedPass = new Array();
  84363. };
  84364. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  84365. // 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)
  84366. var effectKeys = Object.keys(this._renderEffects);
  84367. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  84368. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  84369. if (postProcesses) {
  84370. postProcesses[0].samples = sampleCount;
  84371. return true;
  84372. }
  84373. }
  84374. return false;
  84375. };
  84376. /**
  84377. * Disposes of the pipeline
  84378. */
  84379. PostProcessRenderPipeline.prototype.dispose = function () {
  84380. // Must be implemented by children
  84381. };
  84382. __decorate([
  84383. BABYLON.serialize()
  84384. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  84385. return PostProcessRenderPipeline;
  84386. }());
  84387. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  84388. })(BABYLON || (BABYLON = {}));
  84389. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  84390. var BABYLON;
  84391. (function (BABYLON) {
  84392. /**
  84393. * This represents a depth renderer in Babylon.
  84394. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  84395. */
  84396. var DepthRenderer = /** @class */ (function () {
  84397. /**
  84398. * Instantiates a depth renderer
  84399. * @param scene The scene the renderer belongs to
  84400. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  84401. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  84402. */
  84403. function DepthRenderer(scene, type, camera) {
  84404. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  84405. if (camera === void 0) { camera = null; }
  84406. var _this = this;
  84407. /**
  84408. * Specifiess that the depth renderer will only be used within
  84409. * the camera it is created for.
  84410. * This can help forcing its rendering during the camera processing.
  84411. */
  84412. this.useOnlyInActiveCamera = false;
  84413. this._scene = scene;
  84414. // Register the G Buffer component to the scene.
  84415. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  84416. if (!component) {
  84417. component = new BABYLON.DepthRendererSceneComponent(scene);
  84418. scene._addComponent(component);
  84419. }
  84420. this._camera = camera;
  84421. var engine = scene.getEngine();
  84422. // Render target
  84423. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  84424. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84425. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84426. this._depthMap.refreshRate = 1;
  84427. this._depthMap.renderParticles = false;
  84428. this._depthMap.renderList = null;
  84429. // Camera to get depth map from to support multiple concurrent cameras
  84430. this._depthMap.activeCamera = this._camera;
  84431. this._depthMap.ignoreCameraViewport = true;
  84432. this._depthMap.useCameraPostProcesses = false;
  84433. // set default depth value to 1.0 (far away)
  84434. this._depthMap.onClearObservable.add(function (engine) {
  84435. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  84436. });
  84437. // Custom render function
  84438. var renderSubMesh = function (subMesh) {
  84439. var mesh = subMesh.getRenderingMesh();
  84440. var scene = _this._scene;
  84441. var engine = scene.getEngine();
  84442. var material = subMesh.getMaterial();
  84443. if (!material) {
  84444. return;
  84445. }
  84446. // Culling and reverse (right handed system)
  84447. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  84448. // Managing instances
  84449. var batch = mesh._getInstancesRenderList(subMesh._id);
  84450. if (batch.mustReturn) {
  84451. return;
  84452. }
  84453. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  84454. var camera = _this._camera || scene.activeCamera;
  84455. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  84456. engine.enableEffect(_this._effect);
  84457. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  84458. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84459. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  84460. // Alpha test
  84461. if (material && material.needAlphaTesting()) {
  84462. var alphaTexture = material.getAlphaTestTexture();
  84463. if (alphaTexture) {
  84464. _this._effect.setTexture("diffuseSampler", alphaTexture);
  84465. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84466. }
  84467. }
  84468. // Bones
  84469. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84470. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84471. }
  84472. // Draw
  84473. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  84474. }
  84475. };
  84476. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84477. var index;
  84478. if (depthOnlySubMeshes.length) {
  84479. engine.setColorWrite(false);
  84480. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84481. renderSubMesh(depthOnlySubMeshes.data[index]);
  84482. }
  84483. engine.setColorWrite(true);
  84484. }
  84485. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84486. renderSubMesh(opaqueSubMeshes.data[index]);
  84487. }
  84488. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84489. renderSubMesh(alphaTestSubMeshes.data[index]);
  84490. }
  84491. };
  84492. }
  84493. /**
  84494. * Creates the depth rendering effect and checks if the effect is ready.
  84495. * @param subMesh The submesh to be used to render the depth map of
  84496. * @param useInstances If multiple world instances should be used
  84497. * @returns if the depth renderer is ready to render the depth map
  84498. */
  84499. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  84500. var material = subMesh.getMaterial();
  84501. if (material.disableDepthWrite) {
  84502. return false;
  84503. }
  84504. var defines = [];
  84505. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84506. var mesh = subMesh.getMesh();
  84507. // Alpha test
  84508. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  84509. defines.push("#define ALPHATEST");
  84510. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84511. attribs.push(BABYLON.VertexBuffer.UVKind);
  84512. defines.push("#define UV1");
  84513. }
  84514. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84515. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84516. defines.push("#define UV2");
  84517. }
  84518. }
  84519. // Bones
  84520. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84521. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84522. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84523. if (mesh.numBoneInfluencers > 4) {
  84524. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84525. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84526. }
  84527. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84528. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84529. }
  84530. else {
  84531. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84532. }
  84533. // Instances
  84534. if (useInstances) {
  84535. defines.push("#define INSTANCES");
  84536. attribs.push("world0");
  84537. attribs.push("world1");
  84538. attribs.push("world2");
  84539. attribs.push("world3");
  84540. }
  84541. // Get correct effect
  84542. var join = defines.join("\n");
  84543. if (this._cachedDefines !== join) {
  84544. this._cachedDefines = join;
  84545. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  84546. }
  84547. return this._effect.isReady();
  84548. };
  84549. /**
  84550. * Gets the texture which the depth map will be written to.
  84551. * @returns The depth map texture
  84552. */
  84553. DepthRenderer.prototype.getDepthMap = function () {
  84554. return this._depthMap;
  84555. };
  84556. /**
  84557. * Disposes of the depth renderer.
  84558. */
  84559. DepthRenderer.prototype.dispose = function () {
  84560. this._depthMap.dispose();
  84561. };
  84562. return DepthRenderer;
  84563. }());
  84564. BABYLON.DepthRenderer = DepthRenderer;
  84565. })(BABYLON || (BABYLON = {}));
  84566. //# sourceMappingURL=babylon.depthRenderer.js.map
  84567. var BABYLON;
  84568. (function (BABYLON) {
  84569. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  84570. camera = camera || this.activeCamera;
  84571. if (!camera) {
  84572. throw "No camera available to enable depth renderer";
  84573. }
  84574. if (!this._depthRenderer) {
  84575. this._depthRenderer = {};
  84576. }
  84577. if (!this._depthRenderer[camera.id]) {
  84578. var textureType = 0;
  84579. if (this.getEngine().getCaps().textureHalfFloatRender) {
  84580. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84581. }
  84582. else if (this.getEngine().getCaps().textureFloatRender) {
  84583. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84584. }
  84585. else {
  84586. throw "Depth renderer does not support int texture type";
  84587. }
  84588. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  84589. }
  84590. return this._depthRenderer[camera.id];
  84591. };
  84592. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  84593. camera = camera || this.activeCamera;
  84594. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  84595. return;
  84596. }
  84597. this._depthRenderer[camera.id].dispose();
  84598. delete this._depthRenderer[camera.id];
  84599. };
  84600. /**
  84601. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  84602. * in several rendering techniques.
  84603. */
  84604. var DepthRendererSceneComponent = /** @class */ (function () {
  84605. /**
  84606. * Creates a new instance of the component for the given scene
  84607. * @param scene Defines the scene to register the component in
  84608. */
  84609. function DepthRendererSceneComponent(scene) {
  84610. /**
  84611. * The component name helpfull to identify the component in the list of scene components.
  84612. */
  84613. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  84614. this.scene = scene;
  84615. }
  84616. /**
  84617. * Registers the component in a given scene
  84618. */
  84619. DepthRendererSceneComponent.prototype.register = function () {
  84620. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  84621. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  84622. };
  84623. /**
  84624. * Rebuilds the elements related to this component in case of
  84625. * context lost for instance.
  84626. */
  84627. DepthRendererSceneComponent.prototype.rebuild = function () {
  84628. // Nothing to do for this component
  84629. };
  84630. /**
  84631. * Disposes the component and the associated ressources
  84632. */
  84633. DepthRendererSceneComponent.prototype.dispose = function () {
  84634. for (var key in this.scene._depthRenderer) {
  84635. this.scene._depthRenderer[key].dispose();
  84636. }
  84637. };
  84638. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  84639. if (this.scene._depthRenderer) {
  84640. for (var key in this.scene._depthRenderer) {
  84641. var depthRenderer = this.scene._depthRenderer[key];
  84642. if (!depthRenderer.useOnlyInActiveCamera) {
  84643. renderTargets.push(depthRenderer.getDepthMap());
  84644. }
  84645. }
  84646. }
  84647. };
  84648. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  84649. if (this.scene._depthRenderer) {
  84650. for (var key in this.scene._depthRenderer) {
  84651. var depthRenderer = this.scene._depthRenderer[key];
  84652. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  84653. renderTargets.push(depthRenderer.getDepthMap());
  84654. }
  84655. }
  84656. }
  84657. };
  84658. return DepthRendererSceneComponent;
  84659. }());
  84660. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  84661. })(BABYLON || (BABYLON = {}));
  84662. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  84663. var BABYLON;
  84664. (function (BABYLON) {
  84665. /**
  84666. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  84667. */
  84668. var GeometryBufferRenderer = /** @class */ (function () {
  84669. /**
  84670. * Creates a new G Buffer for the scene
  84671. * @param scene The scene the buffer belongs to
  84672. * @param ratio How big is the buffer related to the main canvas.
  84673. */
  84674. function GeometryBufferRenderer(scene, ratio) {
  84675. if (ratio === void 0) { ratio = 1; }
  84676. /**
  84677. * Dictionary used to store the previous transformation matrices of each rendered mesh
  84678. * in order to compute objects velocities when enableVelocity is set to "true"
  84679. * @hidden
  84680. */
  84681. this._previousTransformationMatrices = {};
  84682. this._enablePosition = false;
  84683. this._enableVelocity = false;
  84684. this._positionIndex = -1;
  84685. this._velocityIndex = -1;
  84686. this._scene = scene;
  84687. this._ratio = ratio;
  84688. // Register the G Buffer component to the scene.
  84689. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  84690. if (!component) {
  84691. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  84692. scene._addComponent(component);
  84693. }
  84694. // Render target
  84695. this._createRenderTargets();
  84696. }
  84697. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  84698. /**
  84699. * Set the render list (meshes to be rendered) used in the G buffer.
  84700. */
  84701. set: function (meshes) {
  84702. this._multiRenderTarget.renderList = meshes;
  84703. },
  84704. enumerable: true,
  84705. configurable: true
  84706. });
  84707. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  84708. /**
  84709. * Gets wether or not G buffer are supported by the running hardware.
  84710. * This requires draw buffer supports
  84711. */
  84712. get: function () {
  84713. return this._multiRenderTarget.isSupported;
  84714. },
  84715. enumerable: true,
  84716. configurable: true
  84717. });
  84718. /**
  84719. * Returns the index of the given texture type in the G-Buffer textures array
  84720. * @param textureType The texture type constant. For example GeometryBufferRenderer.POSITION_TEXTURE_INDEX
  84721. * @returns the index of the given texture type in the G-Buffer textures array
  84722. */
  84723. GeometryBufferRenderer.prototype.getTextureIndex = function (textureType) {
  84724. switch (textureType) {
  84725. case GeometryBufferRenderer.POSITION_TEXTURE_TYPE: return this._positionIndex;
  84726. case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE: return this._velocityIndex;
  84727. default: return -1;
  84728. }
  84729. };
  84730. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  84731. /**
  84732. * Gets a boolean indicating if objects positions are enabled for the G buffer.
  84733. */
  84734. get: function () {
  84735. return this._enablePosition;
  84736. },
  84737. /**
  84738. * Sets whether or not objects positions are enabled for the G buffer.
  84739. */
  84740. set: function (enable) {
  84741. this._enablePosition = enable;
  84742. this.dispose();
  84743. this._createRenderTargets();
  84744. },
  84745. enumerable: true,
  84746. configurable: true
  84747. });
  84748. Object.defineProperty(GeometryBufferRenderer.prototype, "enableVelocity", {
  84749. /**
  84750. * Gets a boolean indicating if objects velocities are enabled for the G buffer.
  84751. */
  84752. get: function () {
  84753. return this._enableVelocity;
  84754. },
  84755. /**
  84756. * Sets wether or not objects velocities are enabled for the G buffer.
  84757. */
  84758. set: function (enable) {
  84759. this._enableVelocity = enable;
  84760. this.dispose();
  84761. this._createRenderTargets();
  84762. },
  84763. enumerable: true,
  84764. configurable: true
  84765. });
  84766. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  84767. /**
  84768. * Gets the scene associated with the buffer.
  84769. */
  84770. get: function () {
  84771. return this._scene;
  84772. },
  84773. enumerable: true,
  84774. configurable: true
  84775. });
  84776. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  84777. /**
  84778. * Gets the ratio used by the buffer during its creation.
  84779. * How big is the buffer related to the main canvas.
  84780. */
  84781. get: function () {
  84782. return this._ratio;
  84783. },
  84784. enumerable: true,
  84785. configurable: true
  84786. });
  84787. /**
  84788. * Checks wether everything is ready to render a submesh to the G buffer.
  84789. * @param subMesh the submesh to check readiness for
  84790. * @param useInstances is the mesh drawn using instance or not
  84791. * @returns true if ready otherwise false
  84792. */
  84793. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  84794. var material = subMesh.getMaterial();
  84795. if (material && material.disableDepthWrite) {
  84796. return false;
  84797. }
  84798. var defines = [];
  84799. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84800. var mesh = subMesh.getMesh();
  84801. // Alpha test
  84802. if (material && material.needAlphaTesting()) {
  84803. defines.push("#define ALPHATEST");
  84804. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84805. attribs.push(BABYLON.VertexBuffer.UVKind);
  84806. defines.push("#define UV1");
  84807. }
  84808. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84809. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84810. defines.push("#define UV2");
  84811. }
  84812. }
  84813. // Buffers
  84814. if (this._enablePosition) {
  84815. defines.push("#define POSITION");
  84816. defines.push("#define POSITION_INDEX " + this._positionIndex);
  84817. }
  84818. if (this._enableVelocity) {
  84819. defines.push("#define VELOCITY");
  84820. defines.push("#define VELOCITY_INDEX " + this._velocityIndex);
  84821. }
  84822. // Bones
  84823. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84824. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84825. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84826. if (mesh.numBoneInfluencers > 4) {
  84827. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84828. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84829. }
  84830. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84831. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84832. }
  84833. else {
  84834. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84835. }
  84836. // Instances
  84837. if (useInstances) {
  84838. defines.push("#define INSTANCES");
  84839. attribs.push("world0");
  84840. attribs.push("world1");
  84841. attribs.push("world2");
  84842. attribs.push("world3");
  84843. }
  84844. // Setup textures count
  84845. defines.push("#define RENDER_TARGET_COUNT " + this._multiRenderTarget.textures.length);
  84846. // Get correct effect
  84847. var join = defines.join("\n");
  84848. if (this._cachedDefines !== join) {
  84849. this._cachedDefines = join;
  84850. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view", "previousWorldViewProjection"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  84851. }
  84852. return this._effect.isReady();
  84853. };
  84854. /**
  84855. * Gets the current underlying G Buffer.
  84856. * @returns the buffer
  84857. */
  84858. GeometryBufferRenderer.prototype.getGBuffer = function () {
  84859. return this._multiRenderTarget;
  84860. };
  84861. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  84862. /**
  84863. * Gets the number of samples used to render the buffer (anti aliasing).
  84864. */
  84865. get: function () {
  84866. return this._multiRenderTarget.samples;
  84867. },
  84868. /**
  84869. * Sets the number of samples used to render the buffer (anti aliasing).
  84870. */
  84871. set: function (value) {
  84872. this._multiRenderTarget.samples = value;
  84873. },
  84874. enumerable: true,
  84875. configurable: true
  84876. });
  84877. /**
  84878. * Disposes the renderer and frees up associated resources.
  84879. */
  84880. GeometryBufferRenderer.prototype.dispose = function () {
  84881. this.getGBuffer().dispose();
  84882. };
  84883. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  84884. var _this = this;
  84885. var engine = this._scene.getEngine();
  84886. var count = 2;
  84887. if (this._enablePosition) {
  84888. this._positionIndex = count;
  84889. count++;
  84890. }
  84891. if (this._enableVelocity) {
  84892. this._velocityIndex = count;
  84893. count++;
  84894. }
  84895. 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 });
  84896. if (!this.isSupported) {
  84897. return;
  84898. }
  84899. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84900. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84901. this._multiRenderTarget.refreshRate = 1;
  84902. this._multiRenderTarget.renderParticles = false;
  84903. this._multiRenderTarget.renderList = null;
  84904. // set default depth value to 1.0 (far away)
  84905. this._multiRenderTarget.onClearObservable.add(function (engine) {
  84906. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  84907. });
  84908. // Custom render function
  84909. var renderSubMesh = function (subMesh) {
  84910. var mesh = subMesh.getRenderingMesh();
  84911. var scene = _this._scene;
  84912. var engine = scene.getEngine();
  84913. var material = subMesh.getMaterial();
  84914. if (!material) {
  84915. return;
  84916. }
  84917. // Velocity
  84918. if (!_this._previousTransformationMatrices[mesh.uniqueId]) {
  84919. _this._previousTransformationMatrices[mesh.uniqueId] = BABYLON.Matrix.Identity();
  84920. }
  84921. // Culling
  84922. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  84923. // Managing instances
  84924. var batch = mesh._getInstancesRenderList(subMesh._id);
  84925. if (batch.mustReturn) {
  84926. return;
  84927. }
  84928. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  84929. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  84930. engine.enableEffect(_this._effect);
  84931. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  84932. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84933. _this._effect.setMatrix("view", scene.getViewMatrix());
  84934. // Alpha test
  84935. if (material && material.needAlphaTesting()) {
  84936. var alphaTexture = material.getAlphaTestTexture();
  84937. if (alphaTexture) {
  84938. _this._effect.setTexture("diffuseSampler", alphaTexture);
  84939. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84940. }
  84941. }
  84942. // Bones
  84943. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84944. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84945. }
  84946. // Velocity
  84947. _this._effect.setMatrix("previousWorldViewProjection", _this._previousTransformationMatrices[mesh.uniqueId]);
  84948. // Draw
  84949. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  84950. }
  84951. // Velocity
  84952. _this._previousTransformationMatrices[mesh.uniqueId] = mesh.getWorldMatrix().multiply(_this._scene.getTransformMatrix());
  84953. };
  84954. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84955. var index;
  84956. if (depthOnlySubMeshes.length) {
  84957. engine.setColorWrite(false);
  84958. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84959. renderSubMesh(depthOnlySubMeshes.data[index]);
  84960. }
  84961. engine.setColorWrite(true);
  84962. }
  84963. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84964. renderSubMesh(opaqueSubMeshes.data[index]);
  84965. }
  84966. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84967. renderSubMesh(alphaTestSubMeshes.data[index]);
  84968. }
  84969. };
  84970. };
  84971. /**
  84972. * Constant used to retrieve the position texture index in the G-Buffer textures array
  84973. * using getIndex(GeometryBufferRenderer.POSITION_TEXTURE_INDEX)
  84974. */
  84975. GeometryBufferRenderer.POSITION_TEXTURE_TYPE = 1;
  84976. /**
  84977. * Constant used to retrieve the velocity texture index in the G-Buffer textures array
  84978. * using getIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_INDEX)
  84979. */
  84980. GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE = 2;
  84981. return GeometryBufferRenderer;
  84982. }());
  84983. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  84984. })(BABYLON || (BABYLON = {}));
  84985. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  84986. var BABYLON;
  84987. (function (BABYLON) {
  84988. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  84989. get: function () {
  84990. this._geometryBufferRenderer;
  84991. },
  84992. set: function (value) {
  84993. if (value && value.isSupported) {
  84994. this._geometryBufferRenderer = value;
  84995. }
  84996. },
  84997. enumerable: true,
  84998. configurable: true
  84999. });
  85000. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  85001. if (ratio === void 0) { ratio = 1; }
  85002. if (this._geometryBufferRenderer) {
  85003. return this._geometryBufferRenderer;
  85004. }
  85005. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  85006. if (!this._geometryBufferRenderer.isSupported) {
  85007. this._geometryBufferRenderer = null;
  85008. }
  85009. return this._geometryBufferRenderer;
  85010. };
  85011. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  85012. if (!this._geometryBufferRenderer) {
  85013. return;
  85014. }
  85015. this._geometryBufferRenderer.dispose();
  85016. this._geometryBufferRenderer = null;
  85017. };
  85018. /**
  85019. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  85020. * in several rendering techniques.
  85021. */
  85022. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  85023. /**
  85024. * Creates a new instance of the component for the given scene
  85025. * @param scene Defines the scene to register the component in
  85026. */
  85027. function GeometryBufferRendererSceneComponent(scene) {
  85028. /**
  85029. * The component name helpful to identify the component in the list of scene components.
  85030. */
  85031. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  85032. this.scene = scene;
  85033. }
  85034. /**
  85035. * Registers the component in a given scene
  85036. */
  85037. GeometryBufferRendererSceneComponent.prototype.register = function () {
  85038. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  85039. };
  85040. /**
  85041. * Rebuilds the elements related to this component in case of
  85042. * context lost for instance.
  85043. */
  85044. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  85045. // Nothing to do for this component
  85046. };
  85047. /**
  85048. * Disposes the component and the associated ressources
  85049. */
  85050. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  85051. // Nothing to do for this component
  85052. };
  85053. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  85054. if (this.scene._geometryBufferRenderer) {
  85055. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  85056. }
  85057. };
  85058. return GeometryBufferRendererSceneComponent;
  85059. }());
  85060. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  85061. })(BABYLON || (BABYLON = {}));
  85062. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  85063. var BABYLON;
  85064. (function (BABYLON) {
  85065. /**
  85066. * Render pipeline to produce ssao effect
  85067. */
  85068. var SSAORenderingPipeline = /** @class */ (function (_super) {
  85069. __extends(SSAORenderingPipeline, _super);
  85070. /**
  85071. * @constructor
  85072. * @param name - The rendering pipeline name
  85073. * @param scene - The scene linked to this pipeline
  85074. * @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 }
  85075. * @param cameras - The array of cameras that the rendering pipeline will be attached to
  85076. */
  85077. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  85078. var _this = _super.call(this, scene.getEngine(), name) || this;
  85079. // Members
  85080. /**
  85081. * @ignore
  85082. * The PassPostProcess id in the pipeline that contains the original scene color
  85083. */
  85084. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  85085. /**
  85086. * @ignore
  85087. * The SSAO PostProcess id in the pipeline
  85088. */
  85089. _this.SSAORenderEffect = "SSAORenderEffect";
  85090. /**
  85091. * @ignore
  85092. * The horizontal blur PostProcess id in the pipeline
  85093. */
  85094. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  85095. /**
  85096. * @ignore
  85097. * The vertical blur PostProcess id in the pipeline
  85098. */
  85099. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  85100. /**
  85101. * @ignore
  85102. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  85103. */
  85104. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  85105. /**
  85106. * The output strength of the SSAO post-process. Default value is 1.0.
  85107. */
  85108. _this.totalStrength = 1.0;
  85109. /**
  85110. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  85111. */
  85112. _this.radius = 0.0001;
  85113. /**
  85114. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  85115. * Must not be equal to fallOff and superior to fallOff.
  85116. * Default value is 0.975
  85117. */
  85118. _this.area = 0.0075;
  85119. /**
  85120. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  85121. * Must not be equal to area and inferior to area.
  85122. * Default value is 0.0
  85123. */
  85124. _this.fallOff = 0.000001;
  85125. /**
  85126. * The base color of the SSAO post-process
  85127. * The final result is "base + ssao" between [0, 1]
  85128. */
  85129. _this.base = 0.5;
  85130. _this._firstUpdate = true;
  85131. _this._scene = scene;
  85132. // Set up assets
  85133. _this._createRandomTexture();
  85134. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  85135. var ssaoRatio = ratio.ssaoRatio || ratio;
  85136. var combineRatio = ratio.combineRatio || ratio;
  85137. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  85138. _this._createSSAOPostProcess(ssaoRatio);
  85139. _this._createBlurPostProcess(ssaoRatio);
  85140. _this._createSSAOCombinePostProcess(combineRatio);
  85141. // Set up pipeline
  85142. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  85143. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  85144. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  85145. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  85146. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  85147. // Finish
  85148. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85149. if (cameras) {
  85150. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85151. }
  85152. return _this;
  85153. }
  85154. // Public Methods
  85155. /**
  85156. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  85157. */
  85158. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  85159. if (disableDepthRender === void 0) { disableDepthRender = false; }
  85160. for (var i = 0; i < this._scene.cameras.length; i++) {
  85161. var camera = this._scene.cameras[i];
  85162. this._originalColorPostProcess.dispose(camera);
  85163. this._ssaoPostProcess.dispose(camera);
  85164. this._blurHPostProcess.dispose(camera);
  85165. this._blurVPostProcess.dispose(camera);
  85166. this._ssaoCombinePostProcess.dispose(camera);
  85167. }
  85168. this._randomTexture.dispose();
  85169. if (disableDepthRender) {
  85170. this._scene.disableDepthRenderer();
  85171. }
  85172. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85173. _super.prototype.dispose.call(this);
  85174. };
  85175. // Private Methods
  85176. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  85177. var _this = this;
  85178. var size = 16;
  85179. 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);
  85180. 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);
  85181. this._blurHPostProcess.onActivateObservable.add(function () {
  85182. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  85183. _this._blurHPostProcess.kernel = size * dw;
  85184. });
  85185. this._blurVPostProcess.onActivateObservable.add(function () {
  85186. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  85187. _this._blurVPostProcess.kernel = size * dw;
  85188. });
  85189. };
  85190. /** @hidden */
  85191. SSAORenderingPipeline.prototype._rebuild = function () {
  85192. this._firstUpdate = true;
  85193. _super.prototype._rebuild.call(this);
  85194. };
  85195. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  85196. var _this = this;
  85197. var numSamples = 16;
  85198. var sampleSphere = [
  85199. 0.5381, 0.1856, -0.4319,
  85200. 0.1379, 0.2486, 0.4430,
  85201. 0.3371, 0.5679, -0.0057,
  85202. -0.6999, -0.0451, -0.0019,
  85203. 0.0689, -0.1598, -0.8547,
  85204. 0.0560, 0.0069, -0.1843,
  85205. -0.0146, 0.1402, 0.0762,
  85206. 0.0100, -0.1924, -0.0344,
  85207. -0.3577, -0.5301, -0.4358,
  85208. -0.3169, 0.1063, 0.0158,
  85209. 0.0103, -0.5869, 0.0046,
  85210. -0.0897, -0.4940, 0.3287,
  85211. 0.7119, -0.0154, -0.0918,
  85212. -0.0533, 0.0596, -0.5411,
  85213. 0.0352, -0.0631, 0.5460,
  85214. -0.4776, 0.2847, -0.0271
  85215. ];
  85216. var samplesFactor = 1.0 / numSamples;
  85217. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  85218. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  85219. "area", "fallOff", "base", "range", "viewport"
  85220. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  85221. this._ssaoPostProcess.onApply = function (effect) {
  85222. if (_this._firstUpdate) {
  85223. effect.setArray3("sampleSphere", sampleSphere);
  85224. effect.setFloat("samplesFactor", samplesFactor);
  85225. effect.setFloat("randTextureTiles", 4.0);
  85226. }
  85227. effect.setFloat("totalStrength", _this.totalStrength);
  85228. effect.setFloat("radius", _this.radius);
  85229. effect.setFloat("area", _this.area);
  85230. effect.setFloat("fallOff", _this.fallOff);
  85231. effect.setFloat("base", _this.base);
  85232. effect.setTexture("textureSampler", _this._depthTexture);
  85233. effect.setTexture("randomSampler", _this._randomTexture);
  85234. };
  85235. };
  85236. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  85237. var _this = this;
  85238. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85239. this._ssaoCombinePostProcess.onApply = function (effect) {
  85240. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  85241. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  85242. };
  85243. };
  85244. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  85245. var size = 512;
  85246. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85247. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  85248. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  85249. var context = this._randomTexture.getContext();
  85250. var rand = function (min, max) {
  85251. return Math.random() * (max - min) + min;
  85252. };
  85253. var randVector = BABYLON.Vector3.Zero();
  85254. for (var x = 0; x < size; x++) {
  85255. for (var y = 0; y < size; y++) {
  85256. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  85257. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  85258. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  85259. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  85260. context.fillRect(x, y, 1, 1);
  85261. }
  85262. }
  85263. this._randomTexture.update(false);
  85264. };
  85265. __decorate([
  85266. BABYLON.serialize()
  85267. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  85268. __decorate([
  85269. BABYLON.serialize()
  85270. ], SSAORenderingPipeline.prototype, "radius", void 0);
  85271. __decorate([
  85272. BABYLON.serialize()
  85273. ], SSAORenderingPipeline.prototype, "area", void 0);
  85274. __decorate([
  85275. BABYLON.serialize()
  85276. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  85277. __decorate([
  85278. BABYLON.serialize()
  85279. ], SSAORenderingPipeline.prototype, "base", void 0);
  85280. return SSAORenderingPipeline;
  85281. }(BABYLON.PostProcessRenderPipeline));
  85282. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  85283. })(BABYLON || (BABYLON = {}));
  85284. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  85285. var BABYLON;
  85286. (function (BABYLON) {
  85287. /**
  85288. * Render pipeline to produce ssao effect
  85289. */
  85290. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  85291. __extends(SSAO2RenderingPipeline, _super);
  85292. /**
  85293. * @constructor
  85294. * @param name The rendering pipeline name
  85295. * @param scene The scene linked to this pipeline
  85296. * @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 }
  85297. * @param cameras The array of cameras that the rendering pipeline will be attached to
  85298. */
  85299. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  85300. var _this = _super.call(this, scene.getEngine(), name) || this;
  85301. // Members
  85302. /**
  85303. * @ignore
  85304. * The PassPostProcess id in the pipeline that contains the original scene color
  85305. */
  85306. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  85307. /**
  85308. * @ignore
  85309. * The SSAO PostProcess id in the pipeline
  85310. */
  85311. _this.SSAORenderEffect = "SSAORenderEffect";
  85312. /**
  85313. * @ignore
  85314. * The horizontal blur PostProcess id in the pipeline
  85315. */
  85316. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  85317. /**
  85318. * @ignore
  85319. * The vertical blur PostProcess id in the pipeline
  85320. */
  85321. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  85322. /**
  85323. * @ignore
  85324. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  85325. */
  85326. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  85327. /**
  85328. * The output strength of the SSAO post-process. Default value is 1.0.
  85329. */
  85330. _this.totalStrength = 1.0;
  85331. /**
  85332. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  85333. */
  85334. _this.maxZ = 100.0;
  85335. /**
  85336. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  85337. */
  85338. _this.minZAspect = 0.2;
  85339. _this._samples = 8;
  85340. _this._textureSamples = 1;
  85341. _this._expensiveBlur = true;
  85342. /**
  85343. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  85344. */
  85345. _this.radius = 2.0;
  85346. /**
  85347. * The base color of the SSAO post-process
  85348. * The final result is "base + ssao" between [0, 1]
  85349. */
  85350. _this.base = 0;
  85351. _this._firstUpdate = true;
  85352. _this._bits = new Uint32Array(1);
  85353. _this._scene = scene;
  85354. _this._ratio = ratio;
  85355. if (!_this.isSupported) {
  85356. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  85357. return _this;
  85358. }
  85359. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  85360. var blurRatio = _this._ratio.blurRatio || ratio;
  85361. // Set up assets
  85362. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  85363. _this._createRandomTexture();
  85364. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  85365. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  85366. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  85367. _this._originalColorPostProcess.samples = _this.textureSamples;
  85368. _this._createSSAOPostProcess(1.0);
  85369. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  85370. _this._createSSAOCombinePostProcess(blurRatio);
  85371. // Set up pipeline
  85372. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  85373. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  85374. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  85375. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  85376. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  85377. // Finish
  85378. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85379. if (cameras) {
  85380. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85381. }
  85382. return _this;
  85383. }
  85384. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  85385. get: function () {
  85386. return this._samples;
  85387. },
  85388. /**
  85389. * Number of samples used for the SSAO calculations. Default value is 8
  85390. */
  85391. set: function (n) {
  85392. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  85393. this._samples = n;
  85394. this._sampleSphere = this._generateHemisphere();
  85395. this._firstUpdate = true;
  85396. },
  85397. enumerable: true,
  85398. configurable: true
  85399. });
  85400. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  85401. get: function () {
  85402. return this._textureSamples;
  85403. },
  85404. /**
  85405. * Number of samples to use for antialiasing
  85406. */
  85407. set: function (n) {
  85408. this._textureSamples = n;
  85409. this._originalColorPostProcess.samples = n;
  85410. this._blurHPostProcess.samples = n;
  85411. this._blurVPostProcess.samples = n;
  85412. this._ssaoPostProcess.samples = n;
  85413. this._ssaoCombinePostProcess.samples = n;
  85414. },
  85415. enumerable: true,
  85416. configurable: true
  85417. });
  85418. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  85419. get: function () {
  85420. return this._expensiveBlur;
  85421. },
  85422. /**
  85423. * If bilateral blur should be used
  85424. */
  85425. set: function (b) {
  85426. 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"]);
  85427. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  85428. this._expensiveBlur = b;
  85429. this._firstUpdate = true;
  85430. },
  85431. enumerable: true,
  85432. configurable: true
  85433. });
  85434. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  85435. /**
  85436. * Support test.
  85437. */
  85438. get: function () {
  85439. var engine = BABYLON.Engine.LastCreatedEngine;
  85440. if (!engine) {
  85441. return false;
  85442. }
  85443. return engine.getCaps().drawBuffersExtension;
  85444. },
  85445. enumerable: true,
  85446. configurable: true
  85447. });
  85448. // Public Methods
  85449. /**
  85450. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  85451. */
  85452. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  85453. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  85454. for (var i = 0; i < this._scene.cameras.length; i++) {
  85455. var camera = this._scene.cameras[i];
  85456. this._originalColorPostProcess.dispose(camera);
  85457. this._ssaoPostProcess.dispose(camera);
  85458. this._blurHPostProcess.dispose(camera);
  85459. this._blurVPostProcess.dispose(camera);
  85460. this._ssaoCombinePostProcess.dispose(camera);
  85461. }
  85462. this._randomTexture.dispose();
  85463. if (disableGeometryBufferRenderer) {
  85464. this._scene.disableGeometryBufferRenderer();
  85465. }
  85466. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85467. _super.prototype.dispose.call(this);
  85468. };
  85469. // Private Methods
  85470. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  85471. var _this = this;
  85472. this._samplerOffsets = [];
  85473. var expensive = this.expensiveBlur;
  85474. for (var i = -8; i < 8; i++) {
  85475. this._samplerOffsets.push(i * 2 + 0.5);
  85476. }
  85477. 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");
  85478. this._blurHPostProcess.onApply = function (effect) {
  85479. if (!_this._scene.activeCamera) {
  85480. return;
  85481. }
  85482. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  85483. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85484. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85485. effect.setFloat("radius", _this.radius);
  85486. effect.setTexture("depthSampler", _this._depthTexture);
  85487. if (_this._firstUpdate) {
  85488. effect.setArray("samplerOffsets", _this._samplerOffsets);
  85489. }
  85490. };
  85491. 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");
  85492. this._blurVPostProcess.onApply = function (effect) {
  85493. if (!_this._scene.activeCamera) {
  85494. return;
  85495. }
  85496. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  85497. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85498. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85499. effect.setFloat("radius", _this.radius);
  85500. effect.setTexture("depthSampler", _this._depthTexture);
  85501. if (_this._firstUpdate) {
  85502. effect.setArray("samplerOffsets", _this._samplerOffsets);
  85503. _this._firstUpdate = false;
  85504. }
  85505. };
  85506. this._blurHPostProcess.samples = this.textureSamples;
  85507. this._blurVPostProcess.samples = this.textureSamples;
  85508. };
  85509. /** @hidden */
  85510. SSAO2RenderingPipeline.prototype._rebuild = function () {
  85511. this._firstUpdate = true;
  85512. _super.prototype._rebuild.call(this);
  85513. };
  85514. //Van der Corput radical inverse
  85515. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  85516. this._bits[0] = i;
  85517. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  85518. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  85519. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  85520. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  85521. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  85522. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  85523. };
  85524. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  85525. return [i / n, this._radicalInverse_VdC(i)];
  85526. };
  85527. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  85528. var phi = v * 2.0 * Math.PI;
  85529. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  85530. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  85531. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  85532. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  85533. };
  85534. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  85535. var numSamples = this.samples;
  85536. var result = [];
  85537. var vector;
  85538. var i = 0;
  85539. while (i < numSamples) {
  85540. if (numSamples < 16) {
  85541. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  85542. }
  85543. else {
  85544. var rand = this._hammersley(i, numSamples);
  85545. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  85546. }
  85547. result.push(vector.x, vector.y, vector.z);
  85548. i++;
  85549. }
  85550. return result;
  85551. };
  85552. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  85553. var _this = this;
  85554. var numSamples = this.samples;
  85555. this._sampleSphere = this._generateHemisphere();
  85556. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  85557. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  85558. "base", "range", "projection", "near", "far", "texelSize",
  85559. "xViewport", "yViewport", "maxZ", "minZAspect"
  85560. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  85561. this._ssaoPostProcess.onApply = function (effect) {
  85562. if (_this._firstUpdate) {
  85563. effect.setArray3("sampleSphere", _this._sampleSphere);
  85564. effect.setFloat("randTextureTiles", 32.0);
  85565. }
  85566. if (!_this._scene.activeCamera) {
  85567. return;
  85568. }
  85569. effect.setFloat("samplesFactor", 1 / _this.samples);
  85570. effect.setFloat("totalStrength", _this.totalStrength);
  85571. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  85572. effect.setFloat("radius", _this.radius);
  85573. effect.setFloat("maxZ", _this.maxZ);
  85574. effect.setFloat("minZAspect", _this.minZAspect);
  85575. effect.setFloat("base", _this.base);
  85576. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85577. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85578. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  85579. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  85580. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  85581. effect.setTexture("textureSampler", _this._depthTexture);
  85582. effect.setTexture("normalSampler", _this._normalTexture);
  85583. effect.setTexture("randomSampler", _this._randomTexture);
  85584. };
  85585. this._ssaoPostProcess.samples = this.textureSamples;
  85586. };
  85587. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  85588. var _this = this;
  85589. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85590. this._ssaoCombinePostProcess.onApply = function (effect) {
  85591. var viewport = _this._scene.activeCamera.viewport;
  85592. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  85593. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  85594. };
  85595. this._ssaoCombinePostProcess.samples = this.textureSamples;
  85596. };
  85597. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  85598. var size = 128;
  85599. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85600. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  85601. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  85602. var context = this._randomTexture.getContext();
  85603. var rand = function (min, max) {
  85604. return Math.random() * (max - min) + min;
  85605. };
  85606. var randVector = BABYLON.Vector3.Zero();
  85607. for (var x = 0; x < size; x++) {
  85608. for (var y = 0; y < size; y++) {
  85609. randVector.x = rand(0.0, 1.0);
  85610. randVector.y = rand(0.0, 1.0);
  85611. randVector.z = 0.0;
  85612. randVector.normalize();
  85613. randVector.scaleInPlace(255);
  85614. randVector.x = Math.floor(randVector.x);
  85615. randVector.y = Math.floor(randVector.y);
  85616. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  85617. context.fillRect(x, y, 1, 1);
  85618. }
  85619. }
  85620. this._randomTexture.update(false);
  85621. };
  85622. /**
  85623. * Serialize the rendering pipeline (Used when exporting)
  85624. * @returns the serialized object
  85625. */
  85626. SSAO2RenderingPipeline.prototype.serialize = function () {
  85627. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85628. serializationObject.customType = "SSAO2RenderingPipeline";
  85629. return serializationObject;
  85630. };
  85631. /**
  85632. * Parse the serialized pipeline
  85633. * @param source Source pipeline.
  85634. * @param scene The scene to load the pipeline to.
  85635. * @param rootUrl The URL of the serialized pipeline.
  85636. * @returns An instantiated pipeline from the serialized object.
  85637. */
  85638. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  85639. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  85640. };
  85641. __decorate([
  85642. BABYLON.serialize()
  85643. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  85644. __decorate([
  85645. BABYLON.serialize()
  85646. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  85647. __decorate([
  85648. BABYLON.serialize()
  85649. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  85650. __decorate([
  85651. BABYLON.serialize("samples")
  85652. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  85653. __decorate([
  85654. BABYLON.serialize("textureSamples")
  85655. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  85656. __decorate([
  85657. BABYLON.serialize()
  85658. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  85659. __decorate([
  85660. BABYLON.serialize("expensiveBlur")
  85661. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  85662. __decorate([
  85663. BABYLON.serialize()
  85664. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  85665. __decorate([
  85666. BABYLON.serialize()
  85667. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  85668. return SSAO2RenderingPipeline;
  85669. }(BABYLON.PostProcessRenderPipeline));
  85670. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  85671. })(BABYLON || (BABYLON = {}));
  85672. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  85673. var BABYLON;
  85674. (function (BABYLON) {
  85675. /**
  85676. * BABYLON.JS Chromatic Aberration GLSL Shader
  85677. * Author: Olivier Guyot
  85678. * Separates very slightly R, G and B colors on the edges of the screen
  85679. * Inspired by Francois Tarlier & Martins Upitis
  85680. */
  85681. var LensRenderingPipeline = /** @class */ (function (_super) {
  85682. __extends(LensRenderingPipeline, _super);
  85683. /**
  85684. * @constructor
  85685. *
  85686. * Effect parameters are as follow:
  85687. * {
  85688. * chromatic_aberration: number; // from 0 to x (1 for realism)
  85689. * edge_blur: number; // from 0 to x (1 for realism)
  85690. * distortion: number; // from 0 to x (1 for realism)
  85691. * grain_amount: number; // from 0 to 1
  85692. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  85693. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  85694. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  85695. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  85696. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  85697. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  85698. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  85699. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  85700. * }
  85701. * Note: if an effect parameter is unset, effect is disabled
  85702. *
  85703. * @param name The rendering pipeline name
  85704. * @param parameters - An object containing all parameters (see above)
  85705. * @param scene The scene linked to this pipeline
  85706. * @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)
  85707. * @param cameras The array of cameras that the rendering pipeline will be attached to
  85708. */
  85709. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  85710. if (ratio === void 0) { ratio = 1.0; }
  85711. var _this = _super.call(this, scene.getEngine(), name) || this;
  85712. // Lens effects can be of the following:
  85713. // - chromatic aberration (slight shift of RGB colors)
  85714. // - blur on the edge of the lens
  85715. // - lens distortion
  85716. // - depth-of-field blur & highlights enhancing
  85717. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  85718. // - grain effect (noise or custom texture)
  85719. // Two additional texture samplers are needed:
  85720. // - depth map (for depth-of-field)
  85721. // - grain texture
  85722. /**
  85723. * @ignore
  85724. * The chromatic aberration PostProcess id in the pipeline
  85725. */
  85726. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  85727. /**
  85728. * @ignore
  85729. * The highlights enhancing PostProcess id in the pipeline
  85730. */
  85731. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  85732. /**
  85733. * @ignore
  85734. * The depth-of-field PostProcess id in the pipeline
  85735. */
  85736. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  85737. _this._scene = scene;
  85738. // Fetch texture samplers
  85739. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  85740. if (parameters.grain_texture) {
  85741. _this._grainTexture = parameters.grain_texture;
  85742. }
  85743. else {
  85744. _this._createGrainTexture();
  85745. }
  85746. // save parameters
  85747. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  85748. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  85749. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  85750. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  85751. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  85752. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  85753. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  85754. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  85755. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  85756. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  85757. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  85758. // Create effects
  85759. _this._createChromaticAberrationPostProcess(ratio);
  85760. _this._createHighlightsPostProcess(ratio);
  85761. _this._createDepthOfFieldPostProcess(ratio / 4);
  85762. // Set up pipeline
  85763. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  85764. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  85765. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  85766. if (_this._highlightsGain === -1) {
  85767. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  85768. }
  85769. // Finish
  85770. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85771. if (cameras) {
  85772. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85773. }
  85774. return _this;
  85775. }
  85776. // public methods (self explanatory)
  85777. /**
  85778. * Sets the amount of blur at the edges
  85779. * @param amount blur amount
  85780. */
  85781. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  85782. /**
  85783. * Sets edge blur to 0
  85784. */
  85785. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  85786. /**
  85787. * Sets the amout of grain
  85788. * @param amount Amount of grain
  85789. */
  85790. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  85791. /**
  85792. * Set grain amount to 0
  85793. */
  85794. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  85795. /**
  85796. * Sets the chromatic aberration amount
  85797. * @param amount amount of chromatic aberration
  85798. */
  85799. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  85800. /**
  85801. * Sets chromatic aberration amount to 0
  85802. */
  85803. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  85804. /**
  85805. * Sets the EdgeDistortion amount
  85806. * @param amount amount of EdgeDistortion
  85807. */
  85808. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  85809. /**
  85810. * Sets edge distortion to 0
  85811. */
  85812. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  85813. /**
  85814. * Sets the FocusDistance amount
  85815. * @param amount amount of FocusDistance
  85816. */
  85817. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  85818. /**
  85819. * Disables depth of field
  85820. */
  85821. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  85822. /**
  85823. * Sets the Aperture amount
  85824. * @param amount amount of Aperture
  85825. */
  85826. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  85827. /**
  85828. * Sets the DarkenOutOfFocus amount
  85829. * @param amount amount of DarkenOutOfFocus
  85830. */
  85831. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  85832. /**
  85833. * Creates a pentagon bokeh effect
  85834. */
  85835. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  85836. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  85837. };
  85838. /**
  85839. * Disables the pentagon bokeh effect
  85840. */
  85841. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  85842. this._highlightsPostProcess.updateEffect();
  85843. };
  85844. /**
  85845. * Enables noise blur
  85846. */
  85847. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  85848. /**
  85849. * Disables noise blur
  85850. */
  85851. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  85852. /**
  85853. * Sets the HighlightsGain amount
  85854. * @param amount amount of HighlightsGain
  85855. */
  85856. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  85857. this._highlightsGain = amount;
  85858. };
  85859. /**
  85860. * Sets the HighlightsThreshold amount
  85861. * @param amount amount of HighlightsThreshold
  85862. */
  85863. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  85864. if (this._highlightsGain === -1) {
  85865. this._highlightsGain = 1.0;
  85866. }
  85867. this._highlightsThreshold = amount;
  85868. };
  85869. /**
  85870. * Disables highlights
  85871. */
  85872. LensRenderingPipeline.prototype.disableHighlights = function () {
  85873. this._highlightsGain = -1;
  85874. };
  85875. /**
  85876. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  85877. * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
  85878. */
  85879. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  85880. if (disableDepthRender === void 0) { disableDepthRender = false; }
  85881. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85882. this._chromaticAberrationPostProcess = null;
  85883. this._highlightsPostProcess = null;
  85884. this._depthOfFieldPostProcess = null;
  85885. this._grainTexture.dispose();
  85886. if (disableDepthRender) {
  85887. this._scene.disableDepthRenderer();
  85888. }
  85889. };
  85890. // colors shifting and distortion
  85891. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  85892. var _this = this;
  85893. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  85894. [], // samplers
  85895. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85896. this._chromaticAberrationPostProcess.onApply = function (effect) {
  85897. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  85898. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  85899. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  85900. effect.setFloat('radialIntensity', 1);
  85901. effect.setFloat2('direction', 17, 17);
  85902. effect.setFloat2('centerPosition', 0.5, 0.5);
  85903. };
  85904. };
  85905. // highlights enhancing
  85906. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  85907. var _this = this;
  85908. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  85909. [], // samplers
  85910. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  85911. this._highlightsPostProcess.onApply = function (effect) {
  85912. effect.setFloat('gain', _this._highlightsGain);
  85913. effect.setFloat('threshold', _this._highlightsThreshold);
  85914. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  85915. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  85916. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  85917. };
  85918. };
  85919. // colors shifting and distortion
  85920. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  85921. var _this = this;
  85922. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  85923. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  85924. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  85925. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85926. this._depthOfFieldPostProcess.onApply = function (effect) {
  85927. effect.setTexture("depthSampler", _this._depthTexture);
  85928. effect.setTexture("grainSampler", _this._grainTexture);
  85929. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  85930. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  85931. effect.setFloat('grain_amount', _this._grainAmount);
  85932. effect.setBool('blur_noise', _this._blurNoise);
  85933. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  85934. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  85935. effect.setFloat('distortion', _this._distortion);
  85936. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  85937. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  85938. effect.setFloat('aperture', _this._dofAperture);
  85939. effect.setFloat('darken', _this._dofDarken);
  85940. effect.setFloat('edge_blur', _this._edgeBlur);
  85941. effect.setBool('highlights', (_this._highlightsGain !== -1));
  85942. if (_this._scene.activeCamera) {
  85943. effect.setFloat('near', _this._scene.activeCamera.minZ);
  85944. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  85945. }
  85946. };
  85947. };
  85948. // creates a black and white random noise texture, 512x512
  85949. LensRenderingPipeline.prototype._createGrainTexture = function () {
  85950. var size = 512;
  85951. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85952. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  85953. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  85954. var context = this._grainTexture.getContext();
  85955. var rand = function (min, max) {
  85956. return Math.random() * (max - min) + min;
  85957. };
  85958. var value;
  85959. for (var x = 0; x < size; x++) {
  85960. for (var y = 0; y < size; y++) {
  85961. value = Math.floor(rand(0.42, 0.58) * 255);
  85962. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  85963. context.fillRect(x, y, 1, 1);
  85964. }
  85965. }
  85966. this._grainTexture.update(false);
  85967. };
  85968. return LensRenderingPipeline;
  85969. }(BABYLON.PostProcessRenderPipeline));
  85970. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  85971. })(BABYLON || (BABYLON = {}));
  85972. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  85973. var BABYLON;
  85974. (function (BABYLON) {
  85975. /**
  85976. * Standard rendering pipeline
  85977. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  85978. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  85979. */
  85980. var StandardRenderingPipeline = /** @class */ (function (_super) {
  85981. __extends(StandardRenderingPipeline, _super);
  85982. /**
  85983. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  85984. * @constructor
  85985. * @param name The rendering pipeline name
  85986. * @param scene The scene linked to this pipeline
  85987. * @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)
  85988. * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null.
  85989. * @param cameras The array of cameras that the rendering pipeline will be attached to
  85990. */
  85991. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  85992. if (originalPostProcess === void 0) { originalPostProcess = null; }
  85993. var _this = _super.call(this, scene.getEngine(), name) || this;
  85994. /**
  85995. * Post-process used to down scale an image x4
  85996. */
  85997. _this.downSampleX4PostProcess = null;
  85998. /**
  85999. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  86000. */
  86001. _this.brightPassPostProcess = null;
  86002. /**
  86003. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  86004. */
  86005. _this.blurHPostProcesses = [];
  86006. /**
  86007. * Post-process array storing all the vertical blur post-processes used by the pipeline
  86008. */
  86009. _this.blurVPostProcesses = [];
  86010. /**
  86011. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  86012. */
  86013. _this.textureAdderPostProcess = null;
  86014. /**
  86015. * Post-process used to create volumetric lighting effect
  86016. */
  86017. _this.volumetricLightPostProcess = null;
  86018. /**
  86019. * Post-process used to smooth the previous volumetric light post-process on the X axis
  86020. */
  86021. _this.volumetricLightSmoothXPostProcess = null;
  86022. /**
  86023. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  86024. */
  86025. _this.volumetricLightSmoothYPostProcess = null;
  86026. /**
  86027. * Post-process used to merge the volumetric light effect and the real scene color
  86028. */
  86029. _this.volumetricLightMergePostProces = null;
  86030. /**
  86031. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  86032. */
  86033. _this.volumetricLightFinalPostProcess = null;
  86034. /**
  86035. * Base post-process used to calculate the average luminance of the final image for HDR
  86036. */
  86037. _this.luminancePostProcess = null;
  86038. /**
  86039. * Post-processes used to create down sample post-processes in order to get
  86040. * the average luminance of the final image for HDR
  86041. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  86042. */
  86043. _this.luminanceDownSamplePostProcesses = [];
  86044. /**
  86045. * Post-process used to create a HDR effect (light adaptation)
  86046. */
  86047. _this.hdrPostProcess = null;
  86048. /**
  86049. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  86050. */
  86051. _this.textureAdderFinalPostProcess = null;
  86052. /**
  86053. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  86054. */
  86055. _this.lensFlareFinalPostProcess = null;
  86056. /**
  86057. * Post-process used to merge the final HDR post-process and the real scene color
  86058. */
  86059. _this.hdrFinalPostProcess = null;
  86060. /**
  86061. * Post-process used to create a lens flare effect
  86062. */
  86063. _this.lensFlarePostProcess = null;
  86064. /**
  86065. * Post-process that merges the result of the lens flare post-process and the real scene color
  86066. */
  86067. _this.lensFlareComposePostProcess = null;
  86068. /**
  86069. * Post-process used to create a motion blur effect
  86070. */
  86071. _this.motionBlurPostProcess = null;
  86072. /**
  86073. * Post-process used to create a depth of field effect
  86074. */
  86075. _this.depthOfFieldPostProcess = null;
  86076. /**
  86077. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  86078. */
  86079. _this.fxaaPostProcess = null;
  86080. // Values
  86081. /**
  86082. * Represents the brightness threshold in order to configure the illuminated surfaces
  86083. */
  86084. _this.brightThreshold = 1.0;
  86085. /**
  86086. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  86087. */
  86088. _this.blurWidth = 512.0;
  86089. /**
  86090. * Sets if the blur for highlighted surfaces must be only horizontal
  86091. */
  86092. _this.horizontalBlur = false;
  86093. /**
  86094. * Sets the overall exposure used by the pipeline
  86095. */
  86096. _this.exposure = 1.0;
  86097. /**
  86098. * Texture used typically to simulate "dirty" on camera lens
  86099. */
  86100. _this.lensTexture = null;
  86101. /**
  86102. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  86103. */
  86104. _this.volumetricLightCoefficient = 0.2;
  86105. /**
  86106. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  86107. */
  86108. _this.volumetricLightPower = 4.0;
  86109. /**
  86110. * Used the set the blur intensity to smooth the volumetric lights
  86111. */
  86112. _this.volumetricLightBlurScale = 64.0;
  86113. /**
  86114. * Light (spot or directional) used to generate the volumetric lights rays
  86115. * The source light must have a shadow generate so the pipeline can get its
  86116. * depth map
  86117. */
  86118. _this.sourceLight = null;
  86119. /**
  86120. * For eye adaptation, represents the minimum luminance the eye can see
  86121. */
  86122. _this.hdrMinimumLuminance = 1.0;
  86123. /**
  86124. * For eye adaptation, represents the decrease luminance speed
  86125. */
  86126. _this.hdrDecreaseRate = 0.5;
  86127. /**
  86128. * For eye adaptation, represents the increase luminance speed
  86129. */
  86130. _this.hdrIncreaseRate = 0.5;
  86131. /**
  86132. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  86133. */
  86134. _this.lensColorTexture = null;
  86135. /**
  86136. * The overall strengh for the lens flare effect
  86137. */
  86138. _this.lensFlareStrength = 20.0;
  86139. /**
  86140. * Dispersion coefficient for lens flare ghosts
  86141. */
  86142. _this.lensFlareGhostDispersal = 1.4;
  86143. /**
  86144. * Main lens flare halo width
  86145. */
  86146. _this.lensFlareHaloWidth = 0.7;
  86147. /**
  86148. * Based on the lens distortion effect, defines how much the lens flare result
  86149. * is distorted
  86150. */
  86151. _this.lensFlareDistortionStrength = 16.0;
  86152. /**
  86153. * Lens star texture must be used to simulate rays on the flares and is available
  86154. * in the documentation
  86155. */
  86156. _this.lensStarTexture = null;
  86157. /**
  86158. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  86159. * flare effect by taking account of the dirt texture
  86160. */
  86161. _this.lensFlareDirtTexture = null;
  86162. /**
  86163. * Represents the focal length for the depth of field effect
  86164. */
  86165. _this.depthOfFieldDistance = 10.0;
  86166. /**
  86167. * Represents the blur intensity for the blurred part of the depth of field effect
  86168. */
  86169. _this.depthOfFieldBlurWidth = 64.0;
  86170. /**
  86171. * For motion blur, defines how much the image is blurred by the movement
  86172. */
  86173. _this.motionStrength = 1.0;
  86174. /**
  86175. * List of animations for the pipeline (IAnimatable implementation)
  86176. */
  86177. _this.animations = [];
  86178. _this._currentDepthOfFieldSource = null;
  86179. _this._hdrCurrentLuminance = 1.0;
  86180. // Getters and setters
  86181. _this._bloomEnabled = false;
  86182. _this._depthOfFieldEnabled = false;
  86183. _this._vlsEnabled = false;
  86184. _this._lensFlareEnabled = false;
  86185. _this._hdrEnabled = false;
  86186. _this._motionBlurEnabled = false;
  86187. _this._fxaaEnabled = false;
  86188. _this._motionBlurSamples = 64.0;
  86189. _this._volumetricLightStepsCount = 50.0;
  86190. _this._samples = 1;
  86191. _this._cameras = cameras || [];
  86192. // Initialize
  86193. _this._scene = scene;
  86194. _this._basePostProcess = originalPostProcess;
  86195. _this._ratio = ratio;
  86196. // Misc
  86197. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86198. // Finish
  86199. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86200. _this._buildPipeline();
  86201. return _this;
  86202. }
  86203. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  86204. /**
  86205. * @ignore
  86206. * Specifies if the bloom pipeline is enabled
  86207. */
  86208. get: function () {
  86209. return this._bloomEnabled;
  86210. },
  86211. set: function (enabled) {
  86212. if (this._bloomEnabled === enabled) {
  86213. return;
  86214. }
  86215. this._bloomEnabled = enabled;
  86216. this._buildPipeline();
  86217. },
  86218. enumerable: true,
  86219. configurable: true
  86220. });
  86221. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  86222. /**
  86223. * @ignore
  86224. * Specifies if the depth of field pipeline is enabed
  86225. */
  86226. get: function () {
  86227. return this._depthOfFieldEnabled;
  86228. },
  86229. set: function (enabled) {
  86230. if (this._depthOfFieldEnabled === enabled) {
  86231. return;
  86232. }
  86233. this._depthOfFieldEnabled = enabled;
  86234. this._buildPipeline();
  86235. },
  86236. enumerable: true,
  86237. configurable: true
  86238. });
  86239. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  86240. /**
  86241. * @ignore
  86242. * Specifies if the lens flare pipeline is enabed
  86243. */
  86244. get: function () {
  86245. return this._lensFlareEnabled;
  86246. },
  86247. set: function (enabled) {
  86248. if (this._lensFlareEnabled === enabled) {
  86249. return;
  86250. }
  86251. this._lensFlareEnabled = enabled;
  86252. this._buildPipeline();
  86253. },
  86254. enumerable: true,
  86255. configurable: true
  86256. });
  86257. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  86258. /**
  86259. * @ignore
  86260. * Specifies if the HDR pipeline is enabled
  86261. */
  86262. get: function () {
  86263. return this._hdrEnabled;
  86264. },
  86265. set: function (enabled) {
  86266. if (this._hdrEnabled === enabled) {
  86267. return;
  86268. }
  86269. this._hdrEnabled = enabled;
  86270. this._buildPipeline();
  86271. },
  86272. enumerable: true,
  86273. configurable: true
  86274. });
  86275. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  86276. /**
  86277. * @ignore
  86278. * Specifies if the volumetric lights scattering effect is enabled
  86279. */
  86280. get: function () {
  86281. return this._vlsEnabled;
  86282. },
  86283. set: function (enabled) {
  86284. if (this._vlsEnabled === enabled) {
  86285. return;
  86286. }
  86287. if (enabled) {
  86288. var geometry = this._scene.enableGeometryBufferRenderer();
  86289. if (!geometry) {
  86290. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  86291. return;
  86292. }
  86293. }
  86294. this._vlsEnabled = enabled;
  86295. this._buildPipeline();
  86296. },
  86297. enumerable: true,
  86298. configurable: true
  86299. });
  86300. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  86301. /**
  86302. * @ignore
  86303. * Specifies if the motion blur effect is enabled
  86304. */
  86305. get: function () {
  86306. return this._motionBlurEnabled;
  86307. },
  86308. set: function (enabled) {
  86309. if (this._motionBlurEnabled === enabled) {
  86310. return;
  86311. }
  86312. this._motionBlurEnabled = enabled;
  86313. this._buildPipeline();
  86314. },
  86315. enumerable: true,
  86316. configurable: true
  86317. });
  86318. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  86319. /**
  86320. * Specifies if anti-aliasing is enabled
  86321. */
  86322. get: function () {
  86323. return this._fxaaEnabled;
  86324. },
  86325. set: function (enabled) {
  86326. if (this._fxaaEnabled === enabled) {
  86327. return;
  86328. }
  86329. this._fxaaEnabled = enabled;
  86330. this._buildPipeline();
  86331. },
  86332. enumerable: true,
  86333. configurable: true
  86334. });
  86335. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  86336. /**
  86337. * Specifies the number of steps used to calculate the volumetric lights
  86338. * Typically in interval [50, 200]
  86339. */
  86340. get: function () {
  86341. return this._volumetricLightStepsCount;
  86342. },
  86343. set: function (count) {
  86344. if (this.volumetricLightPostProcess) {
  86345. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  86346. }
  86347. this._volumetricLightStepsCount = count;
  86348. },
  86349. enumerable: true,
  86350. configurable: true
  86351. });
  86352. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  86353. /**
  86354. * Specifies the number of samples used for the motion blur effect
  86355. * Typically in interval [16, 64]
  86356. */
  86357. get: function () {
  86358. return this._motionBlurSamples;
  86359. },
  86360. set: function (samples) {
  86361. if (this.motionBlurPostProcess) {
  86362. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  86363. }
  86364. this._motionBlurSamples = samples;
  86365. },
  86366. enumerable: true,
  86367. configurable: true
  86368. });
  86369. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  86370. /**
  86371. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  86372. */
  86373. get: function () {
  86374. return this._samples;
  86375. },
  86376. set: function (sampleCount) {
  86377. if (this._samples === sampleCount) {
  86378. return;
  86379. }
  86380. this._samples = sampleCount;
  86381. this._buildPipeline();
  86382. },
  86383. enumerable: true,
  86384. configurable: true
  86385. });
  86386. StandardRenderingPipeline.prototype._buildPipeline = function () {
  86387. var _this = this;
  86388. var ratio = this._ratio;
  86389. var scene = this._scene;
  86390. this._disposePostProcesses();
  86391. this._reset();
  86392. // Create pass post-process
  86393. if (!this._basePostProcess) {
  86394. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  86395. this.originalPostProcess.onApply = function (effect) {
  86396. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  86397. };
  86398. }
  86399. else {
  86400. this.originalPostProcess = this._basePostProcess;
  86401. }
  86402. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  86403. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  86404. }
  86405. this._currentDepthOfFieldSource = this.originalPostProcess;
  86406. if (this._bloomEnabled) {
  86407. // Create down sample X4 post-process
  86408. this._createDownSampleX4PostProcess(scene, ratio / 2);
  86409. // Create bright pass post-process
  86410. this._createBrightPassPostProcess(scene, ratio / 2);
  86411. // Create gaussian blur post-processes (down sampling blurs)
  86412. this._createBlurPostProcesses(scene, ratio / 4, 1);
  86413. // Create texture adder post-process
  86414. this._createTextureAdderPostProcess(scene, ratio);
  86415. // Create depth-of-field source post-process
  86416. 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);
  86417. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  86418. }
  86419. if (this._vlsEnabled) {
  86420. // Create volumetric light
  86421. this._createVolumetricLightPostProcess(scene, ratio);
  86422. // Create volumetric light final post-process
  86423. 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);
  86424. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  86425. }
  86426. if (this._lensFlareEnabled) {
  86427. // Create lens flare post-process
  86428. this._createLensFlarePostProcess(scene, ratio);
  86429. // Create depth-of-field source post-process post lens-flare and disable it now
  86430. 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);
  86431. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  86432. }
  86433. if (this._hdrEnabled) {
  86434. // Create luminance
  86435. this._createLuminancePostProcesses(scene, this._floatTextureType);
  86436. // Create HDR
  86437. this._createHdrPostProcess(scene, ratio);
  86438. // Create depth-of-field source post-process post hdr and disable it now
  86439. 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);
  86440. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  86441. }
  86442. if (this._depthOfFieldEnabled) {
  86443. // Create gaussian blur used by depth-of-field
  86444. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  86445. // Create depth-of-field post-process
  86446. this._createDepthOfFieldPostProcess(scene, ratio);
  86447. }
  86448. if (this._motionBlurEnabled) {
  86449. // Create motion blur post-process
  86450. this._createMotionBlurPostProcess(scene, ratio);
  86451. }
  86452. if (this._fxaaEnabled) {
  86453. // Create fxaa post-process
  86454. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86455. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  86456. }
  86457. if (this._cameras !== null) {
  86458. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  86459. }
  86460. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  86461. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  86462. }
  86463. };
  86464. // Down Sample X4 Post-Processs
  86465. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  86466. var _this = this;
  86467. var downSampleX4Offsets = new Array(32);
  86468. 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);
  86469. this.downSampleX4PostProcess.onApply = function (effect) {
  86470. var id = 0;
  86471. var width = _this.downSampleX4PostProcess.width;
  86472. var height = _this.downSampleX4PostProcess.height;
  86473. for (var i = -2; i < 2; i++) {
  86474. for (var j = -2; j < 2; j++) {
  86475. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  86476. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  86477. id += 2;
  86478. }
  86479. }
  86480. effect.setArray2("dsOffsets", downSampleX4Offsets);
  86481. };
  86482. // Add to pipeline
  86483. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  86484. };
  86485. // Brightpass Post-Process
  86486. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  86487. var _this = this;
  86488. var brightOffsets = new Array(8);
  86489. 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);
  86490. this.brightPassPostProcess.onApply = function (effect) {
  86491. var sU = (1.0 / _this.brightPassPostProcess.width);
  86492. var sV = (1.0 / _this.brightPassPostProcess.height);
  86493. brightOffsets[0] = -0.5 * sU;
  86494. brightOffsets[1] = 0.5 * sV;
  86495. brightOffsets[2] = 0.5 * sU;
  86496. brightOffsets[3] = 0.5 * sV;
  86497. brightOffsets[4] = -0.5 * sU;
  86498. brightOffsets[5] = -0.5 * sV;
  86499. brightOffsets[6] = 0.5 * sU;
  86500. brightOffsets[7] = -0.5 * sV;
  86501. effect.setArray2("dsOffsets", brightOffsets);
  86502. effect.setFloat("brightThreshold", _this.brightThreshold);
  86503. };
  86504. // Add to pipeline
  86505. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  86506. };
  86507. // Create blur H&V post-processes
  86508. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  86509. var _this = this;
  86510. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  86511. var engine = scene.getEngine();
  86512. 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);
  86513. 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);
  86514. blurX.onActivateObservable.add(function () {
  86515. var dw = blurX.width / engine.getRenderWidth();
  86516. blurX.kernel = _this[blurWidthKey] * dw;
  86517. });
  86518. blurY.onActivateObservable.add(function () {
  86519. var dw = blurY.height / engine.getRenderHeight();
  86520. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  86521. });
  86522. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  86523. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  86524. this.blurHPostProcesses.push(blurX);
  86525. this.blurVPostProcesses.push(blurY);
  86526. };
  86527. // Create texture adder post-process
  86528. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  86529. var _this = this;
  86530. 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);
  86531. this.textureAdderPostProcess.onApply = function (effect) {
  86532. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  86533. effect.setTexture("lensSampler", _this.lensTexture);
  86534. effect.setFloat("exposure", _this.exposure);
  86535. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  86536. };
  86537. // Add to pipeline
  86538. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  86539. };
  86540. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  86541. var _this = this;
  86542. var geometryRenderer = scene.enableGeometryBufferRenderer();
  86543. geometryRenderer.enablePosition = true;
  86544. var geometry = geometryRenderer.getGBuffer();
  86545. // Base post-process
  86546. 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));
  86547. var depthValues = BABYLON.Vector2.Zero();
  86548. this.volumetricLightPostProcess.onApply = function (effect) {
  86549. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  86550. var generator = _this.sourceLight.getShadowGenerator();
  86551. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  86552. effect.setTexture("positionSampler", geometry.textures[2]);
  86553. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  86554. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  86555. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  86556. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  86557. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  86558. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  86559. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  86560. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  86561. effect.setVector2("depthValues", depthValues);
  86562. }
  86563. };
  86564. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  86565. // Smooth
  86566. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  86567. // Merge
  86568. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  86569. this.volumetricLightMergePostProces.onApply = function (effect) {
  86570. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  86571. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  86572. };
  86573. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  86574. };
  86575. // Create luminance
  86576. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  86577. var _this = this;
  86578. // Create luminance
  86579. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  86580. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  86581. var offsets = [];
  86582. this.luminancePostProcess.onApply = function (effect) {
  86583. var sU = (1.0 / _this.luminancePostProcess.width);
  86584. var sV = (1.0 / _this.luminancePostProcess.height);
  86585. offsets[0] = -0.5 * sU;
  86586. offsets[1] = 0.5 * sV;
  86587. offsets[2] = 0.5 * sU;
  86588. offsets[3] = 0.5 * sV;
  86589. offsets[4] = -0.5 * sU;
  86590. offsets[5] = -0.5 * sV;
  86591. offsets[6] = 0.5 * sU;
  86592. offsets[7] = -0.5 * sV;
  86593. effect.setArray2("lumOffsets", offsets);
  86594. };
  86595. // Add to pipeline
  86596. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  86597. // Create down sample luminance
  86598. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  86599. var size = Math.pow(3, i);
  86600. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  86601. if (i === 0) {
  86602. defines += "#define FINAL_DOWN_SAMPLER";
  86603. }
  86604. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  86605. this.luminanceDownSamplePostProcesses.push(postProcess);
  86606. }
  86607. // Create callbacks and add effects
  86608. var lastLuminance = this.luminancePostProcess;
  86609. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  86610. var downSampleOffsets = new Array(18);
  86611. pp.onApply = function (effect) {
  86612. if (!lastLuminance) {
  86613. return;
  86614. }
  86615. var id = 0;
  86616. for (var x = -1; x < 2; x++) {
  86617. for (var y = -1; y < 2; y++) {
  86618. downSampleOffsets[id] = x / lastLuminance.width;
  86619. downSampleOffsets[id + 1] = y / lastLuminance.height;
  86620. id += 2;
  86621. }
  86622. }
  86623. effect.setArray2("dsOffsets", downSampleOffsets);
  86624. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  86625. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  86626. lastLuminance = _this.luminancePostProcess;
  86627. }
  86628. else {
  86629. lastLuminance = pp;
  86630. }
  86631. };
  86632. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  86633. pp.onAfterRender = function (effect) {
  86634. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  86635. 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);
  86636. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  86637. };
  86638. }
  86639. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  86640. });
  86641. };
  86642. // Create HDR post-process
  86643. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  86644. var _this = this;
  86645. 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);
  86646. var outputLiminance = 1;
  86647. var time = 0;
  86648. var lastTime = 0;
  86649. this.hdrPostProcess.onApply = function (effect) {
  86650. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  86651. time += scene.getEngine().getDeltaTime();
  86652. if (outputLiminance < 0) {
  86653. outputLiminance = _this._hdrCurrentLuminance;
  86654. }
  86655. else {
  86656. var dt = (lastTime - time) / 1000.0;
  86657. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  86658. outputLiminance += _this.hdrDecreaseRate * dt;
  86659. }
  86660. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  86661. outputLiminance -= _this.hdrIncreaseRate * dt;
  86662. }
  86663. else {
  86664. outputLiminance = _this._hdrCurrentLuminance;
  86665. }
  86666. }
  86667. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  86668. effect.setFloat("averageLuminance", outputLiminance);
  86669. lastTime = time;
  86670. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  86671. };
  86672. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  86673. };
  86674. // Create lens flare post-process
  86675. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  86676. var _this = this;
  86677. 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);
  86678. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  86679. this._createBlurPostProcesses(scene, ratio / 4, 2);
  86680. 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);
  86681. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  86682. var resolution = new BABYLON.Vector2(0, 0);
  86683. // Lens flare
  86684. this.lensFlarePostProcess.onApply = function (effect) {
  86685. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  86686. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  86687. effect.setFloat("strength", _this.lensFlareStrength);
  86688. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  86689. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  86690. // Shift
  86691. resolution.x = _this.lensFlarePostProcess.width;
  86692. resolution.y = _this.lensFlarePostProcess.height;
  86693. effect.setVector2("resolution", resolution);
  86694. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  86695. };
  86696. // Compose
  86697. 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);
  86698. 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);
  86699. this.lensFlareComposePostProcess.onApply = function (effect) {
  86700. if (!_this._scene.activeCamera) {
  86701. return;
  86702. }
  86703. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  86704. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  86705. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  86706. // Lens start rotation matrix
  86707. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  86708. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  86709. 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));
  86710. camRot *= 4.0;
  86711. 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);
  86712. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  86713. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  86714. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  86715. };
  86716. };
  86717. // Create depth-of-field post-process
  86718. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  86719. var _this = this;
  86720. 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);
  86721. this.depthOfFieldPostProcess.onApply = function (effect) {
  86722. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  86723. effect.setTexture("depthSampler", _this._getDepthTexture());
  86724. effect.setFloat("distance", _this.depthOfFieldDistance);
  86725. };
  86726. // Add to pipeline
  86727. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  86728. };
  86729. // Create motion blur post-process
  86730. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  86731. var _this = this;
  86732. 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);
  86733. var motionScale = 0;
  86734. var prevViewProjection = BABYLON.Matrix.Identity();
  86735. var invViewProjection = BABYLON.Matrix.Identity();
  86736. var viewProjection = BABYLON.Matrix.Identity();
  86737. var screenSize = BABYLON.Vector2.Zero();
  86738. this.motionBlurPostProcess.onApply = function (effect) {
  86739. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  86740. viewProjection.invertToRef(invViewProjection);
  86741. effect.setMatrix("inverseViewProjection", invViewProjection);
  86742. effect.setMatrix("prevViewProjection", prevViewProjection);
  86743. prevViewProjection = viewProjection;
  86744. screenSize.x = _this.motionBlurPostProcess.width;
  86745. screenSize.y = _this.motionBlurPostProcess.height;
  86746. effect.setVector2("screenSize", screenSize);
  86747. motionScale = scene.getEngine().getFps() / 60.0;
  86748. effect.setFloat("motionScale", motionScale);
  86749. effect.setFloat("motionStrength", _this.motionStrength);
  86750. effect.setTexture("depthSampler", _this._getDepthTexture());
  86751. };
  86752. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  86753. };
  86754. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  86755. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  86756. var renderer = this._scene.enableGeometryBufferRenderer();
  86757. return renderer.getGBuffer().textures[0];
  86758. }
  86759. return this._scene.enableDepthRenderer().getDepthMap();
  86760. };
  86761. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  86762. for (var i = 0; i < this._cameras.length; i++) {
  86763. var camera = this._cameras[i];
  86764. if (this.originalPostProcess) {
  86765. this.originalPostProcess.dispose(camera);
  86766. }
  86767. if (this.downSampleX4PostProcess) {
  86768. this.downSampleX4PostProcess.dispose(camera);
  86769. }
  86770. if (this.brightPassPostProcess) {
  86771. this.brightPassPostProcess.dispose(camera);
  86772. }
  86773. if (this.textureAdderPostProcess) {
  86774. this.textureAdderPostProcess.dispose(camera);
  86775. }
  86776. if (this.textureAdderFinalPostProcess) {
  86777. this.textureAdderFinalPostProcess.dispose(camera);
  86778. }
  86779. if (this.volumetricLightPostProcess) {
  86780. this.volumetricLightPostProcess.dispose(camera);
  86781. }
  86782. if (this.volumetricLightSmoothXPostProcess) {
  86783. this.volumetricLightSmoothXPostProcess.dispose(camera);
  86784. }
  86785. if (this.volumetricLightSmoothYPostProcess) {
  86786. this.volumetricLightSmoothYPostProcess.dispose(camera);
  86787. }
  86788. if (this.volumetricLightMergePostProces) {
  86789. this.volumetricLightMergePostProces.dispose(camera);
  86790. }
  86791. if (this.volumetricLightFinalPostProcess) {
  86792. this.volumetricLightFinalPostProcess.dispose(camera);
  86793. }
  86794. if (this.lensFlarePostProcess) {
  86795. this.lensFlarePostProcess.dispose(camera);
  86796. }
  86797. if (this.lensFlareComposePostProcess) {
  86798. this.lensFlareComposePostProcess.dispose(camera);
  86799. }
  86800. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  86801. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  86802. }
  86803. if (this.luminancePostProcess) {
  86804. this.luminancePostProcess.dispose(camera);
  86805. }
  86806. if (this.hdrPostProcess) {
  86807. this.hdrPostProcess.dispose(camera);
  86808. }
  86809. if (this.hdrFinalPostProcess) {
  86810. this.hdrFinalPostProcess.dispose(camera);
  86811. }
  86812. if (this.depthOfFieldPostProcess) {
  86813. this.depthOfFieldPostProcess.dispose(camera);
  86814. }
  86815. if (this.motionBlurPostProcess) {
  86816. this.motionBlurPostProcess.dispose(camera);
  86817. }
  86818. if (this.fxaaPostProcess) {
  86819. this.fxaaPostProcess.dispose(camera);
  86820. }
  86821. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  86822. this.blurHPostProcesses[j].dispose(camera);
  86823. }
  86824. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  86825. this.blurVPostProcesses[j].dispose(camera);
  86826. }
  86827. }
  86828. this.originalPostProcess = null;
  86829. this.downSampleX4PostProcess = null;
  86830. this.brightPassPostProcess = null;
  86831. this.textureAdderPostProcess = null;
  86832. this.textureAdderFinalPostProcess = null;
  86833. this.volumetricLightPostProcess = null;
  86834. this.volumetricLightSmoothXPostProcess = null;
  86835. this.volumetricLightSmoothYPostProcess = null;
  86836. this.volumetricLightMergePostProces = null;
  86837. this.volumetricLightFinalPostProcess = null;
  86838. this.lensFlarePostProcess = null;
  86839. this.lensFlareComposePostProcess = null;
  86840. this.luminancePostProcess = null;
  86841. this.hdrPostProcess = null;
  86842. this.hdrFinalPostProcess = null;
  86843. this.depthOfFieldPostProcess = null;
  86844. this.motionBlurPostProcess = null;
  86845. this.fxaaPostProcess = null;
  86846. this.luminanceDownSamplePostProcesses = [];
  86847. this.blurHPostProcesses = [];
  86848. this.blurVPostProcesses = [];
  86849. };
  86850. /**
  86851. * Dispose of the pipeline and stop all post processes
  86852. */
  86853. StandardRenderingPipeline.prototype.dispose = function () {
  86854. this._disposePostProcesses();
  86855. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  86856. _super.prototype.dispose.call(this);
  86857. };
  86858. /**
  86859. * Serialize the rendering pipeline (Used when exporting)
  86860. * @returns the serialized object
  86861. */
  86862. StandardRenderingPipeline.prototype.serialize = function () {
  86863. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  86864. if (this.sourceLight) {
  86865. serializationObject.sourceLightId = this.sourceLight.id;
  86866. }
  86867. serializationObject.customType = "StandardRenderingPipeline";
  86868. return serializationObject;
  86869. };
  86870. /**
  86871. * Parse the serialized pipeline
  86872. * @param source Source pipeline.
  86873. * @param scene The scene to load the pipeline to.
  86874. * @param rootUrl The URL of the serialized pipeline.
  86875. * @returns An instantiated pipeline from the serialized object.
  86876. */
  86877. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  86878. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  86879. if (source.sourceLightId) {
  86880. p.sourceLight = scene.getLightByID(source.sourceLightId);
  86881. }
  86882. return p;
  86883. };
  86884. /**
  86885. * Luminance steps
  86886. */
  86887. StandardRenderingPipeline.LuminanceSteps = 6;
  86888. __decorate([
  86889. BABYLON.serialize()
  86890. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  86891. __decorate([
  86892. BABYLON.serialize()
  86893. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  86894. __decorate([
  86895. BABYLON.serialize()
  86896. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  86897. __decorate([
  86898. BABYLON.serialize()
  86899. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  86900. __decorate([
  86901. BABYLON.serializeAsTexture("lensTexture")
  86902. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  86903. __decorate([
  86904. BABYLON.serialize()
  86905. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  86906. __decorate([
  86907. BABYLON.serialize()
  86908. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  86909. __decorate([
  86910. BABYLON.serialize()
  86911. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  86912. __decorate([
  86913. BABYLON.serialize()
  86914. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  86915. __decorate([
  86916. BABYLON.serialize()
  86917. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  86918. __decorate([
  86919. BABYLON.serialize()
  86920. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  86921. __decorate([
  86922. BABYLON.serializeAsTexture("lensColorTexture")
  86923. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  86924. __decorate([
  86925. BABYLON.serialize()
  86926. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  86927. __decorate([
  86928. BABYLON.serialize()
  86929. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  86930. __decorate([
  86931. BABYLON.serialize()
  86932. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  86933. __decorate([
  86934. BABYLON.serialize()
  86935. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  86936. __decorate([
  86937. BABYLON.serializeAsTexture("lensStarTexture")
  86938. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  86939. __decorate([
  86940. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  86941. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  86942. __decorate([
  86943. BABYLON.serialize()
  86944. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  86945. __decorate([
  86946. BABYLON.serialize()
  86947. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  86948. __decorate([
  86949. BABYLON.serialize()
  86950. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  86951. __decorate([
  86952. BABYLON.serialize()
  86953. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  86954. __decorate([
  86955. BABYLON.serialize()
  86956. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  86957. __decorate([
  86958. BABYLON.serialize()
  86959. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  86960. __decorate([
  86961. BABYLON.serialize()
  86962. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  86963. __decorate([
  86964. BABYLON.serialize()
  86965. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  86966. __decorate([
  86967. BABYLON.serialize()
  86968. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  86969. __decorate([
  86970. BABYLON.serialize()
  86971. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  86972. __decorate([
  86973. BABYLON.serialize()
  86974. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  86975. __decorate([
  86976. BABYLON.serialize()
  86977. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  86978. __decorate([
  86979. BABYLON.serialize()
  86980. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  86981. __decorate([
  86982. BABYLON.serialize()
  86983. ], StandardRenderingPipeline.prototype, "samples", null);
  86984. return StandardRenderingPipeline;
  86985. }(BABYLON.PostProcessRenderPipeline));
  86986. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  86987. })(BABYLON || (BABYLON = {}));
  86988. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  86989. var BABYLON;
  86990. (function (BABYLON) {
  86991. /**
  86992. * Fxaa post process
  86993. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
  86994. */
  86995. var FxaaPostProcess = /** @class */ (function (_super) {
  86996. __extends(FxaaPostProcess, _super);
  86997. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  86998. if (camera === void 0) { camera = null; }
  86999. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87000. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  87001. var defines = _this._getDefines();
  87002. _this.updateEffect(defines);
  87003. _this.onApplyObservable.add(function (effect) {
  87004. var texelSize = _this.texelSize;
  87005. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  87006. });
  87007. return _this;
  87008. }
  87009. FxaaPostProcess.prototype._getDefines = function () {
  87010. var engine = this.getEngine();
  87011. if (!engine) {
  87012. return null;
  87013. }
  87014. var glInfo = engine.getGlInfo();
  87015. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  87016. return "#define MALI 1\n";
  87017. }
  87018. return null;
  87019. };
  87020. return FxaaPostProcess;
  87021. }(BABYLON.PostProcess));
  87022. BABYLON.FxaaPostProcess = FxaaPostProcess;
  87023. })(BABYLON || (BABYLON = {}));
  87024. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  87025. var BABYLON;
  87026. (function (BABYLON) {
  87027. /**
  87028. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  87029. */
  87030. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  87031. __extends(ChromaticAberrationPostProcess, _super);
  87032. /**
  87033. * Creates a new instance ChromaticAberrationPostProcess
  87034. * @param name The name of the effect.
  87035. * @param screenWidth The width of the screen to apply the effect on.
  87036. * @param screenHeight The height of the screen to apply the effect on.
  87037. * @param options The required width/height ratio to downsize to before computing the render pass.
  87038. * @param camera The camera to apply the render pass to.
  87039. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87040. * @param engine The engine which the post process will be applied. (default: current engine)
  87041. * @param reusable If the post process can be reused on the same frame. (default: false)
  87042. * @param textureType Type of textures used when performing the post process. (default: 0)
  87043. * @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)
  87044. */
  87045. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87046. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87047. if (blockCompilation === void 0) { blockCompilation = false; }
  87048. 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;
  87049. /**
  87050. * The amount of seperation of rgb channels (default: 30)
  87051. */
  87052. _this.aberrationAmount = 30;
  87053. /**
  87054. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  87055. */
  87056. _this.radialIntensity = 0;
  87057. /**
  87058. * 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))
  87059. */
  87060. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  87061. /**
  87062. * 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))
  87063. */
  87064. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  87065. _this.onApplyObservable.add(function (effect) {
  87066. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  87067. effect.setFloat('screen_width', screenWidth);
  87068. effect.setFloat('screen_height', screenHeight);
  87069. effect.setFloat('radialIntensity', _this.radialIntensity);
  87070. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  87071. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  87072. });
  87073. return _this;
  87074. }
  87075. return ChromaticAberrationPostProcess;
  87076. }(BABYLON.PostProcess));
  87077. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  87078. })(BABYLON || (BABYLON = {}));
  87079. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  87080. var BABYLON;
  87081. (function (BABYLON) {
  87082. /**
  87083. * The GrainPostProcess adds noise to the image at mid luminance levels
  87084. */
  87085. var GrainPostProcess = /** @class */ (function (_super) {
  87086. __extends(GrainPostProcess, _super);
  87087. /**
  87088. * Creates a new instance of @see GrainPostProcess
  87089. * @param name The name of the effect.
  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 GrainPostProcess(name, 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, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87102. /**
  87103. * The intensity of the grain added (default: 30)
  87104. */
  87105. _this.intensity = 30;
  87106. /**
  87107. * If the grain should be randomized on every frame
  87108. */
  87109. _this.animated = false;
  87110. _this.onApplyObservable.add(function (effect) {
  87111. effect.setFloat('intensity', _this.intensity);
  87112. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  87113. });
  87114. return _this;
  87115. }
  87116. return GrainPostProcess;
  87117. }(BABYLON.PostProcess));
  87118. BABYLON.GrainPostProcess = GrainPostProcess;
  87119. })(BABYLON || (BABYLON = {}));
  87120. //# sourceMappingURL=babylon.grainPostProcess.js.map
  87121. var BABYLON;
  87122. (function (BABYLON) {
  87123. /**
  87124. * The SharpenPostProcess applies a sharpen kernel to every pixel
  87125. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  87126. */
  87127. var SharpenPostProcess = /** @class */ (function (_super) {
  87128. __extends(SharpenPostProcess, _super);
  87129. /**
  87130. * Creates a new instance ConvolutionPostProcess
  87131. * @param name The name of the effect.
  87132. * @param options The required width/height ratio to downsize to before computing the render pass.
  87133. * @param camera The camera to apply the render pass to.
  87134. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87135. * @param engine The engine which the post process will be applied. (default: current engine)
  87136. * @param reusable If the post process can be reused on the same frame. (default: false)
  87137. * @param textureType Type of textures used when performing the post process. (default: 0)
  87138. * @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)
  87139. */
  87140. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87141. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87142. if (blockCompilation === void 0) { blockCompilation = false; }
  87143. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87144. /**
  87145. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  87146. */
  87147. _this.colorAmount = 1.0;
  87148. /**
  87149. * How much sharpness should be applied (default: 0.3)
  87150. */
  87151. _this.edgeAmount = 0.3;
  87152. _this.onApply = function (effect) {
  87153. effect.setFloat2("screenSize", _this.width, _this.height);
  87154. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  87155. };
  87156. return _this;
  87157. }
  87158. return SharpenPostProcess;
  87159. }(BABYLON.PostProcess));
  87160. BABYLON.SharpenPostProcess = SharpenPostProcess;
  87161. })(BABYLON || (BABYLON = {}));
  87162. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  87163. var BABYLON;
  87164. (function (BABYLON) {
  87165. /**
  87166. * The Blur Post Process which blurs an image based on a kernel and direction.
  87167. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  87168. */
  87169. var BlurPostProcess = /** @class */ (function (_super) {
  87170. __extends(BlurPostProcess, _super);
  87171. /**
  87172. * Creates a new instance BlurPostProcess
  87173. * @param name The name of the effect.
  87174. * @param direction The direction in which to blur the image.
  87175. * @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.
  87176. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  87177. * @param camera The camera to apply the render pass to.
  87178. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87179. * @param engine The engine which the post process will be applied. (default: current engine)
  87180. * @param reusable If the post process can be reused on the same frame. (default: false)
  87181. * @param textureType Type of textures used when performing the post process. (default: 0)
  87182. * @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)
  87183. */
  87184. function BlurPostProcess(name,
  87185. /** The direction in which to blur the image. */
  87186. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  87187. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87188. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87189. if (defines === void 0) { defines = ""; }
  87190. if (blockCompilation === void 0) { blockCompilation = false; }
  87191. 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;
  87192. _this.direction = direction;
  87193. _this.blockCompilation = blockCompilation;
  87194. _this._packedFloat = false;
  87195. _this._staticDefines = "";
  87196. _this._staticDefines = defines;
  87197. _this.onApplyObservable.add(function (effect) {
  87198. if (_this._outputTexture) {
  87199. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  87200. }
  87201. else {
  87202. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  87203. }
  87204. });
  87205. _this.kernel = kernel;
  87206. return _this;
  87207. }
  87208. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  87209. /**
  87210. * Gets the length in pixels of the blur sample region
  87211. */
  87212. get: function () {
  87213. return this._idealKernel;
  87214. },
  87215. /**
  87216. * Sets the length in pixels of the blur sample region
  87217. */
  87218. set: function (v) {
  87219. if (this._idealKernel === v) {
  87220. return;
  87221. }
  87222. v = Math.max(v, 1);
  87223. this._idealKernel = v;
  87224. this._kernel = this._nearestBestKernel(v);
  87225. if (!this.blockCompilation) {
  87226. this._updateParameters();
  87227. }
  87228. },
  87229. enumerable: true,
  87230. configurable: true
  87231. });
  87232. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  87233. /**
  87234. * Gets wether or not the blur is unpacking/repacking floats
  87235. */
  87236. get: function () {
  87237. return this._packedFloat;
  87238. },
  87239. /**
  87240. * Sets wether or not the blur needs to unpack/repack floats
  87241. */
  87242. set: function (v) {
  87243. if (this._packedFloat === v) {
  87244. return;
  87245. }
  87246. this._packedFloat = v;
  87247. if (!this.blockCompilation) {
  87248. this._updateParameters();
  87249. }
  87250. },
  87251. enumerable: true,
  87252. configurable: true
  87253. });
  87254. /**
  87255. * Updates the effect with the current post process compile time values and recompiles the shader.
  87256. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  87257. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  87258. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  87259. * @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
  87260. * @param onCompiled Called when the shader has been compiled.
  87261. * @param onError Called if there is an error when compiling a shader.
  87262. */
  87263. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  87264. if (defines === void 0) { defines = null; }
  87265. if (uniforms === void 0) { uniforms = null; }
  87266. if (samplers === void 0) { samplers = null; }
  87267. this._updateParameters(onCompiled, onError);
  87268. };
  87269. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  87270. // Generate sampling offsets and weights
  87271. var N = this._kernel;
  87272. var centerIndex = (N - 1) / 2;
  87273. // Generate Gaussian sampling weights over kernel
  87274. var offsets = [];
  87275. var weights = [];
  87276. var totalWeight = 0;
  87277. for (var i = 0; i < N; i++) {
  87278. var u = i / (N - 1);
  87279. var w = this._gaussianWeight(u * 2.0 - 1);
  87280. offsets[i] = (i - centerIndex);
  87281. weights[i] = w;
  87282. totalWeight += w;
  87283. }
  87284. // Normalize weights
  87285. for (var i = 0; i < weights.length; i++) {
  87286. weights[i] /= totalWeight;
  87287. }
  87288. // Optimize: combine samples to take advantage of hardware linear sampling
  87289. // Walk from left to center, combining pairs (symmetrically)
  87290. var linearSamplingWeights = [];
  87291. var linearSamplingOffsets = [];
  87292. var linearSamplingMap = [];
  87293. for (var i = 0; i <= centerIndex; i += 2) {
  87294. var j = Math.min(i + 1, Math.floor(centerIndex));
  87295. var singleCenterSample = i === j;
  87296. if (singleCenterSample) {
  87297. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  87298. }
  87299. else {
  87300. var sharedCell = j === centerIndex;
  87301. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  87302. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  87303. if (offsetLinear === 0) {
  87304. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  87305. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  87306. }
  87307. else {
  87308. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  87309. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  87310. }
  87311. }
  87312. }
  87313. for (var i = 0; i < linearSamplingMap.length; i++) {
  87314. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  87315. linearSamplingWeights[i] = linearSamplingMap[i].w;
  87316. }
  87317. // Replace with optimized
  87318. offsets = linearSamplingOffsets;
  87319. weights = linearSamplingWeights;
  87320. // Generate shaders
  87321. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  87322. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  87323. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  87324. var defines = "";
  87325. defines += this._staticDefines;
  87326. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  87327. if (this._staticDefines.indexOf("DOF") != -1) {
  87328. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  87329. varyingCount--;
  87330. }
  87331. for (var i = 0; i < varyingCount; i++) {
  87332. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  87333. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  87334. }
  87335. var depCount = 0;
  87336. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  87337. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  87338. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  87339. depCount++;
  87340. }
  87341. if (this.packedFloat) {
  87342. defines += "#define PACKEDFLOAT 1";
  87343. }
  87344. this.blockCompilation = false;
  87345. _super.prototype.updateEffect.call(this, defines, null, null, {
  87346. varyingCount: varyingCount,
  87347. depCount: depCount
  87348. }, onCompiled, onError);
  87349. };
  87350. /**
  87351. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  87352. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  87353. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  87354. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  87355. * The gaps between physical kernels are compensated for in the weighting of the samples
  87356. * @param idealKernel Ideal blur kernel.
  87357. * @return Nearest best kernel.
  87358. */
  87359. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  87360. var v = Math.round(idealKernel);
  87361. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  87362. var k = _a[_i];
  87363. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  87364. return Math.max(k, 3);
  87365. }
  87366. }
  87367. return Math.max(v, 3);
  87368. };
  87369. /**
  87370. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  87371. * @param x The point on the Gaussian distribution to sample.
  87372. * @return the value of the Gaussian function at x.
  87373. */
  87374. BlurPostProcess.prototype._gaussianWeight = function (x) {
  87375. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  87376. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  87377. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  87378. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  87379. // truncated at around 1.3% of peak strength.
  87380. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  87381. var sigma = (1 / 3);
  87382. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  87383. var exponent = -((x * x) / (2.0 * sigma * sigma));
  87384. var weight = (1.0 / denominator) * Math.exp(exponent);
  87385. return weight;
  87386. };
  87387. /**
  87388. * Generates a string that can be used as a floating point number in GLSL.
  87389. * @param x Value to print.
  87390. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  87391. * @return GLSL float string.
  87392. */
  87393. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  87394. if (decimalFigures === void 0) { decimalFigures = 8; }
  87395. return x.toFixed(decimalFigures).replace(/0+$/, '');
  87396. };
  87397. return BlurPostProcess;
  87398. }(BABYLON.PostProcess));
  87399. BABYLON.BlurPostProcess = BlurPostProcess;
  87400. })(BABYLON || (BABYLON = {}));
  87401. //# sourceMappingURL=babylon.blurPostProcess.js.map
  87402. var BABYLON;
  87403. (function (BABYLON) {
  87404. /**
  87405. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  87406. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  87407. * based on samples that have a large difference in distance than the center pixel.
  87408. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  87409. */
  87410. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  87411. __extends(DepthOfFieldBlurPostProcess, _super);
  87412. /**
  87413. * Creates a new instance CircleOfConfusionPostProcess
  87414. * @param name The name of the effect.
  87415. * @param scene The scene the effect belongs to.
  87416. * @param direction The direction the blur should be applied.
  87417. * @param kernel The size of the kernel used to blur.
  87418. * @param options The required width/height ratio to downsize to before computing the render pass.
  87419. * @param camera The camera to apply the render pass to.
  87420. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  87421. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  87422. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87423. * @param engine The engine which the post process will be applied. (default: current engine)
  87424. * @param reusable If the post process can be reused on the same frame. (default: false)
  87425. * @param textureType Type of textures used when performing the post process. (default: 0)
  87426. * @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)
  87427. */
  87428. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  87429. if (imageToBlur === void 0) { imageToBlur = null; }
  87430. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87431. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87432. if (blockCompilation === void 0) { blockCompilation = false; }
  87433. 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;
  87434. _this.direction = direction;
  87435. _this.onApplyObservable.add(function (effect) {
  87436. if (imageToBlur != null) {
  87437. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  87438. }
  87439. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  87440. if (scene.activeCamera) {
  87441. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87442. }
  87443. });
  87444. return _this;
  87445. }
  87446. return DepthOfFieldBlurPostProcess;
  87447. }(BABYLON.BlurPostProcess));
  87448. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  87449. })(BABYLON || (BABYLON = {}));
  87450. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  87451. var BABYLON;
  87452. (function (BABYLON) {
  87453. /**
  87454. * Options to be set when merging outputs from the default pipeline.
  87455. */
  87456. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  87457. function DepthOfFieldMergePostProcessOptions() {
  87458. }
  87459. return DepthOfFieldMergePostProcessOptions;
  87460. }());
  87461. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  87462. /**
  87463. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  87464. */
  87465. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  87466. __extends(DepthOfFieldMergePostProcess, _super);
  87467. /**
  87468. * Creates a new instance of DepthOfFieldMergePostProcess
  87469. * @param name The name of the effect.
  87470. * @param originalFromInput Post process which's input will be used for the merge.
  87471. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  87472. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  87473. * @param options The required width/height ratio to downsize to before computing the render pass.
  87474. * @param camera The camera to apply the render pass to.
  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 DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87482. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87483. if (blockCompilation === void 0) { blockCompilation = false; }
  87484. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  87485. _this.blurSteps = blurSteps;
  87486. _this.onApplyObservable.add(function (effect) {
  87487. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  87488. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  87489. blurSteps.forEach(function (step, index) {
  87490. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  87491. });
  87492. });
  87493. if (!blockCompilation) {
  87494. _this.updateEffect();
  87495. }
  87496. return _this;
  87497. }
  87498. /**
  87499. * Updates the effect with the current post process compile time values and recompiles the shader.
  87500. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  87501. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  87502. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  87503. * @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
  87504. * @param onCompiled Called when the shader has been compiled.
  87505. * @param onError Called if there is an error when compiling a shader.
  87506. */
  87507. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  87508. if (defines === void 0) { defines = null; }
  87509. if (uniforms === void 0) { uniforms = null; }
  87510. if (samplers === void 0) { samplers = null; }
  87511. if (!defines) {
  87512. defines = "";
  87513. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  87514. }
  87515. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  87516. };
  87517. return DepthOfFieldMergePostProcess;
  87518. }(BABYLON.PostProcess));
  87519. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  87520. })(BABYLON || (BABYLON = {}));
  87521. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  87522. var BABYLON;
  87523. (function (BABYLON) {
  87524. /**
  87525. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  87526. */
  87527. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  87528. __extends(CircleOfConfusionPostProcess, _super);
  87529. /**
  87530. * Creates a new instance CircleOfConfusionPostProcess
  87531. * @param name The name of the effect.
  87532. * @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.
  87533. * @param options The required width/height ratio to downsize to before computing the render pass.
  87534. * @param camera The camera to apply the render pass to.
  87535. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87536. * @param engine The engine which the post process will be applied. (default: current engine)
  87537. * @param reusable If the post process can be reused on the same frame. (default: false)
  87538. * @param textureType Type of textures used when performing the post process. (default: 0)
  87539. * @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)
  87540. */
  87541. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87542. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87543. if (blockCompilation === void 0) { blockCompilation = false; }
  87544. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87545. /**
  87546. * 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.
  87547. */
  87548. _this.lensSize = 50;
  87549. /**
  87550. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  87551. */
  87552. _this.fStop = 1.4;
  87553. /**
  87554. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  87555. */
  87556. _this.focusDistance = 2000;
  87557. /**
  87558. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  87559. */
  87560. _this.focalLength = 50;
  87561. _this._depthTexture = null;
  87562. _this._depthTexture = depthTexture;
  87563. _this.onApplyObservable.add(function (effect) {
  87564. if (!_this._depthTexture) {
  87565. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  87566. return;
  87567. }
  87568. effect.setTexture("depthSampler", _this._depthTexture);
  87569. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  87570. var aperture = _this.lensSize / _this.fStop;
  87571. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  87572. effect.setFloat('focusDistance', _this.focusDistance);
  87573. effect.setFloat('cocPrecalculation', cocPrecalculation);
  87574. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  87575. });
  87576. return _this;
  87577. }
  87578. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  87579. /**
  87580. * 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.
  87581. */
  87582. set: function (value) {
  87583. this._depthTexture = value;
  87584. },
  87585. enumerable: true,
  87586. configurable: true
  87587. });
  87588. return CircleOfConfusionPostProcess;
  87589. }(BABYLON.PostProcess));
  87590. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  87591. })(BABYLON || (BABYLON = {}));
  87592. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  87593. var BABYLON;
  87594. (function (BABYLON) {
  87595. /**
  87596. * Specifies the level of max blur that should be applied when using the depth of field effect
  87597. */
  87598. var DepthOfFieldEffectBlurLevel;
  87599. (function (DepthOfFieldEffectBlurLevel) {
  87600. /**
  87601. * Subtle blur
  87602. */
  87603. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  87604. /**
  87605. * Medium blur
  87606. */
  87607. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  87608. /**
  87609. * Large blur
  87610. */
  87611. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  87612. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  87613. /**
  87614. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  87615. */
  87616. var DepthOfFieldEffect = /** @class */ (function (_super) {
  87617. __extends(DepthOfFieldEffect, _super);
  87618. /**
  87619. * Creates a new instance DepthOfFieldEffect
  87620. * @param scene The scene the effect belongs to.
  87621. * @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.
  87622. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  87623. * @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)
  87624. */
  87625. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  87626. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  87627. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  87628. if (blockCompilation === void 0) { blockCompilation = false; }
  87629. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  87630. return _this._effects;
  87631. }, true) || this;
  87632. /**
  87633. * @hidden Internal post processes in depth of field effect
  87634. */
  87635. _this._effects = [];
  87636. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  87637. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87638. // 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)
  87639. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  87640. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  87641. _this._depthOfFieldBlurY = [];
  87642. _this._depthOfFieldBlurX = [];
  87643. var blurCount = 1;
  87644. var kernelSize = 15;
  87645. switch (blurLevel) {
  87646. case DepthOfFieldEffectBlurLevel.High: {
  87647. blurCount = 3;
  87648. kernelSize = 51;
  87649. break;
  87650. }
  87651. case DepthOfFieldEffectBlurLevel.Medium: {
  87652. blurCount = 2;
  87653. kernelSize = 31;
  87654. break;
  87655. }
  87656. default: {
  87657. kernelSize = 15;
  87658. blurCount = 1;
  87659. break;
  87660. }
  87661. }
  87662. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  87663. var ratio = 1.0;
  87664. for (var i = 0; i < blurCount; i++) {
  87665. 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);
  87666. blurY.autoClear = false;
  87667. ratio = 0.75 / Math.pow(2, i);
  87668. 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);
  87669. blurX.autoClear = false;
  87670. _this._depthOfFieldBlurY.push(blurY);
  87671. _this._depthOfFieldBlurX.push(blurX);
  87672. }
  87673. // Set all post processes on the effect.
  87674. _this._effects = [_this._circleOfConfusion];
  87675. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  87676. _this._effects.push(_this._depthOfFieldBlurY[i]);
  87677. _this._effects.push(_this._depthOfFieldBlurX[i]);
  87678. }
  87679. // Merge blurred images with original image based on circleOfConfusion
  87680. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87681. _this._dofMerge.autoClear = false;
  87682. _this._effects.push(_this._dofMerge);
  87683. return _this;
  87684. }
  87685. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  87686. get: function () {
  87687. return this._circleOfConfusion.focalLength;
  87688. },
  87689. /**
  87690. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  87691. */
  87692. set: function (value) {
  87693. this._circleOfConfusion.focalLength = value;
  87694. },
  87695. enumerable: true,
  87696. configurable: true
  87697. });
  87698. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  87699. get: function () {
  87700. return this._circleOfConfusion.fStop;
  87701. },
  87702. /**
  87703. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  87704. */
  87705. set: function (value) {
  87706. this._circleOfConfusion.fStop = value;
  87707. },
  87708. enumerable: true,
  87709. configurable: true
  87710. });
  87711. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  87712. get: function () {
  87713. return this._circleOfConfusion.focusDistance;
  87714. },
  87715. /**
  87716. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  87717. */
  87718. set: function (value) {
  87719. this._circleOfConfusion.focusDistance = value;
  87720. },
  87721. enumerable: true,
  87722. configurable: true
  87723. });
  87724. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  87725. get: function () {
  87726. return this._circleOfConfusion.lensSize;
  87727. },
  87728. /**
  87729. * 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.
  87730. */
  87731. set: function (value) {
  87732. this._circleOfConfusion.lensSize = value;
  87733. },
  87734. enumerable: true,
  87735. configurable: true
  87736. });
  87737. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  87738. /**
  87739. * 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.
  87740. */
  87741. set: function (value) {
  87742. this._circleOfConfusion.depthTexture = value;
  87743. },
  87744. enumerable: true,
  87745. configurable: true
  87746. });
  87747. /**
  87748. * Disposes each of the internal effects for a given camera.
  87749. * @param camera The camera to dispose the effect on.
  87750. */
  87751. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  87752. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87753. this._effects[effectIndex].dispose(camera);
  87754. }
  87755. };
  87756. /**
  87757. * @hidden Internal
  87758. */
  87759. DepthOfFieldEffect.prototype._updateEffects = function () {
  87760. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87761. this._effects[effectIndex].updateEffect();
  87762. }
  87763. };
  87764. /**
  87765. * Internal
  87766. * @returns if all the contained post processes are ready.
  87767. * @hidden
  87768. */
  87769. DepthOfFieldEffect.prototype._isReady = function () {
  87770. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87771. if (!this._effects[effectIndex].isReady()) {
  87772. return false;
  87773. }
  87774. }
  87775. return true;
  87776. };
  87777. return DepthOfFieldEffect;
  87778. }(BABYLON.PostProcessRenderEffect));
  87779. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  87780. })(BABYLON || (BABYLON = {}));
  87781. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  87782. var BABYLON;
  87783. (function (BABYLON) {
  87784. /**
  87785. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  87786. */
  87787. var BloomMergePostProcess = /** @class */ (function (_super) {
  87788. __extends(BloomMergePostProcess, _super);
  87789. /**
  87790. * Creates a new instance of @see BloomMergePostProcess
  87791. * @param name The name of the effect.
  87792. * @param originalFromInput Post process which's input will be used for the merge.
  87793. * @param blurred Blurred highlights post process which's output will be used.
  87794. * @param weight Weight of the bloom to be added to the original input.
  87795. * @param options The required width/height ratio to downsize to before computing the render pass.
  87796. * @param camera The camera to apply the render pass to.
  87797. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87798. * @param engine The engine which the post process will be applied. (default: current engine)
  87799. * @param reusable If the post process can be reused on the same frame. (default: false)
  87800. * @param textureType Type of textures used when performing the post process. (default: 0)
  87801. * @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)
  87802. */
  87803. function BloomMergePostProcess(name, originalFromInput, blurred,
  87804. /** Weight of the bloom to be added to the original input. */
  87805. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87806. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87807. if (blockCompilation === void 0) { blockCompilation = false; }
  87808. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  87809. _this.weight = weight;
  87810. _this.onApplyObservable.add(function (effect) {
  87811. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  87812. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  87813. effect.setFloat("bloomWeight", _this.weight);
  87814. });
  87815. if (!blockCompilation) {
  87816. _this.updateEffect();
  87817. }
  87818. return _this;
  87819. }
  87820. return BloomMergePostProcess;
  87821. }(BABYLON.PostProcess));
  87822. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  87823. })(BABYLON || (BABYLON = {}));
  87824. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  87825. var BABYLON;
  87826. (function (BABYLON) {
  87827. /**
  87828. * 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.
  87829. */
  87830. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  87831. __extends(ExtractHighlightsPostProcess, _super);
  87832. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87833. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87834. if (blockCompilation === void 0) { blockCompilation = false; }
  87835. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87836. /**
  87837. * The luminance threshold, pixels below this value will be set to black.
  87838. */
  87839. _this.threshold = 0.9;
  87840. /** @hidden */
  87841. _this._exposure = 1;
  87842. /**
  87843. * Post process which has the input texture to be used when performing highlight extraction
  87844. * @hidden
  87845. */
  87846. _this._inputPostProcess = null;
  87847. _this.onApplyObservable.add(function (effect) {
  87848. if (_this._inputPostProcess) {
  87849. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  87850. }
  87851. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  87852. effect.setFloat('exposure', _this._exposure);
  87853. });
  87854. return _this;
  87855. }
  87856. return ExtractHighlightsPostProcess;
  87857. }(BABYLON.PostProcess));
  87858. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  87859. })(BABYLON || (BABYLON = {}));
  87860. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  87861. var BABYLON;
  87862. (function (BABYLON) {
  87863. /**
  87864. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  87865. */
  87866. var BloomEffect = /** @class */ (function (_super) {
  87867. __extends(BloomEffect, _super);
  87868. /**
  87869. * Creates a new instance of @see BloomEffect
  87870. * @param scene The scene the effect belongs to.
  87871. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  87872. * @param bloomKernel The size of the kernel to be used when applying the blur.
  87873. * @param bloomWeight The the strength of bloom.
  87874. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  87875. * @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)
  87876. */
  87877. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  87878. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  87879. if (blockCompilation === void 0) { blockCompilation = false; }
  87880. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  87881. return _this._effects;
  87882. }, true) || this;
  87883. _this.bloomScale = bloomScale;
  87884. /**
  87885. * @hidden Internal
  87886. */
  87887. _this._effects = [];
  87888. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87889. _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);
  87890. _this._blurX.alwaysForcePOT = true;
  87891. _this._blurX.autoClear = false;
  87892. _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);
  87893. _this._blurY.alwaysForcePOT = true;
  87894. _this._blurY.autoClear = false;
  87895. _this.kernel = bloomKernel;
  87896. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  87897. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87898. _this._merge.autoClear = false;
  87899. _this._effects.push(_this._merge);
  87900. return _this;
  87901. }
  87902. Object.defineProperty(BloomEffect.prototype, "threshold", {
  87903. /**
  87904. * The luminance threshold to find bright areas of the image to bloom.
  87905. */
  87906. get: function () {
  87907. return this._downscale.threshold;
  87908. },
  87909. set: function (value) {
  87910. this._downscale.threshold = value;
  87911. },
  87912. enumerable: true,
  87913. configurable: true
  87914. });
  87915. Object.defineProperty(BloomEffect.prototype, "weight", {
  87916. /**
  87917. * The strength of the bloom.
  87918. */
  87919. get: function () {
  87920. return this._merge.weight;
  87921. },
  87922. set: function (value) {
  87923. this._merge.weight = value;
  87924. },
  87925. enumerable: true,
  87926. configurable: true
  87927. });
  87928. Object.defineProperty(BloomEffect.prototype, "kernel", {
  87929. /**
  87930. * Specifies the size of the bloom blur kernel, relative to the final output size
  87931. */
  87932. get: function () {
  87933. return this._blurX.kernel / this.bloomScale;
  87934. },
  87935. set: function (value) {
  87936. this._blurX.kernel = value * this.bloomScale;
  87937. this._blurY.kernel = value * this.bloomScale;
  87938. },
  87939. enumerable: true,
  87940. configurable: true
  87941. });
  87942. /**
  87943. * Disposes each of the internal effects for a given camera.
  87944. * @param camera The camera to dispose the effect on.
  87945. */
  87946. BloomEffect.prototype.disposeEffects = function (camera) {
  87947. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87948. this._effects[effectIndex].dispose(camera);
  87949. }
  87950. };
  87951. /**
  87952. * @hidden Internal
  87953. */
  87954. BloomEffect.prototype._updateEffects = function () {
  87955. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87956. this._effects[effectIndex].updateEffect();
  87957. }
  87958. };
  87959. /**
  87960. * Internal
  87961. * @returns if all the contained post processes are ready.
  87962. * @hidden
  87963. */
  87964. BloomEffect.prototype._isReady = function () {
  87965. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87966. if (!this._effects[effectIndex].isReady()) {
  87967. return false;
  87968. }
  87969. }
  87970. return true;
  87971. };
  87972. return BloomEffect;
  87973. }(BABYLON.PostProcessRenderEffect));
  87974. BABYLON.BloomEffect = BloomEffect;
  87975. })(BABYLON || (BABYLON = {}));
  87976. //# sourceMappingURL=babylon.bloomEffect.js.map
  87977. var BABYLON;
  87978. (function (BABYLON) {
  87979. /**
  87980. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  87981. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  87982. */
  87983. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  87984. __extends(DefaultRenderingPipeline, _super);
  87985. /**
  87986. * @constructor
  87987. * @param name - The rendering pipeline name (default: "")
  87988. * @param hdr - If high dynamic range textures should be used (default: true)
  87989. * @param scene - The scene linked to this pipeline (default: the last created scene)
  87990. * @param cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  87991. * @param automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  87992. */
  87993. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  87994. if (name === void 0) { name = ""; }
  87995. if (hdr === void 0) { hdr = true; }
  87996. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  87997. if (automaticBuild === void 0) { automaticBuild = true; }
  87998. var _this = _super.call(this, scene.getEngine(), name) || this;
  87999. _this._camerasToBeAttached = [];
  88000. /**
  88001. * ID of the sharpen post process,
  88002. */
  88003. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  88004. /**
  88005. * @ignore
  88006. * ID of the image processing post process;
  88007. */
  88008. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  88009. /**
  88010. * @ignore
  88011. * ID of the Fast Approximate Anti-Aliasing post process;
  88012. */
  88013. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  88014. /**
  88015. * ID of the chromatic aberration post process,
  88016. */
  88017. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  88018. /**
  88019. * ID of the grain post process
  88020. */
  88021. _this.GrainPostProcessId = "GrainPostProcessEffect";
  88022. /**
  88023. * Glow post process which adds a glow to emmisive areas of the image
  88024. */
  88025. _this._glowLayer = null;
  88026. /**
  88027. * Animations which can be used to tweak settings over a period of time
  88028. */
  88029. _this.animations = [];
  88030. _this._imageProcessingConfigurationObserver = null;
  88031. // Values
  88032. _this._sharpenEnabled = false;
  88033. _this._bloomEnabled = false;
  88034. _this._depthOfFieldEnabled = false;
  88035. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  88036. _this._fxaaEnabled = false;
  88037. _this._imageProcessingEnabled = true;
  88038. _this._bloomScale = 0.5;
  88039. _this._chromaticAberrationEnabled = false;
  88040. _this._grainEnabled = false;
  88041. _this._buildAllowed = true;
  88042. _this._resizeObserver = null;
  88043. _this._hardwareScaleLevel = 1.0;
  88044. _this._bloomKernel = 64;
  88045. /**
  88046. * Specifies the weight of the bloom in the final rendering
  88047. */
  88048. _this._bloomWeight = 0.15;
  88049. /**
  88050. * Specifies the luma threshold for the area that will be blurred by the bloom
  88051. */
  88052. _this._bloomThreshold = 0.9;
  88053. _this._samples = 1;
  88054. _this._hasCleared = false;
  88055. _this._prevPostProcess = null;
  88056. _this._prevPrevPostProcess = null;
  88057. _this._depthOfFieldSceneObserver = null;
  88058. _this._cameras = cameras || scene.cameras;
  88059. _this._cameras = _this._cameras.slice();
  88060. _this._camerasToBeAttached = _this._cameras.slice();
  88061. _this._buildAllowed = automaticBuild;
  88062. // Initialize
  88063. _this._scene = scene;
  88064. var caps = _this._scene.getEngine().getCaps();
  88065. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  88066. // Misc
  88067. if (_this._hdr) {
  88068. if (caps.textureHalfFloatRender) {
  88069. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88070. }
  88071. else if (caps.textureFloatRender) {
  88072. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88073. }
  88074. }
  88075. else {
  88076. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88077. }
  88078. // Attach
  88079. scene.postProcessRenderPipelineManager.addPipeline(_this);
  88080. var engine = _this._scene.getEngine();
  88081. // Create post processes before hand so they can be modified before enabled.
  88082. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  88083. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88084. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  88085. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  88086. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  88087. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88088. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  88089. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88090. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  88091. _this._resizeObserver = engine.onResizeObservable.add(function () {
  88092. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  88093. _this.bloomKernel = _this.bloomKernel;
  88094. });
  88095. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  88096. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  88097. });
  88098. _this._buildPipeline();
  88099. return _this;
  88100. }
  88101. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  88102. get: function () {
  88103. return this._sharpenEnabled;
  88104. },
  88105. /**
  88106. * Enable or disable the sharpen process from the pipeline
  88107. */
  88108. set: function (enabled) {
  88109. if (this._sharpenEnabled === enabled) {
  88110. return;
  88111. }
  88112. this._sharpenEnabled = enabled;
  88113. this._buildPipeline();
  88114. },
  88115. enumerable: true,
  88116. configurable: true
  88117. });
  88118. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  88119. /**
  88120. * Specifies the size of the bloom blur kernel, relative to the final output size
  88121. */
  88122. get: function () {
  88123. return this._bloomKernel;
  88124. },
  88125. set: function (value) {
  88126. this._bloomKernel = value;
  88127. this.bloom.kernel = value / this._hardwareScaleLevel;
  88128. },
  88129. enumerable: true,
  88130. configurable: true
  88131. });
  88132. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  88133. get: function () {
  88134. return this._bloomWeight;
  88135. },
  88136. /**
  88137. * The strength of the bloom.
  88138. */
  88139. set: function (value) {
  88140. if (this._bloomWeight === value) {
  88141. return;
  88142. }
  88143. this.bloom.weight = value;
  88144. this._bloomWeight = value;
  88145. },
  88146. enumerable: true,
  88147. configurable: true
  88148. });
  88149. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  88150. get: function () {
  88151. return this._bloomThreshold;
  88152. },
  88153. /**
  88154. * The strength of the bloom.
  88155. */
  88156. set: function (value) {
  88157. if (this._bloomThreshold === value) {
  88158. return;
  88159. }
  88160. this.bloom.threshold = value;
  88161. this._bloomThreshold = value;
  88162. },
  88163. enumerable: true,
  88164. configurable: true
  88165. });
  88166. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  88167. get: function () {
  88168. return this._bloomScale;
  88169. },
  88170. /**
  88171. * The scale of the bloom, lower value will provide better performance.
  88172. */
  88173. set: function (value) {
  88174. if (this._bloomScale === value) {
  88175. return;
  88176. }
  88177. this._bloomScale = value;
  88178. // recreate bloom and dispose old as this setting is not dynamic
  88179. this._rebuildBloom();
  88180. this._buildPipeline();
  88181. },
  88182. enumerable: true,
  88183. configurable: true
  88184. });
  88185. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  88186. get: function () {
  88187. return this._bloomEnabled;
  88188. },
  88189. /**
  88190. * Enable or disable the bloom from the pipeline
  88191. */
  88192. set: function (enabled) {
  88193. if (this._bloomEnabled === enabled) {
  88194. return;
  88195. }
  88196. this._bloomEnabled = enabled;
  88197. this._buildPipeline();
  88198. },
  88199. enumerable: true,
  88200. configurable: true
  88201. });
  88202. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  88203. // recreate bloom and dispose old as this setting is not dynamic
  88204. var oldBloom = this.bloom;
  88205. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  88206. this.bloom.threshold = oldBloom.threshold;
  88207. for (var i = 0; i < this._cameras.length; i++) {
  88208. oldBloom.disposeEffects(this._cameras[i]);
  88209. }
  88210. };
  88211. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  88212. /**
  88213. * If the depth of field is enabled.
  88214. */
  88215. get: function () {
  88216. return this._depthOfFieldEnabled;
  88217. },
  88218. set: function (enabled) {
  88219. if (this._depthOfFieldEnabled === enabled) {
  88220. return;
  88221. }
  88222. this._depthOfFieldEnabled = enabled;
  88223. this._buildPipeline();
  88224. },
  88225. enumerable: true,
  88226. configurable: true
  88227. });
  88228. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  88229. /**
  88230. * Blur level of the depth of field effect. (Higher blur will effect performance)
  88231. */
  88232. get: function () {
  88233. return this._depthOfFieldBlurLevel;
  88234. },
  88235. set: function (value) {
  88236. if (this._depthOfFieldBlurLevel === value) {
  88237. return;
  88238. }
  88239. this._depthOfFieldBlurLevel = value;
  88240. // recreate dof and dispose old as this setting is not dynamic
  88241. var oldDof = this.depthOfField;
  88242. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  88243. this.depthOfField.focalLength = oldDof.focalLength;
  88244. this.depthOfField.focusDistance = oldDof.focusDistance;
  88245. this.depthOfField.fStop = oldDof.fStop;
  88246. this.depthOfField.lensSize = oldDof.lensSize;
  88247. for (var i = 0; i < this._cameras.length; i++) {
  88248. oldDof.disposeEffects(this._cameras[i]);
  88249. }
  88250. this._buildPipeline();
  88251. },
  88252. enumerable: true,
  88253. configurable: true
  88254. });
  88255. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  88256. get: function () {
  88257. return this._fxaaEnabled;
  88258. },
  88259. /**
  88260. * If the anti aliasing is enabled.
  88261. */
  88262. set: function (enabled) {
  88263. if (this._fxaaEnabled === enabled) {
  88264. return;
  88265. }
  88266. this._fxaaEnabled = enabled;
  88267. this._buildPipeline();
  88268. },
  88269. enumerable: true,
  88270. configurable: true
  88271. });
  88272. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  88273. get: function () {
  88274. return this._samples;
  88275. },
  88276. /**
  88277. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  88278. */
  88279. set: function (sampleCount) {
  88280. if (this._samples === sampleCount) {
  88281. return;
  88282. }
  88283. this._samples = sampleCount;
  88284. this._buildPipeline();
  88285. },
  88286. enumerable: true,
  88287. configurable: true
  88288. });
  88289. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  88290. get: function () {
  88291. return this._imageProcessingEnabled;
  88292. },
  88293. /**
  88294. * If image processing is enabled.
  88295. */
  88296. set: function (enabled) {
  88297. if (this._imageProcessingEnabled === enabled) {
  88298. return;
  88299. }
  88300. this._imageProcessingEnabled = enabled;
  88301. this._buildPipeline();
  88302. },
  88303. enumerable: true,
  88304. configurable: true
  88305. });
  88306. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  88307. get: function () {
  88308. return this._glowLayer == null;
  88309. },
  88310. /**
  88311. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  88312. */
  88313. set: function (enabled) {
  88314. if (enabled && !this._glowLayer) {
  88315. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  88316. }
  88317. else if (!enabled && this._glowLayer) {
  88318. this._glowLayer.dispose();
  88319. this._glowLayer = null;
  88320. }
  88321. },
  88322. enumerable: true,
  88323. configurable: true
  88324. });
  88325. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  88326. get: function () {
  88327. return this._chromaticAberrationEnabled;
  88328. },
  88329. /**
  88330. * Enable or disable the chromaticAberration process from the pipeline
  88331. */
  88332. set: function (enabled) {
  88333. if (this._chromaticAberrationEnabled === enabled) {
  88334. return;
  88335. }
  88336. this._chromaticAberrationEnabled = enabled;
  88337. this._buildPipeline();
  88338. },
  88339. enumerable: true,
  88340. configurable: true
  88341. });
  88342. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  88343. get: function () {
  88344. return this._grainEnabled;
  88345. },
  88346. /**
  88347. * Enable or disable the grain process from the pipeline
  88348. */
  88349. set: function (enabled) {
  88350. if (this._grainEnabled === enabled) {
  88351. return;
  88352. }
  88353. this._grainEnabled = enabled;
  88354. this._buildPipeline();
  88355. },
  88356. enumerable: true,
  88357. configurable: true
  88358. });
  88359. /**
  88360. * Force the compilation of the entire pipeline.
  88361. */
  88362. DefaultRenderingPipeline.prototype.prepare = function () {
  88363. var previousState = this._buildAllowed;
  88364. this._buildAllowed = true;
  88365. this._buildPipeline();
  88366. this._buildAllowed = previousState;
  88367. };
  88368. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  88369. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  88370. if (this._hasCleared) {
  88371. postProcess.autoClear = false;
  88372. }
  88373. else {
  88374. postProcess.autoClear = true;
  88375. this._scene.autoClear = false;
  88376. this._hasCleared = true;
  88377. }
  88378. if (!skipTextureSharing) {
  88379. if (this._prevPrevPostProcess) {
  88380. postProcess.shareOutputWith(this._prevPrevPostProcess);
  88381. }
  88382. else {
  88383. postProcess.useOwnOutput();
  88384. }
  88385. if (this._prevPostProcess) {
  88386. this._prevPrevPostProcess = this._prevPostProcess;
  88387. }
  88388. this._prevPostProcess = postProcess;
  88389. }
  88390. };
  88391. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  88392. var _this = this;
  88393. if (!this._buildAllowed) {
  88394. return;
  88395. }
  88396. this._scene.autoClear = true;
  88397. var engine = this._scene.getEngine();
  88398. this._disposePostProcesses();
  88399. if (this._cameras !== null) {
  88400. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  88401. // get back cameras to be used to reattach pipeline
  88402. this._cameras = this._camerasToBeAttached.slice();
  88403. }
  88404. this._reset();
  88405. this._prevPostProcess = null;
  88406. this._prevPrevPostProcess = null;
  88407. this._hasCleared = false;
  88408. if (this.depthOfFieldEnabled) {
  88409. // Multi camera suport
  88410. if (this._cameras.length > 1) {
  88411. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  88412. var camera = _a[_i];
  88413. var depthRenderer = this._scene.enableDepthRenderer(camera);
  88414. depthRenderer.useOnlyInActiveCamera = true;
  88415. }
  88416. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  88417. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  88418. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  88419. }
  88420. });
  88421. }
  88422. else {
  88423. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88424. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  88425. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  88426. }
  88427. if (!this.depthOfField._isReady()) {
  88428. this.depthOfField._updateEffects();
  88429. }
  88430. this.addEffect(this.depthOfField);
  88431. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  88432. }
  88433. else {
  88434. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88435. }
  88436. if (this.bloomEnabled) {
  88437. if (!this.bloom._isReady()) {
  88438. this.bloom._updateEffects();
  88439. }
  88440. this.addEffect(this.bloom);
  88441. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  88442. }
  88443. if (this._imageProcessingEnabled) {
  88444. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  88445. if (this._hdr) {
  88446. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  88447. this._setAutoClearAndTextureSharing(this.imageProcessing);
  88448. }
  88449. else {
  88450. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  88451. }
  88452. }
  88453. if (this.sharpenEnabled) {
  88454. if (!this.sharpen.isReady()) {
  88455. this.sharpen.updateEffect();
  88456. }
  88457. this.addEffect(this._sharpenEffect);
  88458. this._setAutoClearAndTextureSharing(this.sharpen);
  88459. }
  88460. if (this.grainEnabled) {
  88461. if (!this.grain.isReady()) {
  88462. this.grain.updateEffect();
  88463. }
  88464. this.addEffect(this._grainEffect);
  88465. this._setAutoClearAndTextureSharing(this.grain);
  88466. }
  88467. if (this.chromaticAberrationEnabled) {
  88468. if (!this.chromaticAberration.isReady()) {
  88469. this.chromaticAberration.updateEffect();
  88470. }
  88471. this.addEffect(this._chromaticAberrationEffect);
  88472. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  88473. }
  88474. if (this.fxaaEnabled) {
  88475. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  88476. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  88477. this._setAutoClearAndTextureSharing(this.fxaa, true);
  88478. }
  88479. if (this._cameras !== null) {
  88480. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  88481. }
  88482. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  88483. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  88484. }
  88485. };
  88486. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  88487. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  88488. for (var i = 0; i < this._cameras.length; i++) {
  88489. var camera = this._cameras[i];
  88490. if (this.imageProcessing) {
  88491. this.imageProcessing.dispose(camera);
  88492. }
  88493. if (this.fxaa) {
  88494. this.fxaa.dispose(camera);
  88495. }
  88496. // These are created in the constructor and should not be disposed on every pipeline change
  88497. if (disposeNonRecreated) {
  88498. if (this.sharpen) {
  88499. this.sharpen.dispose(camera);
  88500. }
  88501. if (this.depthOfField) {
  88502. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88503. this.depthOfField.disposeEffects(camera);
  88504. }
  88505. if (this.bloom) {
  88506. this.bloom.disposeEffects(camera);
  88507. }
  88508. if (this.chromaticAberration) {
  88509. this.chromaticAberration.dispose(camera);
  88510. }
  88511. if (this.grain) {
  88512. this.grain.dispose(camera);
  88513. }
  88514. if (this._glowLayer) {
  88515. this._glowLayer.dispose();
  88516. }
  88517. }
  88518. }
  88519. this.imageProcessing = null;
  88520. this.fxaa = null;
  88521. if (disposeNonRecreated) {
  88522. this.sharpen = null;
  88523. this._sharpenEffect = null;
  88524. this.depthOfField = null;
  88525. this.bloom = null;
  88526. this.chromaticAberration = null;
  88527. this._chromaticAberrationEffect = null;
  88528. this.grain = null;
  88529. this._grainEffect = null;
  88530. this._glowLayer = null;
  88531. }
  88532. };
  88533. /**
  88534. * Adds a camera to the pipeline
  88535. * @param camera the camera to be added
  88536. */
  88537. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  88538. this._camerasToBeAttached.push(camera);
  88539. this._buildPipeline();
  88540. };
  88541. /**
  88542. * Removes a camera from the pipeline
  88543. * @param camera the camera to remove
  88544. */
  88545. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  88546. var index = this._camerasToBeAttached.indexOf(camera);
  88547. this._camerasToBeAttached.splice(index, 1);
  88548. this._buildPipeline();
  88549. };
  88550. /**
  88551. * Dispose of the pipeline and stop all post processes
  88552. */
  88553. DefaultRenderingPipeline.prototype.dispose = function () {
  88554. this._disposePostProcesses(true);
  88555. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  88556. this._scene.autoClear = true;
  88557. if (this._resizeObserver) {
  88558. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  88559. this._resizeObserver = null;
  88560. }
  88561. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  88562. _super.prototype.dispose.call(this);
  88563. };
  88564. /**
  88565. * Serialize the rendering pipeline (Used when exporting)
  88566. * @returns the serialized object
  88567. */
  88568. DefaultRenderingPipeline.prototype.serialize = function () {
  88569. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88570. serializationObject.customType = "DefaultRenderingPipeline";
  88571. return serializationObject;
  88572. };
  88573. /**
  88574. * Parse the serialized pipeline
  88575. * @param source Source pipeline.
  88576. * @param scene The scene to load the pipeline to.
  88577. * @param rootUrl The URL of the serialized pipeline.
  88578. * @returns An instantiated pipeline from the serialized object.
  88579. */
  88580. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  88581. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  88582. };
  88583. __decorate([
  88584. BABYLON.serialize()
  88585. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  88586. __decorate([
  88587. BABYLON.serialize()
  88588. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  88589. __decorate([
  88590. BABYLON.serialize()
  88591. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  88592. __decorate([
  88593. BABYLON.serialize()
  88594. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  88595. __decorate([
  88596. BABYLON.serialize()
  88597. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  88598. __decorate([
  88599. BABYLON.serialize()
  88600. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  88601. __decorate([
  88602. BABYLON.serialize()
  88603. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  88604. __decorate([
  88605. BABYLON.serialize()
  88606. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  88607. __decorate([
  88608. BABYLON.serialize()
  88609. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  88610. __decorate([
  88611. BABYLON.serialize()
  88612. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  88613. __decorate([
  88614. BABYLON.serialize()
  88615. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  88616. __decorate([
  88617. BABYLON.serialize()
  88618. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  88619. __decorate([
  88620. BABYLON.serialize()
  88621. ], DefaultRenderingPipeline.prototype, "samples", null);
  88622. __decorate([
  88623. BABYLON.serialize()
  88624. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  88625. __decorate([
  88626. BABYLON.serialize()
  88627. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  88628. __decorate([
  88629. BABYLON.serialize()
  88630. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  88631. __decorate([
  88632. BABYLON.serialize()
  88633. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  88634. return DefaultRenderingPipeline;
  88635. }(BABYLON.PostProcessRenderPipeline));
  88636. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  88637. })(BABYLON || (BABYLON = {}));
  88638. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  88639. var BABYLON;
  88640. (function (BABYLON) {
  88641. /**
  88642. * @hidden
  88643. */
  88644. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  88645. __extends(ImageProcessingConfigurationDefines, _super);
  88646. function ImageProcessingConfigurationDefines() {
  88647. var _this = _super.call(this) || this;
  88648. _this.IMAGEPROCESSING = false;
  88649. _this.VIGNETTE = false;
  88650. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88651. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88652. _this.TONEMAPPING = false;
  88653. _this.TONEMAPPING_ACES = false;
  88654. _this.CONTRAST = false;
  88655. _this.COLORCURVES = false;
  88656. _this.COLORGRADING = false;
  88657. _this.COLORGRADING3D = false;
  88658. _this.SAMPLER3DGREENDEPTH = false;
  88659. _this.SAMPLER3DBGRMAP = false;
  88660. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88661. _this.EXPOSURE = false;
  88662. _this.rebuild();
  88663. return _this;
  88664. }
  88665. return ImageProcessingConfigurationDefines;
  88666. }(BABYLON.MaterialDefines));
  88667. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  88668. /**
  88669. * This groups together the common properties used for image processing either in direct forward pass
  88670. * or through post processing effect depending on the use of the image processing pipeline in your scene
  88671. * or not.
  88672. */
  88673. var ImageProcessingConfiguration = /** @class */ (function () {
  88674. function ImageProcessingConfiguration() {
  88675. /**
  88676. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  88677. */
  88678. this.colorCurves = new BABYLON.ColorCurves();
  88679. this._colorCurvesEnabled = false;
  88680. this._colorGradingEnabled = false;
  88681. this._colorGradingWithGreenDepth = true;
  88682. this._colorGradingBGR = true;
  88683. /** @hidden */
  88684. this._exposure = 1.0;
  88685. this._toneMappingEnabled = false;
  88686. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  88687. this._contrast = 1.0;
  88688. /**
  88689. * Vignette stretch size.
  88690. */
  88691. this.vignetteStretch = 0;
  88692. /**
  88693. * Vignette centre X Offset.
  88694. */
  88695. this.vignetteCentreX = 0;
  88696. /**
  88697. * Vignette centre Y Offset.
  88698. */
  88699. this.vignetteCentreY = 0;
  88700. /**
  88701. * Vignette weight or intensity of the vignette effect.
  88702. */
  88703. this.vignetteWeight = 1.5;
  88704. /**
  88705. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  88706. * if vignetteEnabled is set to true.
  88707. */
  88708. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88709. /**
  88710. * Camera field of view used by the Vignette effect.
  88711. */
  88712. this.vignetteCameraFov = 0.5;
  88713. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  88714. this._vignetteEnabled = false;
  88715. this._applyByPostProcess = false;
  88716. this._isEnabled = true;
  88717. /**
  88718. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  88719. */
  88720. this.onUpdateParameters = new BABYLON.Observable();
  88721. }
  88722. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  88723. /**
  88724. * Gets wether the color curves effect is enabled.
  88725. */
  88726. get: function () {
  88727. return this._colorCurvesEnabled;
  88728. },
  88729. /**
  88730. * Sets wether the color curves effect is enabled.
  88731. */
  88732. set: function (value) {
  88733. if (this._colorCurvesEnabled === value) {
  88734. return;
  88735. }
  88736. this._colorCurvesEnabled = value;
  88737. this._updateParameters();
  88738. },
  88739. enumerable: true,
  88740. configurable: true
  88741. });
  88742. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
  88743. /**
  88744. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  88745. */
  88746. get: function () {
  88747. return this._colorGradingTexture;
  88748. },
  88749. /**
  88750. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  88751. */
  88752. set: function (value) {
  88753. if (this._colorGradingTexture === value) {
  88754. return;
  88755. }
  88756. this._colorGradingTexture = value;
  88757. this._updateParameters();
  88758. },
  88759. enumerable: true,
  88760. configurable: true
  88761. });
  88762. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  88763. /**
  88764. * Gets wether the color grading effect is enabled.
  88765. */
  88766. get: function () {
  88767. return this._colorGradingEnabled;
  88768. },
  88769. /**
  88770. * Sets wether the color grading effect is enabled.
  88771. */
  88772. set: function (value) {
  88773. if (this._colorGradingEnabled === value) {
  88774. return;
  88775. }
  88776. this._colorGradingEnabled = value;
  88777. this._updateParameters();
  88778. },
  88779. enumerable: true,
  88780. configurable: true
  88781. });
  88782. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  88783. /**
  88784. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  88785. */
  88786. get: function () {
  88787. return this._colorGradingWithGreenDepth;
  88788. },
  88789. /**
  88790. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  88791. */
  88792. set: function (value) {
  88793. if (this._colorGradingWithGreenDepth === value) {
  88794. return;
  88795. }
  88796. this._colorGradingWithGreenDepth = value;
  88797. this._updateParameters();
  88798. },
  88799. enumerable: true,
  88800. configurable: true
  88801. });
  88802. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  88803. /**
  88804. * Gets wether the color grading texture contains BGR values.
  88805. */
  88806. get: function () {
  88807. return this._colorGradingBGR;
  88808. },
  88809. /**
  88810. * Sets wether the color grading texture contains BGR values.
  88811. */
  88812. set: function (value) {
  88813. if (this._colorGradingBGR === value) {
  88814. return;
  88815. }
  88816. this._colorGradingBGR = value;
  88817. this._updateParameters();
  88818. },
  88819. enumerable: true,
  88820. configurable: true
  88821. });
  88822. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  88823. /**
  88824. * Gets the Exposure used in the effect.
  88825. */
  88826. get: function () {
  88827. return this._exposure;
  88828. },
  88829. /**
  88830. * Sets the Exposure used in the effect.
  88831. */
  88832. set: function (value) {
  88833. if (this._exposure === value) {
  88834. return;
  88835. }
  88836. this._exposure = value;
  88837. this._updateParameters();
  88838. },
  88839. enumerable: true,
  88840. configurable: true
  88841. });
  88842. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  88843. /**
  88844. * Gets wether the tone mapping effect is enabled.
  88845. */
  88846. get: function () {
  88847. return this._toneMappingEnabled;
  88848. },
  88849. /**
  88850. * Sets wether the tone mapping effect is enabled.
  88851. */
  88852. set: function (value) {
  88853. if (this._toneMappingEnabled === value) {
  88854. return;
  88855. }
  88856. this._toneMappingEnabled = value;
  88857. this._updateParameters();
  88858. },
  88859. enumerable: true,
  88860. configurable: true
  88861. });
  88862. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  88863. /**
  88864. * Gets the type of tone mapping effect.
  88865. */
  88866. get: function () {
  88867. return this._toneMappingType;
  88868. },
  88869. /**
  88870. * Sets the type of tone mapping effect used in BabylonJS.
  88871. */
  88872. set: function (value) {
  88873. if (this._toneMappingType === value) {
  88874. return;
  88875. }
  88876. this._toneMappingType = value;
  88877. this._updateParameters();
  88878. },
  88879. enumerable: true,
  88880. configurable: true
  88881. });
  88882. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  88883. /**
  88884. * Gets the contrast used in the effect.
  88885. */
  88886. get: function () {
  88887. return this._contrast;
  88888. },
  88889. /**
  88890. * Sets the contrast used in the effect.
  88891. */
  88892. set: function (value) {
  88893. if (this._contrast === value) {
  88894. return;
  88895. }
  88896. this._contrast = value;
  88897. this._updateParameters();
  88898. },
  88899. enumerable: true,
  88900. configurable: true
  88901. });
  88902. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  88903. /**
  88904. * Gets the vignette blend mode allowing different kind of effect.
  88905. */
  88906. get: function () {
  88907. return this._vignetteBlendMode;
  88908. },
  88909. /**
  88910. * Sets the vignette blend mode allowing different kind of effect.
  88911. */
  88912. set: function (value) {
  88913. if (this._vignetteBlendMode === value) {
  88914. return;
  88915. }
  88916. this._vignetteBlendMode = value;
  88917. this._updateParameters();
  88918. },
  88919. enumerable: true,
  88920. configurable: true
  88921. });
  88922. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  88923. /**
  88924. * Gets wether the vignette effect is enabled.
  88925. */
  88926. get: function () {
  88927. return this._vignetteEnabled;
  88928. },
  88929. /**
  88930. * Sets wether the vignette effect is enabled.
  88931. */
  88932. set: function (value) {
  88933. if (this._vignetteEnabled === value) {
  88934. return;
  88935. }
  88936. this._vignetteEnabled = value;
  88937. this._updateParameters();
  88938. },
  88939. enumerable: true,
  88940. configurable: true
  88941. });
  88942. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  88943. /**
  88944. * Gets wether the image processing is applied through a post process or not.
  88945. */
  88946. get: function () {
  88947. return this._applyByPostProcess;
  88948. },
  88949. /**
  88950. * Sets wether the image processing is applied through a post process or not.
  88951. */
  88952. set: function (value) {
  88953. if (this._applyByPostProcess === value) {
  88954. return;
  88955. }
  88956. this._applyByPostProcess = value;
  88957. this._updateParameters();
  88958. },
  88959. enumerable: true,
  88960. configurable: true
  88961. });
  88962. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  88963. /**
  88964. * Gets wether the image processing is enabled or not.
  88965. */
  88966. get: function () {
  88967. return this._isEnabled;
  88968. },
  88969. /**
  88970. * Sets wether the image processing is enabled or not.
  88971. */
  88972. set: function (value) {
  88973. if (this._isEnabled === value) {
  88974. return;
  88975. }
  88976. this._isEnabled = value;
  88977. this._updateParameters();
  88978. },
  88979. enumerable: true,
  88980. configurable: true
  88981. });
  88982. /**
  88983. * Method called each time the image processing information changes requires to recompile the effect.
  88984. */
  88985. ImageProcessingConfiguration.prototype._updateParameters = function () {
  88986. this.onUpdateParameters.notifyObservers(this);
  88987. };
  88988. /**
  88989. * Gets the current class name.
  88990. * @return "ImageProcessingConfiguration"
  88991. */
  88992. ImageProcessingConfiguration.prototype.getClassName = function () {
  88993. return "ImageProcessingConfiguration";
  88994. };
  88995. /**
  88996. * Prepare the list of uniforms associated with the Image Processing effects.
  88997. * @param uniforms The list of uniforms used in the effect
  88998. * @param defines the list of defines currently in use
  88999. */
  89000. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  89001. if (defines.EXPOSURE) {
  89002. uniforms.push("exposureLinear");
  89003. }
  89004. if (defines.CONTRAST) {
  89005. uniforms.push("contrast");
  89006. }
  89007. if (defines.COLORGRADING) {
  89008. uniforms.push("colorTransformSettings");
  89009. }
  89010. if (defines.VIGNETTE) {
  89011. uniforms.push("vInverseScreenSize");
  89012. uniforms.push("vignetteSettings1");
  89013. uniforms.push("vignetteSettings2");
  89014. }
  89015. if (defines.COLORCURVES) {
  89016. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  89017. }
  89018. };
  89019. /**
  89020. * Prepare the list of samplers associated with the Image Processing effects.
  89021. * @param samplersList The list of uniforms used in the effect
  89022. * @param defines the list of defines currently in use
  89023. */
  89024. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  89025. if (defines.COLORGRADING) {
  89026. samplersList.push("txColorTransform");
  89027. }
  89028. };
  89029. /**
  89030. * Prepare the list of defines associated to the shader.
  89031. * @param defines the list of defines to complete
  89032. * @param forPostProcess Define if we are currently in post process mode or not
  89033. */
  89034. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  89035. if (forPostProcess === void 0) { forPostProcess = false; }
  89036. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  89037. defines.VIGNETTE = false;
  89038. defines.TONEMAPPING = false;
  89039. defines.TONEMAPPING_ACES = false;
  89040. defines.CONTRAST = false;
  89041. defines.EXPOSURE = false;
  89042. defines.COLORCURVES = false;
  89043. defines.COLORGRADING = false;
  89044. defines.COLORGRADING3D = false;
  89045. defines.IMAGEPROCESSING = false;
  89046. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  89047. return;
  89048. }
  89049. defines.VIGNETTE = this.vignetteEnabled;
  89050. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  89051. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  89052. defines.TONEMAPPING = this.toneMappingEnabled;
  89053. switch (this._toneMappingType) {
  89054. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  89055. defines.TONEMAPPING_ACES = true;
  89056. break;
  89057. }
  89058. defines.CONTRAST = (this.contrast !== 1.0);
  89059. defines.EXPOSURE = (this.exposure !== 1.0);
  89060. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  89061. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  89062. if (defines.COLORGRADING) {
  89063. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  89064. }
  89065. else {
  89066. defines.COLORGRADING3D = false;
  89067. }
  89068. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  89069. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  89070. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  89071. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  89072. };
  89073. /**
  89074. * Returns true if all the image processing information are ready.
  89075. * @returns True if ready, otherwise, false
  89076. */
  89077. ImageProcessingConfiguration.prototype.isReady = function () {
  89078. // Color Grading texure can not be none blocking.
  89079. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  89080. };
  89081. /**
  89082. * Binds the image processing to the shader.
  89083. * @param effect The effect to bind to
  89084. * @param aspectRatio Define the current aspect ratio of the effect
  89085. */
  89086. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  89087. if (aspectRatio === void 0) { aspectRatio = 1; }
  89088. // Color Curves
  89089. if (this._colorCurvesEnabled && this.colorCurves) {
  89090. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  89091. }
  89092. // Vignette
  89093. if (this._vignetteEnabled) {
  89094. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  89095. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  89096. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  89097. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  89098. var vignetteScaleX = vignetteScaleY * aspectRatio;
  89099. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  89100. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  89101. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  89102. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  89103. var vignettePower = -2.0 * this.vignetteWeight;
  89104. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  89105. }
  89106. // Exposure
  89107. effect.setFloat("exposureLinear", this.exposure);
  89108. // Contrast
  89109. effect.setFloat("contrast", this.contrast);
  89110. // Color transform settings
  89111. if (this.colorGradingTexture) {
  89112. effect.setTexture("txColorTransform", this.colorGradingTexture);
  89113. var textureSize = this.colorGradingTexture.getSize().height;
  89114. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  89115. 0.5 / textureSize, // textureOffset
  89116. textureSize, // textureSize
  89117. this.colorGradingTexture.level // weight
  89118. );
  89119. }
  89120. };
  89121. /**
  89122. * Clones the current image processing instance.
  89123. * @return The cloned image processing
  89124. */
  89125. ImageProcessingConfiguration.prototype.clone = function () {
  89126. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  89127. };
  89128. /**
  89129. * Serializes the current image processing instance to a json representation.
  89130. * @return a JSON representation
  89131. */
  89132. ImageProcessingConfiguration.prototype.serialize = function () {
  89133. return BABYLON.SerializationHelper.Serialize(this);
  89134. };
  89135. /**
  89136. * Parses the image processing from a json representation.
  89137. * @param source the JSON source to parse
  89138. * @return The parsed image processing
  89139. */
  89140. ImageProcessingConfiguration.Parse = function (source) {
  89141. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  89142. };
  89143. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  89144. /**
  89145. * Used to apply the vignette as a mix with the pixel color.
  89146. */
  89147. get: function () {
  89148. return this._VIGNETTEMODE_MULTIPLY;
  89149. },
  89150. enumerable: true,
  89151. configurable: true
  89152. });
  89153. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  89154. /**
  89155. * Used to apply the vignette as a replacement of the pixel color.
  89156. */
  89157. get: function () {
  89158. return this._VIGNETTEMODE_OPAQUE;
  89159. },
  89160. enumerable: true,
  89161. configurable: true
  89162. });
  89163. /**
  89164. * Default tone mapping applied in BabylonJS.
  89165. */
  89166. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  89167. /**
  89168. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  89169. * to other engines rendering to increase portability.
  89170. */
  89171. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  89172. // Static constants associated to the image processing.
  89173. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  89174. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  89175. __decorate([
  89176. BABYLON.serializeAsColorCurves()
  89177. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  89178. __decorate([
  89179. BABYLON.serialize()
  89180. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  89181. __decorate([
  89182. BABYLON.serializeAsTexture("colorGradingTexture")
  89183. ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
  89184. __decorate([
  89185. BABYLON.serialize()
  89186. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  89187. __decorate([
  89188. BABYLON.serialize()
  89189. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  89190. __decorate([
  89191. BABYLON.serialize()
  89192. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  89193. __decorate([
  89194. BABYLON.serialize()
  89195. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  89196. __decorate([
  89197. BABYLON.serialize()
  89198. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  89199. __decorate([
  89200. BABYLON.serialize()
  89201. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  89202. __decorate([
  89203. BABYLON.serialize()
  89204. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  89205. __decorate([
  89206. BABYLON.serialize()
  89207. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  89208. __decorate([
  89209. BABYLON.serialize()
  89210. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  89211. __decorate([
  89212. BABYLON.serialize()
  89213. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  89214. __decorate([
  89215. BABYLON.serialize()
  89216. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  89217. __decorate([
  89218. BABYLON.serializeAsColor4()
  89219. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  89220. __decorate([
  89221. BABYLON.serialize()
  89222. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  89223. __decorate([
  89224. BABYLON.serialize()
  89225. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  89226. __decorate([
  89227. BABYLON.serialize()
  89228. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  89229. __decorate([
  89230. BABYLON.serialize()
  89231. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  89232. __decorate([
  89233. BABYLON.serialize()
  89234. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  89235. return ImageProcessingConfiguration;
  89236. }());
  89237. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  89238. })(BABYLON || (BABYLON = {}));
  89239. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  89240. var BABYLON;
  89241. (function (BABYLON) {
  89242. /**
  89243. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  89244. * It can help converting any input color in a desired output one. This can then be used to create effects
  89245. * from sepia, black and white to sixties or futuristic rendering...
  89246. *
  89247. * The only supported format is currently 3dl.
  89248. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  89249. */
  89250. var ColorGradingTexture = /** @class */ (function (_super) {
  89251. __extends(ColorGradingTexture, _super);
  89252. /**
  89253. * Instantiates a ColorGradingTexture from the following parameters.
  89254. *
  89255. * @param url The location of the color gradind data (currently only supporting 3dl)
  89256. * @param scene The scene the texture will be used in
  89257. */
  89258. function ColorGradingTexture(url, scene) {
  89259. var _this = _super.call(this, scene) || this;
  89260. if (!url) {
  89261. return _this;
  89262. }
  89263. _this._engine = scene.getEngine();
  89264. _this._textureMatrix = BABYLON.Matrix.Identity();
  89265. _this.name = url;
  89266. _this.url = url;
  89267. _this.hasAlpha = false;
  89268. _this.isCube = false;
  89269. _this.is3D = _this._engine.webGLVersion > 1;
  89270. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89271. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89272. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89273. _this.anisotropicFilteringLevel = 1;
  89274. _this._texture = _this._getFromCache(url, true);
  89275. if (!_this._texture) {
  89276. if (!scene.useDelayedTextureLoading) {
  89277. _this.loadTexture();
  89278. }
  89279. else {
  89280. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  89281. }
  89282. }
  89283. return _this;
  89284. }
  89285. /**
  89286. * Returns the texture matrix used in most of the material.
  89287. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  89288. */
  89289. ColorGradingTexture.prototype.getTextureMatrix = function () {
  89290. return this._textureMatrix;
  89291. };
  89292. /**
  89293. * Occurs when the file being loaded is a .3dl LUT file.
  89294. */
  89295. ColorGradingTexture.prototype.load3dlTexture = function () {
  89296. var engine = this._engine;
  89297. var texture;
  89298. if (engine.webGLVersion === 1) {
  89299. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89300. }
  89301. else {
  89302. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89303. }
  89304. this._texture = texture;
  89305. var callback = function (text) {
  89306. if (typeof text !== "string") {
  89307. return;
  89308. }
  89309. var data = null;
  89310. var tempData = null;
  89311. var line;
  89312. var lines = text.split('\n');
  89313. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  89314. var maxColor = 0;
  89315. for (var i = 0; i < lines.length; i++) {
  89316. line = lines[i];
  89317. if (!ColorGradingTexture._noneEmptyLineRegex.test(line)) {
  89318. continue;
  89319. }
  89320. if (line.indexOf('#') === 0) {
  89321. continue;
  89322. }
  89323. var words = line.split(" ");
  89324. if (size === 0) {
  89325. // Number of space + one
  89326. size = words.length;
  89327. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  89328. tempData = new Float32Array(size * size * size * 4);
  89329. continue;
  89330. }
  89331. if (size != 0) {
  89332. var r = Math.max(parseInt(words[0]), 0);
  89333. var g = Math.max(parseInt(words[1]), 0);
  89334. var b = Math.max(parseInt(words[2]), 0);
  89335. maxColor = Math.max(r, maxColor);
  89336. maxColor = Math.max(g, maxColor);
  89337. maxColor = Math.max(b, maxColor);
  89338. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  89339. if (tempData) {
  89340. tempData[pixelStorageIndex + 0] = r;
  89341. tempData[pixelStorageIndex + 1] = g;
  89342. tempData[pixelStorageIndex + 2] = b;
  89343. }
  89344. // Keep for reference in case of back compat problems.
  89345. // pixelIndexSlice++;
  89346. // if (pixelIndexSlice % size == 0) {
  89347. // pixelIndexH++;
  89348. // pixelIndexSlice = 0;
  89349. // if (pixelIndexH % size == 0) {
  89350. // pixelIndexW++;
  89351. // pixelIndexH = 0;
  89352. // }
  89353. // }
  89354. pixelIndexH++;
  89355. if (pixelIndexH % size == 0) {
  89356. pixelIndexSlice++;
  89357. pixelIndexH = 0;
  89358. if (pixelIndexSlice % size == 0) {
  89359. pixelIndexW++;
  89360. pixelIndexSlice = 0;
  89361. }
  89362. }
  89363. }
  89364. }
  89365. if (tempData && data) {
  89366. for (var i = 0; i < tempData.length; i++) {
  89367. if (i > 0 && (i + 1) % 4 === 0) {
  89368. data[i] = 255;
  89369. }
  89370. else {
  89371. var value = tempData[i];
  89372. data[i] = (value / maxColor * 255);
  89373. }
  89374. }
  89375. }
  89376. if (texture.is3D) {
  89377. texture.updateSize(size, size, size);
  89378. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  89379. }
  89380. else {
  89381. texture.updateSize(size * size, size);
  89382. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  89383. }
  89384. };
  89385. var scene = this.getScene();
  89386. if (scene) {
  89387. scene._loadFile(this.url, callback);
  89388. }
  89389. else {
  89390. this._engine._loadFile(this.url, callback);
  89391. }
  89392. return this._texture;
  89393. };
  89394. /**
  89395. * Starts the loading process of the texture.
  89396. */
  89397. ColorGradingTexture.prototype.loadTexture = function () {
  89398. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  89399. this.load3dlTexture();
  89400. }
  89401. };
  89402. /**
  89403. * Clones the color gradind texture.
  89404. */
  89405. ColorGradingTexture.prototype.clone = function () {
  89406. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  89407. // Base texture
  89408. newTexture.level = this.level;
  89409. return newTexture;
  89410. };
  89411. /**
  89412. * Called during delayed load for textures.
  89413. */
  89414. ColorGradingTexture.prototype.delayLoad = function () {
  89415. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  89416. return;
  89417. }
  89418. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  89419. this._texture = this._getFromCache(this.url, true);
  89420. if (!this._texture) {
  89421. this.loadTexture();
  89422. }
  89423. };
  89424. /**
  89425. * Parses a color grading texture serialized by Babylon.
  89426. * @param parsedTexture The texture information being parsedTexture
  89427. * @param scene The scene to load the texture in
  89428. * @param rootUrl The root url of the data assets to load
  89429. * @return A color gradind texture
  89430. */
  89431. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  89432. var texture = null;
  89433. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  89434. texture = new ColorGradingTexture(parsedTexture.name, scene);
  89435. texture.name = parsedTexture.name;
  89436. texture.level = parsedTexture.level;
  89437. }
  89438. return texture;
  89439. };
  89440. /**
  89441. * Serializes the LUT texture to json format.
  89442. */
  89443. ColorGradingTexture.prototype.serialize = function () {
  89444. if (!this.name) {
  89445. return null;
  89446. }
  89447. var serializationObject = {};
  89448. serializationObject.name = this.name;
  89449. serializationObject.level = this.level;
  89450. serializationObject.customType = "BABYLON.ColorGradingTexture";
  89451. return serializationObject;
  89452. };
  89453. /**
  89454. * Empty line regex stored for GC.
  89455. */
  89456. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  89457. return ColorGradingTexture;
  89458. }(BABYLON.BaseTexture));
  89459. BABYLON.ColorGradingTexture = ColorGradingTexture;
  89460. })(BABYLON || (BABYLON = {}));
  89461. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  89462. var BABYLON;
  89463. (function (BABYLON) {
  89464. /**
  89465. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89466. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89467. * 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;
  89468. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89469. */
  89470. var ColorCurves = /** @class */ (function () {
  89471. function ColorCurves() {
  89472. this._dirty = true;
  89473. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  89474. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  89475. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  89476. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  89477. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  89478. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  89479. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  89480. this._globalHue = 30;
  89481. this._globalDensity = 0;
  89482. this._globalSaturation = 0;
  89483. this._globalExposure = 0;
  89484. this._highlightsHue = 30;
  89485. this._highlightsDensity = 0;
  89486. this._highlightsSaturation = 0;
  89487. this._highlightsExposure = 0;
  89488. this._midtonesHue = 30;
  89489. this._midtonesDensity = 0;
  89490. this._midtonesSaturation = 0;
  89491. this._midtonesExposure = 0;
  89492. this._shadowsHue = 30;
  89493. this._shadowsDensity = 0;
  89494. this._shadowsSaturation = 0;
  89495. this._shadowsExposure = 0;
  89496. }
  89497. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  89498. /**
  89499. * Gets the global Hue value.
  89500. * 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).
  89501. */
  89502. get: function () {
  89503. return this._globalHue;
  89504. },
  89505. /**
  89506. * Sets the global Hue value.
  89507. * 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).
  89508. */
  89509. set: function (value) {
  89510. this._globalHue = value;
  89511. this._dirty = true;
  89512. },
  89513. enumerable: true,
  89514. configurable: true
  89515. });
  89516. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  89517. /**
  89518. * Gets the global Density value.
  89519. * 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.
  89520. * Values less than zero provide a filter of opposite hue.
  89521. */
  89522. get: function () {
  89523. return this._globalDensity;
  89524. },
  89525. /**
  89526. * Sets the global Density value.
  89527. * 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.
  89528. * Values less than zero provide a filter of opposite hue.
  89529. */
  89530. set: function (value) {
  89531. this._globalDensity = value;
  89532. this._dirty = true;
  89533. },
  89534. enumerable: true,
  89535. configurable: true
  89536. });
  89537. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  89538. /**
  89539. * Gets the global Saturation value.
  89540. * 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.
  89541. */
  89542. get: function () {
  89543. return this._globalSaturation;
  89544. },
  89545. /**
  89546. * Sets the global Saturation value.
  89547. * 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.
  89548. */
  89549. set: function (value) {
  89550. this._globalSaturation = value;
  89551. this._dirty = true;
  89552. },
  89553. enumerable: true,
  89554. configurable: true
  89555. });
  89556. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  89557. /**
  89558. * Gets the global Exposure value.
  89559. * 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.
  89560. */
  89561. get: function () {
  89562. return this._globalExposure;
  89563. },
  89564. /**
  89565. * Sets the global Exposure value.
  89566. * 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.
  89567. */
  89568. set: function (value) {
  89569. this._globalExposure = value;
  89570. this._dirty = true;
  89571. },
  89572. enumerable: true,
  89573. configurable: true
  89574. });
  89575. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  89576. /**
  89577. * Gets the highlights Hue value.
  89578. * 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).
  89579. */
  89580. get: function () {
  89581. return this._highlightsHue;
  89582. },
  89583. /**
  89584. * Sets the highlights Hue value.
  89585. * 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).
  89586. */
  89587. set: function (value) {
  89588. this._highlightsHue = value;
  89589. this._dirty = true;
  89590. },
  89591. enumerable: true,
  89592. configurable: true
  89593. });
  89594. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  89595. /**
  89596. * Gets the highlights Density value.
  89597. * 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.
  89598. * Values less than zero provide a filter of opposite hue.
  89599. */
  89600. get: function () {
  89601. return this._highlightsDensity;
  89602. },
  89603. /**
  89604. * Sets the highlights Density value.
  89605. * 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.
  89606. * Values less than zero provide a filter of opposite hue.
  89607. */
  89608. set: function (value) {
  89609. this._highlightsDensity = value;
  89610. this._dirty = true;
  89611. },
  89612. enumerable: true,
  89613. configurable: true
  89614. });
  89615. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  89616. /**
  89617. * Gets the highlights Saturation value.
  89618. * 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.
  89619. */
  89620. get: function () {
  89621. return this._highlightsSaturation;
  89622. },
  89623. /**
  89624. * Sets the highlights Saturation value.
  89625. * 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.
  89626. */
  89627. set: function (value) {
  89628. this._highlightsSaturation = value;
  89629. this._dirty = true;
  89630. },
  89631. enumerable: true,
  89632. configurable: true
  89633. });
  89634. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  89635. /**
  89636. * Gets the highlights Exposure value.
  89637. * 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.
  89638. */
  89639. get: function () {
  89640. return this._highlightsExposure;
  89641. },
  89642. /**
  89643. * Sets the highlights Exposure value.
  89644. * 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.
  89645. */
  89646. set: function (value) {
  89647. this._highlightsExposure = value;
  89648. this._dirty = true;
  89649. },
  89650. enumerable: true,
  89651. configurable: true
  89652. });
  89653. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  89654. /**
  89655. * Gets the midtones Hue value.
  89656. * 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).
  89657. */
  89658. get: function () {
  89659. return this._midtonesHue;
  89660. },
  89661. /**
  89662. * Sets the midtones Hue value.
  89663. * 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).
  89664. */
  89665. set: function (value) {
  89666. this._midtonesHue = value;
  89667. this._dirty = true;
  89668. },
  89669. enumerable: true,
  89670. configurable: true
  89671. });
  89672. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  89673. /**
  89674. * Gets the midtones Density value.
  89675. * 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.
  89676. * Values less than zero provide a filter of opposite hue.
  89677. */
  89678. get: function () {
  89679. return this._midtonesDensity;
  89680. },
  89681. /**
  89682. * Sets the midtones Density value.
  89683. * 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.
  89684. * Values less than zero provide a filter of opposite hue.
  89685. */
  89686. set: function (value) {
  89687. this._midtonesDensity = value;
  89688. this._dirty = true;
  89689. },
  89690. enumerable: true,
  89691. configurable: true
  89692. });
  89693. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  89694. /**
  89695. * Gets the midtones Saturation value.
  89696. * 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.
  89697. */
  89698. get: function () {
  89699. return this._midtonesSaturation;
  89700. },
  89701. /**
  89702. * Sets the midtones Saturation value.
  89703. * 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.
  89704. */
  89705. set: function (value) {
  89706. this._midtonesSaturation = value;
  89707. this._dirty = true;
  89708. },
  89709. enumerable: true,
  89710. configurable: true
  89711. });
  89712. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  89713. /**
  89714. * Gets the midtones Exposure value.
  89715. * 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.
  89716. */
  89717. get: function () {
  89718. return this._midtonesExposure;
  89719. },
  89720. /**
  89721. * Sets the midtones Exposure value.
  89722. * 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.
  89723. */
  89724. set: function (value) {
  89725. this._midtonesExposure = value;
  89726. this._dirty = true;
  89727. },
  89728. enumerable: true,
  89729. configurable: true
  89730. });
  89731. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  89732. /**
  89733. * Gets the shadows Hue value.
  89734. * 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).
  89735. */
  89736. get: function () {
  89737. return this._shadowsHue;
  89738. },
  89739. /**
  89740. * Sets the shadows Hue value.
  89741. * 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).
  89742. */
  89743. set: function (value) {
  89744. this._shadowsHue = value;
  89745. this._dirty = true;
  89746. },
  89747. enumerable: true,
  89748. configurable: true
  89749. });
  89750. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  89751. /**
  89752. * Gets the shadows Density value.
  89753. * 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.
  89754. * Values less than zero provide a filter of opposite hue.
  89755. */
  89756. get: function () {
  89757. return this._shadowsDensity;
  89758. },
  89759. /**
  89760. * Sets the shadows Density value.
  89761. * 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.
  89762. * Values less than zero provide a filter of opposite hue.
  89763. */
  89764. set: function (value) {
  89765. this._shadowsDensity = value;
  89766. this._dirty = true;
  89767. },
  89768. enumerable: true,
  89769. configurable: true
  89770. });
  89771. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  89772. /**
  89773. * Gets the shadows Saturation value.
  89774. * 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.
  89775. */
  89776. get: function () {
  89777. return this._shadowsSaturation;
  89778. },
  89779. /**
  89780. * Sets the shadows Saturation value.
  89781. * 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.
  89782. */
  89783. set: function (value) {
  89784. this._shadowsSaturation = value;
  89785. this._dirty = true;
  89786. },
  89787. enumerable: true,
  89788. configurable: true
  89789. });
  89790. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  89791. /**
  89792. * Gets the shadows Exposure value.
  89793. * 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.
  89794. */
  89795. get: function () {
  89796. return this._shadowsExposure;
  89797. },
  89798. /**
  89799. * Sets the shadows Exposure value.
  89800. * 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.
  89801. */
  89802. set: function (value) {
  89803. this._shadowsExposure = value;
  89804. this._dirty = true;
  89805. },
  89806. enumerable: true,
  89807. configurable: true
  89808. });
  89809. /**
  89810. * Returns the class name
  89811. * @returns The class name
  89812. */
  89813. ColorCurves.prototype.getClassName = function () {
  89814. return "ColorCurves";
  89815. };
  89816. /**
  89817. * Binds the color curves to the shader.
  89818. * @param colorCurves The color curve to bind
  89819. * @param effect The effect to bind to
  89820. * @param positiveUniform The positive uniform shader parameter
  89821. * @param neutralUniform The neutral uniform shader parameter
  89822. * @param negativeUniform The negative uniform shader parameter
  89823. */
  89824. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  89825. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  89826. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  89827. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  89828. if (colorCurves._dirty) {
  89829. colorCurves._dirty = false;
  89830. // Fill in global info.
  89831. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  89832. // Compute highlights info.
  89833. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  89834. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  89835. // Compute midtones info.
  89836. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  89837. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  89838. // Compute shadows info.
  89839. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  89840. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  89841. // Compute deltas (neutral is midtones).
  89842. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  89843. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  89844. }
  89845. if (effect) {
  89846. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  89847. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  89848. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  89849. }
  89850. };
  89851. /**
  89852. * Prepare the list of uniforms associated with the ColorCurves effects.
  89853. * @param uniformsList The list of uniforms used in the effect
  89854. */
  89855. ColorCurves.PrepareUniforms = function (uniformsList) {
  89856. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  89857. };
  89858. /**
  89859. * Returns color grading data based on a hue, density, saturation and exposure value.
  89860. * @param filterHue The hue of the color filter.
  89861. * @param filterDensity The density of the color filter.
  89862. * @param saturation The saturation.
  89863. * @param exposure The exposure.
  89864. * @param result The result data container.
  89865. */
  89866. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  89867. if (hue == null) {
  89868. return;
  89869. }
  89870. hue = ColorCurves.clamp(hue, 0, 360);
  89871. density = ColorCurves.clamp(density, -100, 100);
  89872. saturation = ColorCurves.clamp(saturation, -100, 100);
  89873. exposure = ColorCurves.clamp(exposure, -100, 100);
  89874. // Remap the slider/config filter density with non-linear mapping and also scale by half
  89875. // so that the maximum filter density is only 50% control. This provides fine control
  89876. // for small values and reasonable range.
  89877. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  89878. density *= 0.5;
  89879. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  89880. if (density < 0) {
  89881. density *= -1;
  89882. hue = (hue + 180) % 360;
  89883. }
  89884. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  89885. result.scaleToRef(2, result);
  89886. result.a = 1 + 0.01 * saturation;
  89887. };
  89888. /**
  89889. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  89890. * @param value The input slider value in range [-100,100].
  89891. * @returns Adjusted value.
  89892. */
  89893. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  89894. value /= 100;
  89895. var x = Math.abs(value);
  89896. x = Math.pow(x, 2);
  89897. if (value < 0) {
  89898. x *= -1;
  89899. }
  89900. x *= 100;
  89901. return x;
  89902. };
  89903. /**
  89904. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  89905. * @param hue The hue (H) input.
  89906. * @param saturation The saturation (S) input.
  89907. * @param brightness The brightness (B) input.
  89908. * @result An RGBA color represented as Vector4.
  89909. */
  89910. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  89911. var h = ColorCurves.clamp(hue, 0, 360);
  89912. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  89913. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  89914. if (s === 0) {
  89915. result.r = v;
  89916. result.g = v;
  89917. result.b = v;
  89918. }
  89919. else {
  89920. // sector 0 to 5
  89921. h /= 60;
  89922. var i = Math.floor(h);
  89923. // fractional part of h
  89924. var f = h - i;
  89925. var p = v * (1 - s);
  89926. var q = v * (1 - s * f);
  89927. var t = v * (1 - s * (1 - f));
  89928. switch (i) {
  89929. case 0:
  89930. result.r = v;
  89931. result.g = t;
  89932. result.b = p;
  89933. break;
  89934. case 1:
  89935. result.r = q;
  89936. result.g = v;
  89937. result.b = p;
  89938. break;
  89939. case 2:
  89940. result.r = p;
  89941. result.g = v;
  89942. result.b = t;
  89943. break;
  89944. case 3:
  89945. result.r = p;
  89946. result.g = q;
  89947. result.b = v;
  89948. break;
  89949. case 4:
  89950. result.r = t;
  89951. result.g = p;
  89952. result.b = v;
  89953. break;
  89954. default: // case 5:
  89955. result.r = v;
  89956. result.g = p;
  89957. result.b = q;
  89958. break;
  89959. }
  89960. }
  89961. result.a = 1;
  89962. };
  89963. /**
  89964. * Returns a value clamped between min and max
  89965. * @param value The value to clamp
  89966. * @param min The minimum of value
  89967. * @param max The maximum of value
  89968. * @returns The clamped value.
  89969. */
  89970. ColorCurves.clamp = function (value, min, max) {
  89971. return Math.min(Math.max(value, min), max);
  89972. };
  89973. /**
  89974. * Clones the current color curve instance.
  89975. * @return The cloned curves
  89976. */
  89977. ColorCurves.prototype.clone = function () {
  89978. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  89979. };
  89980. /**
  89981. * Serializes the current color curve instance to a json representation.
  89982. * @return a JSON representation
  89983. */
  89984. ColorCurves.prototype.serialize = function () {
  89985. return BABYLON.SerializationHelper.Serialize(this);
  89986. };
  89987. /**
  89988. * Parses the color curve from a json representation.
  89989. * @param source the JSON source to parse
  89990. * @return The parsed curves
  89991. */
  89992. ColorCurves.Parse = function (source) {
  89993. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  89994. };
  89995. __decorate([
  89996. BABYLON.serialize()
  89997. ], ColorCurves.prototype, "_globalHue", void 0);
  89998. __decorate([
  89999. BABYLON.serialize()
  90000. ], ColorCurves.prototype, "_globalDensity", void 0);
  90001. __decorate([
  90002. BABYLON.serialize()
  90003. ], ColorCurves.prototype, "_globalSaturation", void 0);
  90004. __decorate([
  90005. BABYLON.serialize()
  90006. ], ColorCurves.prototype, "_globalExposure", void 0);
  90007. __decorate([
  90008. BABYLON.serialize()
  90009. ], ColorCurves.prototype, "_highlightsHue", void 0);
  90010. __decorate([
  90011. BABYLON.serialize()
  90012. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  90013. __decorate([
  90014. BABYLON.serialize()
  90015. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  90016. __decorate([
  90017. BABYLON.serialize()
  90018. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  90019. __decorate([
  90020. BABYLON.serialize()
  90021. ], ColorCurves.prototype, "_midtonesHue", void 0);
  90022. __decorate([
  90023. BABYLON.serialize()
  90024. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  90025. __decorate([
  90026. BABYLON.serialize()
  90027. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  90028. __decorate([
  90029. BABYLON.serialize()
  90030. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  90031. return ColorCurves;
  90032. }());
  90033. BABYLON.ColorCurves = ColorCurves;
  90034. })(BABYLON || (BABYLON = {}));
  90035. //# sourceMappingURL=babylon.colorCurves.js.map
  90036. var BABYLON;
  90037. (function (BABYLON) {
  90038. /**
  90039. * Post process which applies a refractin texture
  90040. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  90041. */
  90042. var RefractionPostProcess = /** @class */ (function (_super) {
  90043. __extends(RefractionPostProcess, _super);
  90044. /**
  90045. * Initializes the RefractionPostProcess
  90046. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  90047. * @param name The name of the effect.
  90048. * @param refractionTextureUrl Url of the refraction texture to use
  90049. * @param color the base color of the refraction (used to taint the rendering)
  90050. * @param depth simulated refraction depth
  90051. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  90052. * @param camera The camera to apply the render pass to.
  90053. * @param options The required width/height ratio to downsize to before computing the render pass.
  90054. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90055. * @param engine The engine which the post process will be applied. (default: current engine)
  90056. * @param reusable If the post process can be reused on the same frame. (default: false)
  90057. */
  90058. function RefractionPostProcess(name, refractionTextureUrl,
  90059. /** the base color of the refraction (used to taint the rendering) */
  90060. color,
  90061. /** simulated refraction depth */
  90062. depth,
  90063. /** the coefficient of the base color (0 to remove base color tainting) */
  90064. colorLevel, options, camera, samplingMode, engine, reusable) {
  90065. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  90066. _this.color = color;
  90067. _this.depth = depth;
  90068. _this.colorLevel = colorLevel;
  90069. _this._ownRefractionTexture = true;
  90070. _this.onActivateObservable.add(function (cam) {
  90071. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  90072. });
  90073. _this.onApplyObservable.add(function (effect) {
  90074. effect.setColor3("baseColor", _this.color);
  90075. effect.setFloat("depth", _this.depth);
  90076. effect.setFloat("colorLevel", _this.colorLevel);
  90077. effect.setTexture("refractionSampler", _this._refTexture);
  90078. });
  90079. return _this;
  90080. }
  90081. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  90082. /**
  90083. * Gets or sets the refraction texture
  90084. * Please note that you are responsible for disposing the texture if you set it manually
  90085. */
  90086. get: function () {
  90087. return this._refTexture;
  90088. },
  90089. set: function (value) {
  90090. if (this._refTexture && this._ownRefractionTexture) {
  90091. this._refTexture.dispose();
  90092. }
  90093. this._refTexture = value;
  90094. this._ownRefractionTexture = false;
  90095. },
  90096. enumerable: true,
  90097. configurable: true
  90098. });
  90099. // Methods
  90100. /**
  90101. * Disposes of the post process
  90102. * @param camera Camera to dispose post process on
  90103. */
  90104. RefractionPostProcess.prototype.dispose = function (camera) {
  90105. if (this._refTexture && this._ownRefractionTexture) {
  90106. this._refTexture.dispose();
  90107. this._refTexture = null;
  90108. }
  90109. _super.prototype.dispose.call(this, camera);
  90110. };
  90111. return RefractionPostProcess;
  90112. }(BABYLON.PostProcess));
  90113. BABYLON.RefractionPostProcess = RefractionPostProcess;
  90114. })(BABYLON || (BABYLON = {}));
  90115. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  90116. var BABYLON;
  90117. (function (BABYLON) {
  90118. /**
  90119. * Post process used to render in black and white
  90120. */
  90121. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  90122. __extends(BlackAndWhitePostProcess, _super);
  90123. /**
  90124. * Creates a black and white post process
  90125. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  90126. * @param name The name of the effect.
  90127. * @param options The required width/height ratio to downsize to before computing the render pass.
  90128. * @param camera The camera to apply the render pass to.
  90129. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90130. * @param engine The engine which the post process will be applied. (default: current engine)
  90131. * @param reusable If the post process can be reused on the same frame. (default: false)
  90132. */
  90133. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  90134. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  90135. /**
  90136. * Linear about to convert he result to black and white (default: 1)
  90137. */
  90138. _this.degree = 1;
  90139. _this.onApplyObservable.add(function (effect) {
  90140. effect.setFloat("degree", _this.degree);
  90141. });
  90142. return _this;
  90143. }
  90144. return BlackAndWhitePostProcess;
  90145. }(BABYLON.PostProcess));
  90146. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  90147. })(BABYLON || (BABYLON = {}));
  90148. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  90149. var BABYLON;
  90150. (function (BABYLON) {
  90151. /**
  90152. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  90153. * input texture to perform effects such as edge detection or sharpening
  90154. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  90155. */
  90156. var ConvolutionPostProcess = /** @class */ (function (_super) {
  90157. __extends(ConvolutionPostProcess, _super);
  90158. /**
  90159. * Creates a new instance ConvolutionPostProcess
  90160. * @param name The name of the effect.
  90161. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  90162. * @param options The required width/height ratio to downsize to before computing the render pass.
  90163. * @param camera The camera to apply the render pass to.
  90164. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90165. * @param engine The engine which the post process will be applied. (default: current engine)
  90166. * @param reusable If the post process can be reused on the same frame. (default: false)
  90167. * @param textureType Type of textures used when performing the post process. (default: 0)
  90168. */
  90169. function ConvolutionPostProcess(name,
  90170. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  90171. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  90172. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90173. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  90174. _this.kernel = kernel;
  90175. _this.onApply = function (effect) {
  90176. effect.setFloat2("screenSize", _this.width, _this.height);
  90177. effect.setArray("kernel", _this.kernel);
  90178. };
  90179. return _this;
  90180. }
  90181. // Statics
  90182. /**
  90183. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90184. */
  90185. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  90186. /**
  90187. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90188. */
  90189. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  90190. /**
  90191. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90192. */
  90193. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  90194. /**
  90195. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90196. */
  90197. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  90198. /**
  90199. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90200. */
  90201. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  90202. /**
  90203. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90204. */
  90205. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  90206. return ConvolutionPostProcess;
  90207. }(BABYLON.PostProcess));
  90208. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  90209. })(BABYLON || (BABYLON = {}));
  90210. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  90211. var BABYLON;
  90212. (function (BABYLON) {
  90213. /**
  90214. * Applies a kernel filter to the image
  90215. */
  90216. var FilterPostProcess = /** @class */ (function (_super) {
  90217. __extends(FilterPostProcess, _super);
  90218. /**
  90219. *
  90220. * @param name The name of the effect.
  90221. * @param kernelMatrix The matrix to be applied to the image
  90222. * @param options The required width/height ratio to downsize to before computing the render pass.
  90223. * @param camera The camera to apply the render pass to.
  90224. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90225. * @param engine The engine which the post process will be applied. (default: current engine)
  90226. * @param reusable If the post process can be reused on the same frame. (default: false)
  90227. */
  90228. function FilterPostProcess(name,
  90229. /** The matrix to be applied to the image */
  90230. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  90231. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  90232. _this.kernelMatrix = kernelMatrix;
  90233. _this.onApply = function (effect) {
  90234. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  90235. };
  90236. return _this;
  90237. }
  90238. return FilterPostProcess;
  90239. }(BABYLON.PostProcess));
  90240. BABYLON.FilterPostProcess = FilterPostProcess;
  90241. })(BABYLON || (BABYLON = {}));
  90242. //# sourceMappingURL=babylon.filterPostProcess.js.map
  90243. var BABYLON;
  90244. (function (BABYLON) {
  90245. /**
  90246. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  90247. */
  90248. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  90249. __extends(VolumetricLightScatteringPostProcess, _super);
  90250. /**
  90251. * @constructor
  90252. * @param name The post-process name
  90253. * @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)
  90254. * @param camera The camera that the post-process will be attached to
  90255. * @param mesh The mesh used to create the light scattering
  90256. * @param samples The post-process quality, default 100
  90257. * @param samplingModeThe post-process filtering mode
  90258. * @param engine The babylon engine
  90259. * @param reusable If the post-process is reusable
  90260. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  90261. */
  90262. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  90263. if (samples === void 0) { samples = 100; }
  90264. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90265. 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;
  90266. _this._screenCoordinates = BABYLON.Vector2.Zero();
  90267. /**
  90268. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  90269. */
  90270. _this.customMeshPosition = BABYLON.Vector3.Zero();
  90271. /**
  90272. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  90273. */
  90274. _this.useCustomMeshPosition = false;
  90275. /**
  90276. * If the post-process should inverse the light scattering direction
  90277. */
  90278. _this.invert = true;
  90279. /**
  90280. * Array containing the excluded meshes not rendered in the internal pass
  90281. */
  90282. _this.excludedMeshes = new Array();
  90283. /**
  90284. * Controls the overall intensity of the post-process
  90285. */
  90286. _this.exposure = 0.3;
  90287. /**
  90288. * Dissipates each sample's contribution in range [0, 1]
  90289. */
  90290. _this.decay = 0.96815;
  90291. /**
  90292. * Controls the overall intensity of each sample
  90293. */
  90294. _this.weight = 0.58767;
  90295. /**
  90296. * Controls the density of each sample
  90297. */
  90298. _this.density = 0.926;
  90299. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  90300. engine = scene.getEngine();
  90301. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  90302. // Configure mesh
  90303. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  90304. // Configure
  90305. _this._createPass(scene, ratio.passRatio || ratio);
  90306. _this.onActivate = function (camera) {
  90307. if (!_this.isSupported) {
  90308. _this.dispose(camera);
  90309. }
  90310. _this.onActivate = null;
  90311. };
  90312. _this.onApplyObservable.add(function (effect) {
  90313. _this._updateMeshScreenCoordinates(scene);
  90314. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  90315. effect.setFloat("exposure", _this.exposure);
  90316. effect.setFloat("decay", _this.decay);
  90317. effect.setFloat("weight", _this.weight);
  90318. effect.setFloat("density", _this.density);
  90319. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  90320. });
  90321. return _this;
  90322. }
  90323. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  90324. /**
  90325. * @hidden
  90326. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  90327. */
  90328. get: function () {
  90329. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  90330. return false;
  90331. },
  90332. set: function (useDiffuseColor) {
  90333. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  90334. },
  90335. enumerable: true,
  90336. configurable: true
  90337. });
  90338. /**
  90339. * Returns the string "VolumetricLightScatteringPostProcess"
  90340. * @returns "VolumetricLightScatteringPostProcess"
  90341. */
  90342. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  90343. return "VolumetricLightScatteringPostProcess";
  90344. };
  90345. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  90346. var mesh = subMesh.getMesh();
  90347. // Render this.mesh as default
  90348. if (mesh === this.mesh && mesh.material) {
  90349. return mesh.material.isReady(mesh);
  90350. }
  90351. var defines = [];
  90352. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90353. var material = subMesh.getMaterial();
  90354. // Alpha test
  90355. if (material) {
  90356. if (material.needAlphaTesting()) {
  90357. defines.push("#define ALPHATEST");
  90358. }
  90359. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90360. attribs.push(BABYLON.VertexBuffer.UVKind);
  90361. defines.push("#define UV1");
  90362. }
  90363. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90364. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90365. defines.push("#define UV2");
  90366. }
  90367. }
  90368. // Bones
  90369. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90370. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90371. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90372. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90373. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  90374. }
  90375. else {
  90376. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90377. }
  90378. // Instances
  90379. if (useInstances) {
  90380. defines.push("#define INSTANCES");
  90381. attribs.push("world0");
  90382. attribs.push("world1");
  90383. attribs.push("world2");
  90384. attribs.push("world3");
  90385. }
  90386. // Get correct effect
  90387. var join = defines.join("\n");
  90388. if (this._cachedDefines !== join) {
  90389. this._cachedDefines = join;
  90390. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  90391. }
  90392. return this._volumetricLightScatteringPass.isReady();
  90393. };
  90394. /**
  90395. * Sets the new light position for light scattering effect
  90396. * @param position The new custom light position
  90397. */
  90398. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  90399. this.customMeshPosition = position;
  90400. };
  90401. /**
  90402. * Returns the light position for light scattering effect
  90403. * @return Vector3 The custom light position
  90404. */
  90405. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  90406. return this.customMeshPosition;
  90407. };
  90408. /**
  90409. * Disposes the internal assets and detaches the post-process from the camera
  90410. */
  90411. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  90412. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  90413. if (rttIndex !== -1) {
  90414. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  90415. }
  90416. this._volumetricLightScatteringRTT.dispose();
  90417. _super.prototype.dispose.call(this, camera);
  90418. };
  90419. /**
  90420. * Returns the render target texture used by the post-process
  90421. * @return the render target texture used by the post-process
  90422. */
  90423. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  90424. return this._volumetricLightScatteringRTT;
  90425. };
  90426. // Private methods
  90427. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  90428. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  90429. return true;
  90430. }
  90431. return false;
  90432. };
  90433. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  90434. var _this = this;
  90435. var engine = scene.getEngine();
  90436. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  90437. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90438. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90439. this._volumetricLightScatteringRTT.renderList = null;
  90440. this._volumetricLightScatteringRTT.renderParticles = false;
  90441. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  90442. var camera = this.getCamera();
  90443. if (camera) {
  90444. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  90445. }
  90446. else {
  90447. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  90448. }
  90449. // Custom render function for submeshes
  90450. var renderSubMesh = function (subMesh) {
  90451. var mesh = subMesh.getRenderingMesh();
  90452. if (_this._meshExcluded(mesh)) {
  90453. return;
  90454. }
  90455. var material = subMesh.getMaterial();
  90456. if (!material) {
  90457. return;
  90458. }
  90459. var scene = mesh.getScene();
  90460. var engine = scene.getEngine();
  90461. // Culling
  90462. engine.setState(material.backFaceCulling);
  90463. // Managing instances
  90464. var batch = mesh._getInstancesRenderList(subMesh._id);
  90465. if (batch.mustReturn) {
  90466. return;
  90467. }
  90468. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  90469. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  90470. var effect = _this._volumetricLightScatteringPass;
  90471. if (mesh === _this.mesh) {
  90472. if (subMesh.effect) {
  90473. effect = subMesh.effect;
  90474. }
  90475. else {
  90476. effect = material.getEffect();
  90477. }
  90478. }
  90479. engine.enableEffect(effect);
  90480. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  90481. if (mesh === _this.mesh) {
  90482. material.bind(mesh.getWorldMatrix(), mesh);
  90483. }
  90484. else {
  90485. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  90486. // Alpha test
  90487. if (material && material.needAlphaTesting()) {
  90488. var alphaTexture = material.getAlphaTestTexture();
  90489. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  90490. if (alphaTexture) {
  90491. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90492. }
  90493. }
  90494. // Bones
  90495. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90496. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90497. }
  90498. }
  90499. // Draw
  90500. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  90501. }
  90502. };
  90503. // Render target texture callbacks
  90504. var savedSceneClearColor;
  90505. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  90506. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  90507. savedSceneClearColor = scene.clearColor;
  90508. scene.clearColor = sceneClearColor;
  90509. });
  90510. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  90511. scene.clearColor = savedSceneClearColor;
  90512. });
  90513. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  90514. var engine = scene.getEngine();
  90515. var index;
  90516. if (depthOnlySubMeshes.length) {
  90517. engine.setColorWrite(false);
  90518. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  90519. renderSubMesh(depthOnlySubMeshes.data[index]);
  90520. }
  90521. engine.setColorWrite(true);
  90522. }
  90523. for (index = 0; index < opaqueSubMeshes.length; index++) {
  90524. renderSubMesh(opaqueSubMeshes.data[index]);
  90525. }
  90526. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  90527. renderSubMesh(alphaTestSubMeshes.data[index]);
  90528. }
  90529. if (transparentSubMeshes.length) {
  90530. // Sort sub meshes
  90531. for (index = 0; index < transparentSubMeshes.length; index++) {
  90532. var submesh = transparentSubMeshes.data[index];
  90533. var boundingInfo = submesh.getBoundingInfo();
  90534. if (boundingInfo && scene.activeCamera) {
  90535. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  90536. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  90537. }
  90538. }
  90539. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  90540. sortedArray.sort(function (a, b) {
  90541. // Alpha index first
  90542. if (a._alphaIndex > b._alphaIndex) {
  90543. return 1;
  90544. }
  90545. if (a._alphaIndex < b._alphaIndex) {
  90546. return -1;
  90547. }
  90548. // Then distance to camera
  90549. if (a._distanceToCamera < b._distanceToCamera) {
  90550. return 1;
  90551. }
  90552. if (a._distanceToCamera > b._distanceToCamera) {
  90553. return -1;
  90554. }
  90555. return 0;
  90556. });
  90557. // Render sub meshes
  90558. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  90559. for (index = 0; index < sortedArray.length; index++) {
  90560. renderSubMesh(sortedArray[index]);
  90561. }
  90562. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  90563. }
  90564. };
  90565. };
  90566. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  90567. var transform = scene.getTransformMatrix();
  90568. var meshPosition;
  90569. if (this.useCustomMeshPosition) {
  90570. meshPosition = this.customMeshPosition;
  90571. }
  90572. else if (this.attachedNode) {
  90573. meshPosition = this.attachedNode.position;
  90574. }
  90575. else {
  90576. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  90577. }
  90578. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  90579. this._screenCoordinates.x = pos.x / this._viewPort.width;
  90580. this._screenCoordinates.y = pos.y / this._viewPort.height;
  90581. if (this.invert) {
  90582. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  90583. }
  90584. };
  90585. // Static methods
  90586. /**
  90587. * Creates a default mesh for the Volumeric Light Scattering post-process
  90588. * @param name The mesh name
  90589. * @param scene The scene where to create the mesh
  90590. * @return the default mesh
  90591. */
  90592. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  90593. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  90594. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  90595. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  90596. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  90597. mesh.material = material;
  90598. return mesh;
  90599. };
  90600. __decorate([
  90601. BABYLON.serializeAsVector3()
  90602. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  90603. __decorate([
  90604. BABYLON.serialize()
  90605. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  90606. __decorate([
  90607. BABYLON.serialize()
  90608. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  90609. __decorate([
  90610. BABYLON.serializeAsMeshReference()
  90611. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  90612. __decorate([
  90613. BABYLON.serialize()
  90614. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  90615. __decorate([
  90616. BABYLON.serialize()
  90617. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  90618. __decorate([
  90619. BABYLON.serialize()
  90620. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  90621. __decorate([
  90622. BABYLON.serialize()
  90623. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  90624. __decorate([
  90625. BABYLON.serialize()
  90626. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  90627. return VolumetricLightScatteringPostProcess;
  90628. }(BABYLON.PostProcess));
  90629. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  90630. })(BABYLON || (BABYLON = {}));
  90631. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  90632. var BABYLON;
  90633. (function (BABYLON) {
  90634. /**
  90635. *
  90636. * This post-process allows the modification of rendered colors by using
  90637. * a 'look-up table' (LUT). This effect is also called Color Grading.
  90638. *
  90639. * The object needs to be provided an url to a texture containing the color
  90640. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  90641. * Use an image editing software to tweak the LUT to match your needs.
  90642. *
  90643. * For an example of a color LUT, see here:
  90644. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  90645. * For explanations on color grading, see here:
  90646. * @see http://udn.epicgames.com/Three/ColorGrading.html
  90647. *
  90648. */
  90649. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  90650. __extends(ColorCorrectionPostProcess, _super);
  90651. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  90652. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  90653. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  90654. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  90655. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90656. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90657. _this.onApply = function (effect) {
  90658. effect.setTexture("colorTable", _this._colorTableTexture);
  90659. };
  90660. return _this;
  90661. }
  90662. return ColorCorrectionPostProcess;
  90663. }(BABYLON.PostProcess));
  90664. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  90665. })(BABYLON || (BABYLON = {}));
  90666. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  90667. var BABYLON;
  90668. (function (BABYLON) {
  90669. /** Defines operator used for tonemapping */
  90670. var TonemappingOperator;
  90671. (function (TonemappingOperator) {
  90672. /** Hable */
  90673. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  90674. /** Reinhard */
  90675. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  90676. /** HejiDawson */
  90677. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  90678. /** Photographic */
  90679. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  90680. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  90681. /**
  90682. * Defines a post process to apply tone mapping
  90683. */
  90684. var TonemapPostProcess = /** @class */ (function (_super) {
  90685. __extends(TonemapPostProcess, _super);
  90686. /**
  90687. * Creates a new TonemapPostProcess
  90688. * @param name defines the name of the postprocess
  90689. * @param _operator defines the operator to use
  90690. * @param exposureAdjustment defines the required exposure adjustement
  90691. * @param camera defines the camera to use (can be null)
  90692. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  90693. * @param engine defines the hosting engine (can be ignore if camera is set)
  90694. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  90695. */
  90696. function TonemapPostProcess(name, _operator,
  90697. /** Defines the required exposure adjustement */
  90698. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  90699. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90700. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90701. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  90702. _this._operator = _operator;
  90703. _this.exposureAdjustment = exposureAdjustment;
  90704. var defines = "#define ";
  90705. if (_this._operator === TonemappingOperator.Hable) {
  90706. defines += "HABLE_TONEMAPPING";
  90707. }
  90708. else if (_this._operator === TonemappingOperator.Reinhard) {
  90709. defines += "REINHARD_TONEMAPPING";
  90710. }
  90711. else if (_this._operator === TonemappingOperator.HejiDawson) {
  90712. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  90713. }
  90714. else if (_this._operator === TonemappingOperator.Photographic) {
  90715. defines += "PHOTOGRAPHIC_TONEMAPPING";
  90716. }
  90717. //sadly a second call to create the effect.
  90718. _this.updateEffect(defines);
  90719. _this.onApply = function (effect) {
  90720. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  90721. };
  90722. return _this;
  90723. }
  90724. return TonemapPostProcess;
  90725. }(BABYLON.PostProcess));
  90726. BABYLON.TonemapPostProcess = TonemapPostProcess;
  90727. })(BABYLON || (BABYLON = {}));
  90728. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  90729. var BABYLON;
  90730. (function (BABYLON) {
  90731. /**
  90732. * DisplayPassPostProcess which produces an output the same as it's input
  90733. */
  90734. var DisplayPassPostProcess = /** @class */ (function (_super) {
  90735. __extends(DisplayPassPostProcess, _super);
  90736. /**
  90737. * Creates the DisplayPassPostProcess
  90738. * @param name The name of the effect.
  90739. * @param options The required width/height ratio to downsize to before computing the render pass.
  90740. * @param camera The camera to apply the render pass to.
  90741. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90742. * @param engine The engine which the post process will be applied. (default: current engine)
  90743. * @param reusable If the post process can be reused on the same frame. (default: false)
  90744. */
  90745. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  90746. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  90747. }
  90748. return DisplayPassPostProcess;
  90749. }(BABYLON.PostProcess));
  90750. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  90751. })(BABYLON || (BABYLON = {}));
  90752. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  90753. var BABYLON;
  90754. (function (BABYLON) {
  90755. /**
  90756. * Extracts highlights from the image
  90757. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  90758. */
  90759. var HighlightsPostProcess = /** @class */ (function (_super) {
  90760. __extends(HighlightsPostProcess, _super);
  90761. /**
  90762. * Extracts highlights from the image
  90763. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  90764. * @param name The name of the effect.
  90765. * @param options The required width/height ratio to downsize to before computing the render pass.
  90766. * @param camera The camera to apply the render pass to.
  90767. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90768. * @param engine The engine which the post process will be applied. (default: current engine)
  90769. * @param reusable If the post process can be reused on the same frame. (default: false)
  90770. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  90771. */
  90772. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  90773. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90774. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  90775. }
  90776. return HighlightsPostProcess;
  90777. }(BABYLON.PostProcess));
  90778. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  90779. })(BABYLON || (BABYLON = {}));
  90780. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  90781. var BABYLON;
  90782. (function (BABYLON) {
  90783. /**
  90784. * ImageProcessingPostProcess
  90785. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  90786. */
  90787. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  90788. __extends(ImageProcessingPostProcess, _super);
  90789. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  90790. if (camera === void 0) { camera = null; }
  90791. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90792. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  90793. _this._fromLinearSpace = true;
  90794. /**
  90795. * Defines cache preventing GC.
  90796. */
  90797. _this._defines = {
  90798. IMAGEPROCESSING: false,
  90799. VIGNETTE: false,
  90800. VIGNETTEBLENDMODEMULTIPLY: false,
  90801. VIGNETTEBLENDMODEOPAQUE: false,
  90802. TONEMAPPING: false,
  90803. TONEMAPPING_ACES: false,
  90804. CONTRAST: false,
  90805. COLORCURVES: false,
  90806. COLORGRADING: false,
  90807. COLORGRADING3D: false,
  90808. FROMLINEARSPACE: false,
  90809. SAMPLER3DGREENDEPTH: false,
  90810. SAMPLER3DBGRMAP: false,
  90811. IMAGEPROCESSINGPOSTPROCESS: false,
  90812. EXPOSURE: false,
  90813. };
  90814. // Setup the configuration as forced by the constructor. This would then not force the
  90815. // scene materials output in linear space and let untouched the default forward pass.
  90816. if (imageProcessingConfiguration) {
  90817. imageProcessingConfiguration.applyByPostProcess = true;
  90818. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  90819. // This will cause the shader to be compiled
  90820. _this.fromLinearSpace = false;
  90821. }
  90822. // Setup the default processing configuration to the scene.
  90823. else {
  90824. _this._attachImageProcessingConfiguration(null, true);
  90825. _this.imageProcessingConfiguration.applyByPostProcess = true;
  90826. }
  90827. _this.onApply = function (effect) {
  90828. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  90829. };
  90830. return _this;
  90831. }
  90832. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  90833. /**
  90834. * Gets the image processing configuration used either in this material.
  90835. */
  90836. get: function () {
  90837. return this._imageProcessingConfiguration;
  90838. },
  90839. /**
  90840. * Sets the Default image processing configuration used either in the this material.
  90841. *
  90842. * If sets to null, the scene one is in use.
  90843. */
  90844. set: function (value) {
  90845. this._attachImageProcessingConfiguration(value);
  90846. },
  90847. enumerable: true,
  90848. configurable: true
  90849. });
  90850. /**
  90851. * Attaches a new image processing configuration to the PBR Material.
  90852. * @param configuration
  90853. */
  90854. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  90855. var _this = this;
  90856. if (doNotBuild === void 0) { doNotBuild = false; }
  90857. if (configuration === this._imageProcessingConfiguration) {
  90858. return;
  90859. }
  90860. // Detaches observer.
  90861. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90862. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90863. }
  90864. // Pick the scene configuration if needed.
  90865. if (!configuration) {
  90866. var scene = null;
  90867. var engine = this.getEngine();
  90868. var camera = this.getCamera();
  90869. if (camera) {
  90870. scene = camera.getScene();
  90871. }
  90872. else if (engine && engine.scenes) {
  90873. var scenes = engine.scenes;
  90874. scene = scenes[scenes.length - 1];
  90875. }
  90876. else {
  90877. scene = BABYLON.Engine.LastCreatedScene;
  90878. }
  90879. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  90880. }
  90881. else {
  90882. this._imageProcessingConfiguration = configuration;
  90883. }
  90884. // Attaches observer.
  90885. if (this._imageProcessingConfiguration) {
  90886. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  90887. _this._updateParameters();
  90888. });
  90889. }
  90890. // Ensure the effect will be rebuilt.
  90891. if (!doNotBuild) {
  90892. this._updateParameters();
  90893. }
  90894. };
  90895. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  90896. /**
  90897. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  90898. */
  90899. get: function () {
  90900. return this.imageProcessingConfiguration.colorCurves;
  90901. },
  90902. /**
  90903. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  90904. */
  90905. set: function (value) {
  90906. this.imageProcessingConfiguration.colorCurves = value;
  90907. },
  90908. enumerable: true,
  90909. configurable: true
  90910. });
  90911. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  90912. /**
  90913. * Gets wether the color curves effect is enabled.
  90914. */
  90915. get: function () {
  90916. return this.imageProcessingConfiguration.colorCurvesEnabled;
  90917. },
  90918. /**
  90919. * Sets wether the color curves effect is enabled.
  90920. */
  90921. set: function (value) {
  90922. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  90923. },
  90924. enumerable: true,
  90925. configurable: true
  90926. });
  90927. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  90928. /**
  90929. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  90930. */
  90931. get: function () {
  90932. return this.imageProcessingConfiguration.colorGradingTexture;
  90933. },
  90934. /**
  90935. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  90936. */
  90937. set: function (value) {
  90938. this.imageProcessingConfiguration.colorGradingTexture = value;
  90939. },
  90940. enumerable: true,
  90941. configurable: true
  90942. });
  90943. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  90944. /**
  90945. * Gets wether the color grading effect is enabled.
  90946. */
  90947. get: function () {
  90948. return this.imageProcessingConfiguration.colorGradingEnabled;
  90949. },
  90950. /**
  90951. * Gets wether the color grading effect is enabled.
  90952. */
  90953. set: function (value) {
  90954. this.imageProcessingConfiguration.colorGradingEnabled = value;
  90955. },
  90956. enumerable: true,
  90957. configurable: true
  90958. });
  90959. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  90960. /**
  90961. * Gets exposure used in the effect.
  90962. */
  90963. get: function () {
  90964. return this.imageProcessingConfiguration.exposure;
  90965. },
  90966. /**
  90967. * Sets exposure used in the effect.
  90968. */
  90969. set: function (value) {
  90970. this.imageProcessingConfiguration.exposure = value;
  90971. },
  90972. enumerable: true,
  90973. configurable: true
  90974. });
  90975. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  90976. /**
  90977. * Gets wether tonemapping is enabled or not.
  90978. */
  90979. get: function () {
  90980. return this._imageProcessingConfiguration.toneMappingEnabled;
  90981. },
  90982. /**
  90983. * Sets wether tonemapping is enabled or not
  90984. */
  90985. set: function (value) {
  90986. this._imageProcessingConfiguration.toneMappingEnabled = value;
  90987. },
  90988. enumerable: true,
  90989. configurable: true
  90990. });
  90991. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  90992. /**
  90993. * Gets contrast used in the effect.
  90994. */
  90995. get: function () {
  90996. return this.imageProcessingConfiguration.contrast;
  90997. },
  90998. /**
  90999. * Sets contrast used in the effect.
  91000. */
  91001. set: function (value) {
  91002. this.imageProcessingConfiguration.contrast = value;
  91003. },
  91004. enumerable: true,
  91005. configurable: true
  91006. });
  91007. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  91008. /**
  91009. * Gets Vignette stretch size.
  91010. */
  91011. get: function () {
  91012. return this.imageProcessingConfiguration.vignetteStretch;
  91013. },
  91014. /**
  91015. * Sets Vignette stretch size.
  91016. */
  91017. set: function (value) {
  91018. this.imageProcessingConfiguration.vignetteStretch = value;
  91019. },
  91020. enumerable: true,
  91021. configurable: true
  91022. });
  91023. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  91024. /**
  91025. * Gets Vignette centre X Offset.
  91026. */
  91027. get: function () {
  91028. return this.imageProcessingConfiguration.vignetteCentreX;
  91029. },
  91030. /**
  91031. * Sets Vignette centre X Offset.
  91032. */
  91033. set: function (value) {
  91034. this.imageProcessingConfiguration.vignetteCentreX = value;
  91035. },
  91036. enumerable: true,
  91037. configurable: true
  91038. });
  91039. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  91040. /**
  91041. * Gets Vignette centre Y Offset.
  91042. */
  91043. get: function () {
  91044. return this.imageProcessingConfiguration.vignetteCentreY;
  91045. },
  91046. /**
  91047. * Sets Vignette centre Y Offset.
  91048. */
  91049. set: function (value) {
  91050. this.imageProcessingConfiguration.vignetteCentreY = value;
  91051. },
  91052. enumerable: true,
  91053. configurable: true
  91054. });
  91055. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  91056. /**
  91057. * Gets Vignette weight or intensity of the vignette effect.
  91058. */
  91059. get: function () {
  91060. return this.imageProcessingConfiguration.vignetteWeight;
  91061. },
  91062. /**
  91063. * Sets Vignette weight or intensity of the vignette effect.
  91064. */
  91065. set: function (value) {
  91066. this.imageProcessingConfiguration.vignetteWeight = value;
  91067. },
  91068. enumerable: true,
  91069. configurable: true
  91070. });
  91071. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  91072. /**
  91073. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  91074. * if vignetteEnabled is set to true.
  91075. */
  91076. get: function () {
  91077. return this.imageProcessingConfiguration.vignetteColor;
  91078. },
  91079. /**
  91080. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  91081. * if vignetteEnabled is set to true.
  91082. */
  91083. set: function (value) {
  91084. this.imageProcessingConfiguration.vignetteColor = value;
  91085. },
  91086. enumerable: true,
  91087. configurable: true
  91088. });
  91089. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  91090. /**
  91091. * Gets Camera field of view used by the Vignette effect.
  91092. */
  91093. get: function () {
  91094. return this.imageProcessingConfiguration.vignetteCameraFov;
  91095. },
  91096. /**
  91097. * Sets Camera field of view used by the Vignette effect.
  91098. */
  91099. set: function (value) {
  91100. this.imageProcessingConfiguration.vignetteCameraFov = value;
  91101. },
  91102. enumerable: true,
  91103. configurable: true
  91104. });
  91105. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  91106. /**
  91107. * Gets the vignette blend mode allowing different kind of effect.
  91108. */
  91109. get: function () {
  91110. return this.imageProcessingConfiguration.vignetteBlendMode;
  91111. },
  91112. /**
  91113. * Sets the vignette blend mode allowing different kind of effect.
  91114. */
  91115. set: function (value) {
  91116. this.imageProcessingConfiguration.vignetteBlendMode = value;
  91117. },
  91118. enumerable: true,
  91119. configurable: true
  91120. });
  91121. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  91122. /**
  91123. * Gets wether the vignette effect is enabled.
  91124. */
  91125. get: function () {
  91126. return this.imageProcessingConfiguration.vignetteEnabled;
  91127. },
  91128. /**
  91129. * Sets wether the vignette effect is enabled.
  91130. */
  91131. set: function (value) {
  91132. this.imageProcessingConfiguration.vignetteEnabled = value;
  91133. },
  91134. enumerable: true,
  91135. configurable: true
  91136. });
  91137. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  91138. /**
  91139. * Gets wether the input of the processing is in Gamma or Linear Space.
  91140. */
  91141. get: function () {
  91142. return this._fromLinearSpace;
  91143. },
  91144. /**
  91145. * Sets wether the input of the processing is in Gamma or Linear Space.
  91146. */
  91147. set: function (value) {
  91148. if (this._fromLinearSpace === value) {
  91149. return;
  91150. }
  91151. this._fromLinearSpace = value;
  91152. this._updateParameters();
  91153. },
  91154. enumerable: true,
  91155. configurable: true
  91156. });
  91157. /**
  91158. * "ImageProcessingPostProcess"
  91159. * @returns "ImageProcessingPostProcess"
  91160. */
  91161. ImageProcessingPostProcess.prototype.getClassName = function () {
  91162. return "ImageProcessingPostProcess";
  91163. };
  91164. ImageProcessingPostProcess.prototype._updateParameters = function () {
  91165. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  91166. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  91167. var defines = "";
  91168. for (var define in this._defines) {
  91169. if (this._defines[define]) {
  91170. defines += "#define " + define + ";\r\n";
  91171. }
  91172. }
  91173. var samplers = ["textureSampler"];
  91174. var uniforms = ["scale"];
  91175. if (BABYLON.ImageProcessingConfiguration) {
  91176. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  91177. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  91178. }
  91179. this.updateEffect(defines, uniforms, samplers);
  91180. };
  91181. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  91182. _super.prototype.dispose.call(this, camera);
  91183. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91184. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91185. }
  91186. if (this._imageProcessingConfiguration) {
  91187. this.imageProcessingConfiguration.applyByPostProcess = false;
  91188. }
  91189. };
  91190. __decorate([
  91191. BABYLON.serialize()
  91192. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  91193. return ImageProcessingPostProcess;
  91194. }(BABYLON.PostProcess));
  91195. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  91196. })(BABYLON || (BABYLON = {}));
  91197. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  91198. var BABYLON;
  91199. (function (BABYLON) {
  91200. /**
  91201. * The Motion Blur Post Process which blurs an image based on the objects velocity in scene.
  91202. * Velocity can be affected by each object's rotation, position and scale depending on the transformation speed.
  91203. * As an example, all you have to do is to create the post-process:
  91204. * var mb = new BABYLON.MotionBlurPostProcess(
  91205. * 'mb', // The name of the effect.
  91206. * scene, // The scene containing the objects to blur according to their velocity.
  91207. * 1.0, // The required width/height ratio to downsize to before computing the render pass.
  91208. * camera // The camera to apply the render pass to.
  91209. * );
  91210. * Then, all objects moving, rotating and/or scaling will be blurred depending on the transformation speed.
  91211. */
  91212. var MotionBlurPostProcess = /** @class */ (function (_super) {
  91213. __extends(MotionBlurPostProcess, _super);
  91214. /**
  91215. * Creates a new instance MotionBlurPostProcess
  91216. * @param name The name of the effect.
  91217. * @param scene The scene containing the objects to blur according to their velocity.
  91218. * @param options The required width/height ratio to downsize to before computing the render pass.
  91219. * @param camera The camera to apply the render pass to.
  91220. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  91221. * @param engine The engine which the post process will be applied. (default: current engine)
  91222. * @param reusable If the post process can be reused on the same frame. (default: false)
  91223. * @param textureType Type of textures used when performing the post process. (default: 0)
  91224. * @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)
  91225. */
  91226. function MotionBlurPostProcess(name, scene, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  91227. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  91228. if (blockCompilation === void 0) { blockCompilation = false; }
  91229. 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;
  91230. /**
  91231. * Defines how much the image is blurred by the movement. Default value is equal to 1
  91232. */
  91233. _this.motionStrength = 1;
  91234. _this._motionBlurSamples = 32;
  91235. _this._geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  91236. if (!_this._geometryBufferRenderer) {
  91237. // Geometry buffer renderer is not supported. So, work as a passthrough.
  91238. BABYLON.Tools.Warn("Multiple Render Target support needed to compute object based motion blur");
  91239. _this.updateEffect();
  91240. }
  91241. else {
  91242. // Geometry buffer renderer is supported.
  91243. _this._geometryBufferRenderer.enableVelocity = true;
  91244. _this.onApply = function (effect) {
  91245. effect.setVector2("screenSize", new BABYLON.Vector2(_this.width, _this.height));
  91246. effect.setFloat("motionScale", scene.getAnimationRatio());
  91247. effect.setFloat("motionStrength", _this.motionStrength);
  91248. if (_this._geometryBufferRenderer) {
  91249. var velocityIndex = _this._geometryBufferRenderer.getTextureIndex(BABYLON.GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE);
  91250. effect.setTexture("velocitySampler", _this._geometryBufferRenderer.getGBuffer().textures[velocityIndex]);
  91251. }
  91252. };
  91253. }
  91254. return _this;
  91255. }
  91256. Object.defineProperty(MotionBlurPostProcess.prototype, "motionBlurSamples", {
  91257. /**
  91258. * Gets the number of iterations are used for motion blur quality. Default value is equal to 32
  91259. */
  91260. get: function () {
  91261. return this._motionBlurSamples;
  91262. },
  91263. /**
  91264. * Sets the number of iterations to be used for motion blur quality
  91265. */
  91266. set: function (samples) {
  91267. this._motionBlurSamples = samples;
  91268. if (this._geometryBufferRenderer) {
  91269. this.updateEffect("#define GEOMETRY_SUPPORTED\n#define SAMPLES " + samples.toFixed(1));
  91270. }
  91271. },
  91272. enumerable: true,
  91273. configurable: true
  91274. });
  91275. /**
  91276. * Disposes the post process.
  91277. * @param camera The camera to dispose the post process on.
  91278. */
  91279. MotionBlurPostProcess.prototype.dispose = function (camera) {
  91280. if (this._geometryBufferRenderer) {
  91281. // Clear previous transformation matrices dictionary used to compute objects velocities
  91282. this._geometryBufferRenderer._previousTransformationMatrices = {};
  91283. }
  91284. _super.prototype.dispose.call(this, camera);
  91285. };
  91286. return MotionBlurPostProcess;
  91287. }(BABYLON.PostProcess));
  91288. BABYLON.MotionBlurPostProcess = MotionBlurPostProcess;
  91289. })(BABYLON || (BABYLON = {}));
  91290. //# sourceMappingURL=babylon.motionBlurPostProcess.js.map
  91291. var BABYLON;
  91292. (function (BABYLON) {
  91293. /**
  91294. * Class used to store bone information
  91295. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  91296. */
  91297. var Bone = /** @class */ (function (_super) {
  91298. __extends(Bone, _super);
  91299. /**
  91300. * Create a new bone
  91301. * @param name defines the bone name
  91302. * @param skeleton defines the parent skeleton
  91303. * @param parentBone defines the parent (can be null if the bone is the root)
  91304. * @param localMatrix defines the local matrix
  91305. * @param restPose defines the rest pose matrix
  91306. * @param baseMatrix defines the base matrix
  91307. * @param index defines index of the bone in the hiearchy
  91308. */
  91309. function Bone(
  91310. /**
  91311. * defines the bone name
  91312. */
  91313. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  91314. if (parentBone === void 0) { parentBone = null; }
  91315. if (localMatrix === void 0) { localMatrix = null; }
  91316. if (restPose === void 0) { restPose = null; }
  91317. if (baseMatrix === void 0) { baseMatrix = null; }
  91318. if (index === void 0) { index = null; }
  91319. var _this = _super.call(this, name, skeleton.getScene()) || this;
  91320. _this.name = name;
  91321. /**
  91322. * Gets the list of child bones
  91323. */
  91324. _this.children = new Array();
  91325. /** Gets the animations associated with this bone */
  91326. _this.animations = new Array();
  91327. /**
  91328. * @hidden Internal only
  91329. * Set this value to map this bone to a different index in the transform matrices
  91330. * Set this value to -1 to exclude the bone from the transform matrices
  91331. */
  91332. _this._index = null;
  91333. _this._absoluteTransform = new BABYLON.Matrix();
  91334. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  91335. _this._scalingDeterminant = 1;
  91336. _this._worldTransform = new BABYLON.Matrix();
  91337. _this._needToDecompose = true;
  91338. _this._needToCompose = false;
  91339. _this._skeleton = skeleton;
  91340. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  91341. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  91342. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  91343. _this._index = index;
  91344. skeleton.bones.push(_this);
  91345. _this.setParent(parentBone, false);
  91346. if (baseMatrix || localMatrix) {
  91347. _this._updateDifferenceMatrix();
  91348. }
  91349. return _this;
  91350. }
  91351. Object.defineProperty(Bone.prototype, "_matrix", {
  91352. /** @hidden */
  91353. get: function () {
  91354. this._compose();
  91355. return this._localMatrix;
  91356. },
  91357. /** @hidden */
  91358. set: function (value) {
  91359. this._localMatrix.copyFrom(value);
  91360. this._needToDecompose = true;
  91361. },
  91362. enumerable: true,
  91363. configurable: true
  91364. });
  91365. // Members
  91366. /**
  91367. * Gets the parent skeleton
  91368. * @returns a skeleton
  91369. */
  91370. Bone.prototype.getSkeleton = function () {
  91371. return this._skeleton;
  91372. };
  91373. /**
  91374. * Gets parent bone
  91375. * @returns a bone or null if the bone is the root of the bone hierarchy
  91376. */
  91377. Bone.prototype.getParent = function () {
  91378. return this._parent;
  91379. };
  91380. /**
  91381. * Sets the parent bone
  91382. * @param parent defines the parent (can be null if the bone is the root)
  91383. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  91384. */
  91385. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  91386. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  91387. if (this._parent === parent) {
  91388. return;
  91389. }
  91390. if (this._parent) {
  91391. var index = this._parent.children.indexOf(this);
  91392. if (index !== -1) {
  91393. this._parent.children.splice(index, 1);
  91394. }
  91395. }
  91396. this._parent = parent;
  91397. if (this._parent) {
  91398. this._parent.children.push(this);
  91399. }
  91400. if (updateDifferenceMatrix) {
  91401. this._updateDifferenceMatrix();
  91402. }
  91403. this.markAsDirty();
  91404. };
  91405. /**
  91406. * Gets the local matrix
  91407. * @returns a matrix
  91408. */
  91409. Bone.prototype.getLocalMatrix = function () {
  91410. this._compose();
  91411. return this._localMatrix;
  91412. };
  91413. /**
  91414. * Gets the base matrix (initial matrix which remains unchanged)
  91415. * @returns a matrix
  91416. */
  91417. Bone.prototype.getBaseMatrix = function () {
  91418. return this._baseMatrix;
  91419. };
  91420. /**
  91421. * Gets the rest pose matrix
  91422. * @returns a matrix
  91423. */
  91424. Bone.prototype.getRestPose = function () {
  91425. return this._restPose;
  91426. };
  91427. /**
  91428. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  91429. */
  91430. Bone.prototype.getWorldMatrix = function () {
  91431. return this._worldTransform;
  91432. };
  91433. /**
  91434. * Sets the local matrix to rest pose matrix
  91435. */
  91436. Bone.prototype.returnToRest = function () {
  91437. this.updateMatrix(this._restPose.clone());
  91438. };
  91439. /**
  91440. * Gets the inverse of the absolute transform matrix.
  91441. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  91442. * @returns a matrix
  91443. */
  91444. Bone.prototype.getInvertedAbsoluteTransform = function () {
  91445. return this._invertedAbsoluteTransform;
  91446. };
  91447. /**
  91448. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  91449. * @returns a matrix
  91450. */
  91451. Bone.prototype.getAbsoluteTransform = function () {
  91452. return this._absoluteTransform;
  91453. };
  91454. Object.defineProperty(Bone.prototype, "position", {
  91455. // Properties (matches AbstractMesh properties)
  91456. /** Gets or sets current position (in local space) */
  91457. get: function () {
  91458. this._decompose();
  91459. return this._localPosition;
  91460. },
  91461. set: function (newPosition) {
  91462. this._decompose();
  91463. this._localPosition.copyFrom(newPosition);
  91464. this._markAsDirtyAndCompose();
  91465. },
  91466. enumerable: true,
  91467. configurable: true
  91468. });
  91469. Object.defineProperty(Bone.prototype, "rotation", {
  91470. /** Gets or sets current rotation (in local space) */
  91471. get: function () {
  91472. return this.getRotation();
  91473. },
  91474. set: function (newRotation) {
  91475. this.setRotation(newRotation);
  91476. },
  91477. enumerable: true,
  91478. configurable: true
  91479. });
  91480. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  91481. /** Gets or sets current rotation quaternion (in local space) */
  91482. get: function () {
  91483. this._decompose();
  91484. return this._localRotation;
  91485. },
  91486. set: function (newRotation) {
  91487. this.setRotationQuaternion(newRotation);
  91488. },
  91489. enumerable: true,
  91490. configurable: true
  91491. });
  91492. Object.defineProperty(Bone.prototype, "scaling", {
  91493. /** Gets or sets current scaling (in local space) */
  91494. get: function () {
  91495. return this.getScale();
  91496. },
  91497. set: function (newScaling) {
  91498. this.setScale(newScaling);
  91499. },
  91500. enumerable: true,
  91501. configurable: true
  91502. });
  91503. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  91504. /**
  91505. * Gets the animation properties override
  91506. */
  91507. get: function () {
  91508. return this._skeleton.animationPropertiesOverride;
  91509. },
  91510. enumerable: true,
  91511. configurable: true
  91512. });
  91513. // Methods
  91514. Bone.prototype._decompose = function () {
  91515. if (!this._needToDecompose) {
  91516. return;
  91517. }
  91518. this._needToDecompose = false;
  91519. if (!this._localScaling) {
  91520. this._localScaling = BABYLON.Vector3.Zero();
  91521. this._localRotation = BABYLON.Quaternion.Zero();
  91522. this._localPosition = BABYLON.Vector3.Zero();
  91523. }
  91524. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  91525. };
  91526. Bone.prototype._compose = function () {
  91527. if (!this._needToCompose) {
  91528. return;
  91529. }
  91530. this._needToCompose = false;
  91531. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  91532. };
  91533. /**
  91534. * Update the base and local matrices
  91535. * @param matrix defines the new base or local matrix
  91536. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  91537. * @param updateLocalMatrix defines if the local matrix should be updated
  91538. */
  91539. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  91540. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  91541. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  91542. this._baseMatrix.copyFrom(matrix);
  91543. if (updateDifferenceMatrix) {
  91544. this._updateDifferenceMatrix();
  91545. }
  91546. if (updateLocalMatrix) {
  91547. this._localMatrix.copyFrom(matrix);
  91548. this._markAsDirtyAndDecompose();
  91549. }
  91550. else {
  91551. this.markAsDirty();
  91552. }
  91553. };
  91554. /** @hidden */
  91555. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  91556. if (updateChildren === void 0) { updateChildren = true; }
  91557. if (!rootMatrix) {
  91558. rootMatrix = this._baseMatrix;
  91559. }
  91560. if (this._parent) {
  91561. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  91562. }
  91563. else {
  91564. this._absoluteTransform.copyFrom(rootMatrix);
  91565. }
  91566. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  91567. if (updateChildren) {
  91568. for (var index = 0; index < this.children.length; index++) {
  91569. this.children[index]._updateDifferenceMatrix();
  91570. }
  91571. }
  91572. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  91573. };
  91574. /**
  91575. * Flag the bone as dirty (Forcing it to update everything)
  91576. */
  91577. Bone.prototype.markAsDirty = function () {
  91578. this._currentRenderId++;
  91579. this._childRenderId++;
  91580. this._skeleton._markAsDirty();
  91581. };
  91582. Bone.prototype._markAsDirtyAndCompose = function () {
  91583. this.markAsDirty();
  91584. this._needToCompose = true;
  91585. };
  91586. Bone.prototype._markAsDirtyAndDecompose = function () {
  91587. this.markAsDirty();
  91588. this._needToDecompose = true;
  91589. };
  91590. /**
  91591. * Copy an animation range from another bone
  91592. * @param source defines the source bone
  91593. * @param rangeName defines the range name to copy
  91594. * @param frameOffset defines the frame offset
  91595. * @param rescaleAsRequired defines if rescaling must be applied if required
  91596. * @param skelDimensionsRatio defines the scaling ratio
  91597. * @returns true if operation was successful
  91598. */
  91599. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  91600. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  91601. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  91602. // all animation may be coming from a library skeleton, so may need to create animation
  91603. if (this.animations.length === 0) {
  91604. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  91605. this.animations[0].setKeys([]);
  91606. }
  91607. // get animation info / verify there is such a range from the source bone
  91608. var sourceRange = source.animations[0].getRange(rangeName);
  91609. if (!sourceRange) {
  91610. return false;
  91611. }
  91612. var from = sourceRange.from;
  91613. var to = sourceRange.to;
  91614. var sourceKeys = source.animations[0].getKeys();
  91615. // rescaling prep
  91616. var sourceBoneLength = source.length;
  91617. var sourceParent = source.getParent();
  91618. var parent = this.getParent();
  91619. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  91620. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  91621. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  91622. var destKeys = this.animations[0].getKeys();
  91623. // loop vars declaration
  91624. var orig;
  91625. var origTranslation;
  91626. var mat;
  91627. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  91628. orig = sourceKeys[key];
  91629. if (orig.frame >= from && orig.frame <= to) {
  91630. if (rescaleAsRequired) {
  91631. mat = orig.value.clone();
  91632. // scale based on parent ratio, when bone has parent
  91633. if (parentScalingReqd) {
  91634. origTranslation = mat.getTranslation();
  91635. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  91636. // scale based on skeleton dimension ratio when root bone, and value is passed
  91637. }
  91638. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  91639. origTranslation = mat.getTranslation();
  91640. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  91641. // use original when root bone, and no data for skelDimensionsRatio
  91642. }
  91643. else {
  91644. mat = orig.value;
  91645. }
  91646. }
  91647. else {
  91648. mat = orig.value;
  91649. }
  91650. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  91651. }
  91652. }
  91653. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  91654. return true;
  91655. };
  91656. /**
  91657. * Translate the bone in local or world space
  91658. * @param vec The amount to translate the bone
  91659. * @param space The space that the translation is in
  91660. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91661. */
  91662. Bone.prototype.translate = function (vec, space, mesh) {
  91663. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91664. var lm = this.getLocalMatrix();
  91665. if (space == BABYLON.Space.LOCAL) {
  91666. lm.addAtIndex(12, vec.x);
  91667. lm.addAtIndex(13, vec.y);
  91668. lm.addAtIndex(14, vec.z);
  91669. }
  91670. else {
  91671. var wm = null;
  91672. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91673. if (mesh) {
  91674. wm = mesh.getWorldMatrix();
  91675. }
  91676. this._skeleton.computeAbsoluteTransforms();
  91677. var tmat = Bone._tmpMats[0];
  91678. var tvec = Bone._tmpVecs[0];
  91679. if (this._parent) {
  91680. if (mesh && wm) {
  91681. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91682. tmat.multiplyToRef(wm, tmat);
  91683. }
  91684. else {
  91685. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91686. }
  91687. }
  91688. tmat.setTranslationFromFloats(0, 0, 0);
  91689. tmat.invert();
  91690. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  91691. lm.addAtIndex(12, tvec.x);
  91692. lm.addAtIndex(13, tvec.y);
  91693. lm.addAtIndex(14, tvec.z);
  91694. }
  91695. this._markAsDirtyAndDecompose();
  91696. };
  91697. /**
  91698. * Set the postion of the bone in local or world space
  91699. * @param position The position to set the bone
  91700. * @param space The space that the position is in
  91701. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91702. */
  91703. Bone.prototype.setPosition = function (position, space, mesh) {
  91704. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91705. var lm = this.getLocalMatrix();
  91706. if (space == BABYLON.Space.LOCAL) {
  91707. lm.setTranslationFromFloats(position.x, position.y, position.z);
  91708. }
  91709. else {
  91710. var wm = null;
  91711. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91712. if (mesh) {
  91713. wm = mesh.getWorldMatrix();
  91714. }
  91715. this._skeleton.computeAbsoluteTransforms();
  91716. var tmat = Bone._tmpMats[0];
  91717. var vec = Bone._tmpVecs[0];
  91718. if (this._parent) {
  91719. if (mesh && wm) {
  91720. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91721. tmat.multiplyToRef(wm, tmat);
  91722. }
  91723. else {
  91724. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91725. }
  91726. }
  91727. tmat.invert();
  91728. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  91729. lm.setTranslationFromFloats(vec.x, vec.y, vec.z);
  91730. }
  91731. this._markAsDirtyAndDecompose();
  91732. };
  91733. /**
  91734. * Set the absolute position of the bone (world space)
  91735. * @param position The position to set the bone
  91736. * @param mesh The mesh that this bone is attached to
  91737. */
  91738. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  91739. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  91740. };
  91741. /**
  91742. * Scale the bone on the x, y and z axes (in local space)
  91743. * @param x The amount to scale the bone on the x axis
  91744. * @param y The amount to scale the bone on the y axis
  91745. * @param z The amount to scale the bone on the z axis
  91746. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  91747. */
  91748. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  91749. if (scaleChildren === void 0) { scaleChildren = false; }
  91750. var locMat = this.getLocalMatrix();
  91751. // Apply new scaling on top of current local matrix
  91752. var scaleMat = Bone._tmpMats[0];
  91753. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  91754. scaleMat.multiplyToRef(locMat, locMat);
  91755. // Invert scaling matrix and apply the inverse to all children
  91756. scaleMat.invert();
  91757. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  91758. var child = _a[_i];
  91759. var cm = child.getLocalMatrix();
  91760. cm.multiplyToRef(scaleMat, cm);
  91761. cm.multiplyAtIndex(12, x);
  91762. cm.multiplyAtIndex(13, y);
  91763. cm.multiplyAtIndex(14, z);
  91764. child._markAsDirtyAndDecompose();
  91765. }
  91766. this._markAsDirtyAndDecompose();
  91767. if (scaleChildren) {
  91768. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  91769. var child = _c[_b];
  91770. child.scale(x, y, z, scaleChildren);
  91771. }
  91772. }
  91773. };
  91774. /**
  91775. * Set the bone scaling in local space
  91776. * @param scale defines the scaling vector
  91777. */
  91778. Bone.prototype.setScale = function (scale) {
  91779. this._decompose();
  91780. this._localScaling.copyFrom(scale);
  91781. this._markAsDirtyAndCompose();
  91782. };
  91783. /**
  91784. * Gets the current scaling in local space
  91785. * @returns the current scaling vector
  91786. */
  91787. Bone.prototype.getScale = function () {
  91788. this._decompose();
  91789. return this._localScaling;
  91790. };
  91791. /**
  91792. * Gets the current scaling in local space and stores it in a target vector
  91793. * @param result defines the target vector
  91794. */
  91795. Bone.prototype.getScaleToRef = function (result) {
  91796. this._decompose();
  91797. result.copyFrom(this._localScaling);
  91798. };
  91799. /**
  91800. * Set the yaw, pitch, and roll of the bone in local or world space
  91801. * @param yaw The rotation of the bone on the y axis
  91802. * @param pitch The rotation of the bone on the x axis
  91803. * @param roll The rotation of the bone on the z axis
  91804. * @param space The space that the axes of rotation are in
  91805. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91806. */
  91807. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  91808. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91809. if (space === BABYLON.Space.LOCAL) {
  91810. var quat = Bone._tmpQuat;
  91811. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  91812. this.setRotationQuaternion(quat, space, mesh);
  91813. return;
  91814. }
  91815. var rotMatInv = Bone._tmpMats[0];
  91816. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91817. return;
  91818. }
  91819. var rotMat = Bone._tmpMats[1];
  91820. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  91821. rotMatInv.multiplyToRef(rotMat, rotMat);
  91822. this._rotateWithMatrix(rotMat, space, mesh);
  91823. };
  91824. /**
  91825. * Add a rotation to the bone on an axis in local or world space
  91826. * @param axis The axis to rotate the bone on
  91827. * @param amount The amount to rotate the bone
  91828. * @param space The space that the axis is in
  91829. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91830. */
  91831. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  91832. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91833. var rmat = Bone._tmpMats[0];
  91834. rmat.setTranslationFromFloats(0, 0, 0);
  91835. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  91836. this._rotateWithMatrix(rmat, space, mesh);
  91837. };
  91838. /**
  91839. * Set the rotation of the bone to a particular axis angle in local or world space
  91840. * @param axis The axis to rotate the bone on
  91841. * @param angle The angle that the bone should be rotated to
  91842. * @param space The space that the axis is in
  91843. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91844. */
  91845. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  91846. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91847. if (space === BABYLON.Space.LOCAL) {
  91848. var quat = Bone._tmpQuat;
  91849. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  91850. this.setRotationQuaternion(quat, space, mesh);
  91851. return;
  91852. }
  91853. var rotMatInv = Bone._tmpMats[0];
  91854. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91855. return;
  91856. }
  91857. var rotMat = Bone._tmpMats[1];
  91858. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  91859. rotMatInv.multiplyToRef(rotMat, rotMat);
  91860. this._rotateWithMatrix(rotMat, space, mesh);
  91861. };
  91862. /**
  91863. * Set the euler rotation of the bone in local of world space
  91864. * @param rotation The euler rotation that the bone should be set to
  91865. * @param space The space that the rotation is in
  91866. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91867. */
  91868. Bone.prototype.setRotation = function (rotation, space, mesh) {
  91869. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91870. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  91871. };
  91872. /**
  91873. * Set the quaternion rotation of the bone in local of world space
  91874. * @param quat The quaternion rotation that the bone should be set to
  91875. * @param space The space that the rotation is in
  91876. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91877. */
  91878. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  91879. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91880. if (space === BABYLON.Space.LOCAL) {
  91881. this._decompose();
  91882. this._localRotation.copyFrom(quat);
  91883. this._markAsDirtyAndCompose();
  91884. return;
  91885. }
  91886. var rotMatInv = Bone._tmpMats[0];
  91887. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91888. return;
  91889. }
  91890. var rotMat = Bone._tmpMats[1];
  91891. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  91892. rotMatInv.multiplyToRef(rotMat, rotMat);
  91893. this._rotateWithMatrix(rotMat, space, mesh);
  91894. };
  91895. /**
  91896. * Set the rotation matrix of the bone in local of world space
  91897. * @param rotMat The rotation matrix that the bone should be set to
  91898. * @param space The space that the rotation is in
  91899. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91900. */
  91901. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  91902. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91903. if (space === BABYLON.Space.LOCAL) {
  91904. var quat = Bone._tmpQuat;
  91905. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  91906. this.setRotationQuaternion(quat, space, mesh);
  91907. return;
  91908. }
  91909. var rotMatInv = Bone._tmpMats[0];
  91910. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91911. return;
  91912. }
  91913. var rotMat2 = Bone._tmpMats[1];
  91914. rotMat2.copyFrom(rotMat);
  91915. rotMatInv.multiplyToRef(rotMat, rotMat2);
  91916. this._rotateWithMatrix(rotMat2, space, mesh);
  91917. };
  91918. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  91919. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91920. var lmat = this.getLocalMatrix();
  91921. var lx = lmat.m[12];
  91922. var ly = lmat.m[13];
  91923. var lz = lmat.m[14];
  91924. var parent = this.getParent();
  91925. var parentScale = Bone._tmpMats[3];
  91926. var parentScaleInv = Bone._tmpMats[4];
  91927. if (parent && space == BABYLON.Space.WORLD) {
  91928. if (mesh) {
  91929. parentScale.copyFrom(mesh.getWorldMatrix());
  91930. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  91931. }
  91932. else {
  91933. parentScale.copyFrom(parent.getAbsoluteTransform());
  91934. }
  91935. parentScaleInv.copyFrom(parentScale);
  91936. parentScaleInv.invert();
  91937. lmat.multiplyToRef(parentScale, lmat);
  91938. lmat.multiplyToRef(rmat, lmat);
  91939. lmat.multiplyToRef(parentScaleInv, lmat);
  91940. }
  91941. else {
  91942. if (space == BABYLON.Space.WORLD && mesh) {
  91943. parentScale.copyFrom(mesh.getWorldMatrix());
  91944. parentScaleInv.copyFrom(parentScale);
  91945. parentScaleInv.invert();
  91946. lmat.multiplyToRef(parentScale, lmat);
  91947. lmat.multiplyToRef(rmat, lmat);
  91948. lmat.multiplyToRef(parentScaleInv, lmat);
  91949. }
  91950. else {
  91951. lmat.multiplyToRef(rmat, lmat);
  91952. }
  91953. }
  91954. lmat.setTranslationFromFloats(lx, ly, lz);
  91955. this.computeAbsoluteTransforms();
  91956. this._markAsDirtyAndDecompose();
  91957. };
  91958. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  91959. var scaleMatrix = Bone._tmpMats[2];
  91960. rotMatInv.copyFrom(this.getAbsoluteTransform());
  91961. if (mesh) {
  91962. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  91963. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  91964. }
  91965. rotMatInv.invert();
  91966. if (isNaN(rotMatInv.m[0])) {
  91967. // Matrix failed to invert.
  91968. // This can happen if scale is zero for example.
  91969. return false;
  91970. }
  91971. scaleMatrix.multiplyAtIndex(0, this._scalingDeterminant);
  91972. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  91973. return true;
  91974. };
  91975. /**
  91976. * Get the position of the bone in local or world space
  91977. * @param space The space that the returned position is in
  91978. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91979. * @returns The position of the bone
  91980. */
  91981. Bone.prototype.getPosition = function (space, mesh) {
  91982. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91983. if (mesh === void 0) { mesh = null; }
  91984. var pos = BABYLON.Vector3.Zero();
  91985. this.getPositionToRef(space, mesh, pos);
  91986. return pos;
  91987. };
  91988. /**
  91989. * Copy the position of the bone to a vector3 in local or world space
  91990. * @param space The space that the returned position is in
  91991. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91992. * @param result The vector3 to copy the position to
  91993. */
  91994. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  91995. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91996. if (space == BABYLON.Space.LOCAL) {
  91997. var lm = this.getLocalMatrix();
  91998. result.x = lm.m[12];
  91999. result.y = lm.m[13];
  92000. result.z = lm.m[14];
  92001. }
  92002. else {
  92003. var wm = null;
  92004. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92005. if (mesh) {
  92006. wm = mesh.getWorldMatrix();
  92007. }
  92008. this._skeleton.computeAbsoluteTransforms();
  92009. var tmat = Bone._tmpMats[0];
  92010. if (mesh && wm) {
  92011. tmat.copyFrom(this.getAbsoluteTransform());
  92012. tmat.multiplyToRef(wm, tmat);
  92013. }
  92014. else {
  92015. tmat = this.getAbsoluteTransform();
  92016. }
  92017. result.x = tmat.m[12];
  92018. result.y = tmat.m[13];
  92019. result.z = tmat.m[14];
  92020. }
  92021. };
  92022. /**
  92023. * Get the absolute position of the bone (world space)
  92024. * @param mesh The mesh that this bone is attached to
  92025. * @returns The absolute position of the bone
  92026. */
  92027. Bone.prototype.getAbsolutePosition = function (mesh) {
  92028. if (mesh === void 0) { mesh = null; }
  92029. var pos = BABYLON.Vector3.Zero();
  92030. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  92031. return pos;
  92032. };
  92033. /**
  92034. * Copy the absolute position of the bone (world space) to the result param
  92035. * @param mesh The mesh that this bone is attached to
  92036. * @param result The vector3 to copy the absolute position to
  92037. */
  92038. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  92039. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  92040. };
  92041. /**
  92042. * Compute the absolute transforms of this bone and its children
  92043. */
  92044. Bone.prototype.computeAbsoluteTransforms = function () {
  92045. this._compose();
  92046. if (this._parent) {
  92047. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  92048. }
  92049. else {
  92050. this._absoluteTransform.copyFrom(this._localMatrix);
  92051. var poseMatrix = this._skeleton.getPoseMatrix();
  92052. if (poseMatrix) {
  92053. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  92054. }
  92055. }
  92056. var children = this.children;
  92057. var len = children.length;
  92058. for (var i = 0; i < len; i++) {
  92059. children[i].computeAbsoluteTransforms();
  92060. }
  92061. };
  92062. /**
  92063. * Get the world direction from an axis that is in the local space of the bone
  92064. * @param localAxis The local direction that is used to compute the world direction
  92065. * @param mesh The mesh that this bone is attached to
  92066. * @returns The world direction
  92067. */
  92068. Bone.prototype.getDirection = function (localAxis, mesh) {
  92069. if (mesh === void 0) { mesh = null; }
  92070. var result = BABYLON.Vector3.Zero();
  92071. this.getDirectionToRef(localAxis, mesh, result);
  92072. return result;
  92073. };
  92074. /**
  92075. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  92076. * @param localAxis The local direction that is used to compute the world direction
  92077. * @param mesh The mesh that this bone is attached to
  92078. * @param result The vector3 that the world direction will be copied to
  92079. */
  92080. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  92081. if (mesh === void 0) { mesh = null; }
  92082. var wm = null;
  92083. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92084. if (mesh) {
  92085. wm = mesh.getWorldMatrix();
  92086. }
  92087. this._skeleton.computeAbsoluteTransforms();
  92088. var mat = Bone._tmpMats[0];
  92089. mat.copyFrom(this.getAbsoluteTransform());
  92090. if (mesh && wm) {
  92091. mat.multiplyToRef(wm, mat);
  92092. }
  92093. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  92094. result.normalize();
  92095. };
  92096. /**
  92097. * Get the euler rotation of the bone in local or world space
  92098. * @param space The space that the rotation should be in
  92099. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92100. * @returns The euler rotation
  92101. */
  92102. Bone.prototype.getRotation = function (space, mesh) {
  92103. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92104. if (mesh === void 0) { mesh = null; }
  92105. var result = BABYLON.Vector3.Zero();
  92106. this.getRotationToRef(space, mesh, result);
  92107. return result;
  92108. };
  92109. /**
  92110. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  92111. * @param space The space that the rotation should be in
  92112. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92113. * @param result The vector3 that the rotation should be copied to
  92114. */
  92115. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  92116. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92117. if (mesh === void 0) { mesh = null; }
  92118. var quat = Bone._tmpQuat;
  92119. this.getRotationQuaternionToRef(space, mesh, quat);
  92120. quat.toEulerAnglesToRef(result);
  92121. };
  92122. /**
  92123. * Get the quaternion rotation of the bone in either local or world space
  92124. * @param space The space that the rotation should be in
  92125. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92126. * @returns The quaternion rotation
  92127. */
  92128. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  92129. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92130. if (mesh === void 0) { mesh = null; }
  92131. var result = BABYLON.Quaternion.Identity();
  92132. this.getRotationQuaternionToRef(space, mesh, result);
  92133. return result;
  92134. };
  92135. /**
  92136. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  92137. * @param space The space that the rotation should be in
  92138. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92139. * @param result The quaternion that the rotation should be copied to
  92140. */
  92141. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  92142. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92143. if (mesh === void 0) { mesh = null; }
  92144. if (space == BABYLON.Space.LOCAL) {
  92145. this._decompose();
  92146. result.copyFrom(this._localRotation);
  92147. }
  92148. else {
  92149. var mat = Bone._tmpMats[0];
  92150. var amat = this.getAbsoluteTransform();
  92151. if (mesh) {
  92152. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  92153. }
  92154. else {
  92155. mat.copyFrom(amat);
  92156. }
  92157. mat.multiplyAtIndex(0, this._scalingDeterminant);
  92158. mat.multiplyAtIndex(1, this._scalingDeterminant);
  92159. mat.multiplyAtIndex(2, this._scalingDeterminant);
  92160. mat.decompose(undefined, result, undefined);
  92161. }
  92162. };
  92163. /**
  92164. * Get the rotation matrix of the bone in local or world space
  92165. * @param space The space that the rotation should be in
  92166. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92167. * @returns The rotation matrix
  92168. */
  92169. Bone.prototype.getRotationMatrix = function (space, mesh) {
  92170. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92171. var result = BABYLON.Matrix.Identity();
  92172. this.getRotationMatrixToRef(space, mesh, result);
  92173. return result;
  92174. };
  92175. /**
  92176. * Copy the rotation matrix of the bone to a matrix. The rotation can be 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. * @param result The quaternion that the rotation should be copied to
  92180. */
  92181. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  92182. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92183. if (space == BABYLON.Space.LOCAL) {
  92184. this.getLocalMatrix().getRotationMatrixToRef(result);
  92185. }
  92186. else {
  92187. var mat = Bone._tmpMats[0];
  92188. var amat = this.getAbsoluteTransform();
  92189. if (mesh) {
  92190. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  92191. }
  92192. else {
  92193. mat.copyFrom(amat);
  92194. }
  92195. mat.multiplyAtIndex(0, this._scalingDeterminant);
  92196. mat.multiplyAtIndex(1, this._scalingDeterminant);
  92197. mat.multiplyAtIndex(2, this._scalingDeterminant);
  92198. mat.getRotationMatrixToRef(result);
  92199. }
  92200. };
  92201. /**
  92202. * Get the world position of a point that is in the local space of the bone
  92203. * @param position The local position
  92204. * @param mesh The mesh that this bone is attached to
  92205. * @returns The world position
  92206. */
  92207. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  92208. if (mesh === void 0) { mesh = null; }
  92209. var result = BABYLON.Vector3.Zero();
  92210. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  92211. return result;
  92212. };
  92213. /**
  92214. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  92215. * @param position The local position
  92216. * @param mesh The mesh that this bone is attached to
  92217. * @param result The vector3 that the world position should be copied to
  92218. */
  92219. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  92220. if (mesh === void 0) { mesh = null; }
  92221. var wm = null;
  92222. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92223. if (mesh) {
  92224. wm = mesh.getWorldMatrix();
  92225. }
  92226. this._skeleton.computeAbsoluteTransforms();
  92227. var tmat = Bone._tmpMats[0];
  92228. if (mesh && wm) {
  92229. tmat.copyFrom(this.getAbsoluteTransform());
  92230. tmat.multiplyToRef(wm, tmat);
  92231. }
  92232. else {
  92233. tmat = this.getAbsoluteTransform();
  92234. }
  92235. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  92236. };
  92237. /**
  92238. * Get the local position of a point that is in world space
  92239. * @param position The world position
  92240. * @param mesh The mesh that this bone is attached to
  92241. * @returns The local position
  92242. */
  92243. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  92244. if (mesh === void 0) { mesh = null; }
  92245. var result = BABYLON.Vector3.Zero();
  92246. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  92247. return result;
  92248. };
  92249. /**
  92250. * Get the local position of a point that is in world space and copy it to the result param
  92251. * @param position The world position
  92252. * @param mesh The mesh that this bone is attached to
  92253. * @param result The vector3 that the local position should be copied to
  92254. */
  92255. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  92256. if (mesh === void 0) { mesh = null; }
  92257. var wm = null;
  92258. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92259. if (mesh) {
  92260. wm = mesh.getWorldMatrix();
  92261. }
  92262. this._skeleton.computeAbsoluteTransforms();
  92263. var tmat = Bone._tmpMats[0];
  92264. tmat.copyFrom(this.getAbsoluteTransform());
  92265. if (mesh && wm) {
  92266. tmat.multiplyToRef(wm, tmat);
  92267. }
  92268. tmat.invert();
  92269. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  92270. };
  92271. Bone._tmpVecs = BABYLON.Tools.BuildArray(2, BABYLON.Vector3.Zero);
  92272. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  92273. Bone._tmpMats = BABYLON.Tools.BuildArray(5, BABYLON.Matrix.Identity);
  92274. return Bone;
  92275. }(BABYLON.Node));
  92276. BABYLON.Bone = Bone;
  92277. })(BABYLON || (BABYLON = {}));
  92278. //# sourceMappingURL=babylon.bone.js.map
  92279. var BABYLON;
  92280. (function (BABYLON) {
  92281. /**
  92282. * Class used to apply inverse kinematics to bones
  92283. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  92284. */
  92285. var BoneIKController = /** @class */ (function () {
  92286. /**
  92287. * Creates a new BoneIKController
  92288. * @param mesh defines the mesh to control
  92289. * @param bone defines the bone to control
  92290. * @param options defines options to set up the controller
  92291. */
  92292. function BoneIKController(mesh, bone, options) {
  92293. /**
  92294. * Gets or sets the target position
  92295. */
  92296. this.targetPosition = BABYLON.Vector3.Zero();
  92297. /**
  92298. * Gets or sets the pole target position
  92299. */
  92300. this.poleTargetPosition = BABYLON.Vector3.Zero();
  92301. /**
  92302. * Gets or sets the pole target local offset
  92303. */
  92304. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  92305. /**
  92306. * Gets or sets the pole angle
  92307. */
  92308. this.poleAngle = 0;
  92309. /**
  92310. * 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)
  92311. */
  92312. this.slerpAmount = 1;
  92313. this._bone1Quat = BABYLON.Quaternion.Identity();
  92314. this._bone1Mat = BABYLON.Matrix.Identity();
  92315. this._bone2Ang = Math.PI;
  92316. this._maxAngle = Math.PI;
  92317. this._rightHandedSystem = false;
  92318. this._bendAxis = BABYLON.Vector3.Right();
  92319. this._slerping = false;
  92320. this._adjustRoll = 0;
  92321. this._bone2 = bone;
  92322. this._bone1 = bone.getParent();
  92323. if (!this._bone1) {
  92324. return;
  92325. }
  92326. this.mesh = mesh;
  92327. var bonePos = bone.getPosition();
  92328. if (bone.getAbsoluteTransform().determinant() > 0) {
  92329. this._rightHandedSystem = true;
  92330. this._bendAxis.x = 0;
  92331. this._bendAxis.y = 0;
  92332. this._bendAxis.z = -1;
  92333. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  92334. this._adjustRoll = Math.PI * .5;
  92335. this._bendAxis.z = 1;
  92336. }
  92337. }
  92338. if (this._bone1.length) {
  92339. var boneScale1 = this._bone1.getScale();
  92340. var boneScale2 = this._bone2.getScale();
  92341. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  92342. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  92343. }
  92344. else if (this._bone1.children[0]) {
  92345. mesh.computeWorldMatrix(true);
  92346. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  92347. var pos2 = this._bone2.getAbsolutePosition(mesh);
  92348. var pos3 = this._bone1.getAbsolutePosition(mesh);
  92349. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  92350. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  92351. }
  92352. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  92353. this.maxAngle = Math.PI;
  92354. if (options) {
  92355. if (options.targetMesh) {
  92356. this.targetMesh = options.targetMesh;
  92357. this.targetMesh.computeWorldMatrix(true);
  92358. }
  92359. if (options.poleTargetMesh) {
  92360. this.poleTargetMesh = options.poleTargetMesh;
  92361. this.poleTargetMesh.computeWorldMatrix(true);
  92362. }
  92363. else if (options.poleTargetBone) {
  92364. this.poleTargetBone = options.poleTargetBone;
  92365. }
  92366. else if (this._bone1.getParent()) {
  92367. this.poleTargetBone = this._bone1.getParent();
  92368. }
  92369. if (options.poleTargetLocalOffset) {
  92370. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  92371. }
  92372. if (options.poleAngle) {
  92373. this.poleAngle = options.poleAngle;
  92374. }
  92375. if (options.bendAxis) {
  92376. this._bendAxis.copyFrom(options.bendAxis);
  92377. }
  92378. if (options.maxAngle) {
  92379. this.maxAngle = options.maxAngle;
  92380. }
  92381. if (options.slerpAmount) {
  92382. this.slerpAmount = options.slerpAmount;
  92383. }
  92384. }
  92385. }
  92386. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  92387. /**
  92388. * Gets or sets maximum allowed angle
  92389. */
  92390. get: function () {
  92391. return this._maxAngle;
  92392. },
  92393. set: function (value) {
  92394. this._setMaxAngle(value);
  92395. },
  92396. enumerable: true,
  92397. configurable: true
  92398. });
  92399. BoneIKController.prototype._setMaxAngle = function (ang) {
  92400. if (ang < 0) {
  92401. ang = 0;
  92402. }
  92403. if (ang > Math.PI || ang == undefined) {
  92404. ang = Math.PI;
  92405. }
  92406. this._maxAngle = ang;
  92407. var a = this._bone1Length;
  92408. var b = this._bone2Length;
  92409. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  92410. };
  92411. /**
  92412. * Force the controller to update the bones
  92413. */
  92414. BoneIKController.prototype.update = function () {
  92415. var bone1 = this._bone1;
  92416. if (!bone1) {
  92417. return;
  92418. }
  92419. var target = this.targetPosition;
  92420. var poleTarget = this.poleTargetPosition;
  92421. var mat1 = BoneIKController._tmpMats[0];
  92422. var mat2 = BoneIKController._tmpMats[1];
  92423. if (this.targetMesh) {
  92424. target.copyFrom(this.targetMesh.getAbsolutePosition());
  92425. }
  92426. if (this.poleTargetBone) {
  92427. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  92428. }
  92429. else if (this.poleTargetMesh) {
  92430. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  92431. }
  92432. var bonePos = BoneIKController._tmpVecs[0];
  92433. var zaxis = BoneIKController._tmpVecs[1];
  92434. var xaxis = BoneIKController._tmpVecs[2];
  92435. var yaxis = BoneIKController._tmpVecs[3];
  92436. var upAxis = BoneIKController._tmpVecs[4];
  92437. var _tmpQuat = BoneIKController._tmpQuat;
  92438. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  92439. poleTarget.subtractToRef(bonePos, upAxis);
  92440. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  92441. upAxis.y = 1;
  92442. }
  92443. else {
  92444. upAxis.normalize();
  92445. }
  92446. target.subtractToRef(bonePos, yaxis);
  92447. yaxis.normalize();
  92448. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  92449. zaxis.normalize();
  92450. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  92451. xaxis.normalize();
  92452. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  92453. var a = this._bone1Length;
  92454. var b = this._bone2Length;
  92455. var c = BABYLON.Vector3.Distance(bonePos, target);
  92456. if (this._maxReach > 0) {
  92457. c = Math.min(this._maxReach, c);
  92458. }
  92459. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  92460. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  92461. if (acosa > 1) {
  92462. acosa = 1;
  92463. }
  92464. if (acosb > 1) {
  92465. acosb = 1;
  92466. }
  92467. if (acosa < -1) {
  92468. acosa = -1;
  92469. }
  92470. if (acosb < -1) {
  92471. acosb = -1;
  92472. }
  92473. var angA = Math.acos(acosa);
  92474. var angB = Math.acos(acosb);
  92475. var angC = -angA - angB;
  92476. if (this._rightHandedSystem) {
  92477. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  92478. mat2.multiplyToRef(mat1, mat1);
  92479. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  92480. mat2.multiplyToRef(mat1, mat1);
  92481. }
  92482. else {
  92483. var _tmpVec = BoneIKController._tmpVecs[5];
  92484. _tmpVec.copyFrom(this._bendAxis);
  92485. _tmpVec.x *= -1;
  92486. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  92487. mat2.multiplyToRef(mat1, mat1);
  92488. }
  92489. if (this.poleAngle) {
  92490. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  92491. mat1.multiplyToRef(mat2, mat1);
  92492. }
  92493. if (this._bone1) {
  92494. if (this.slerpAmount < 1) {
  92495. if (!this._slerping) {
  92496. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  92497. }
  92498. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  92499. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  92500. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  92501. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  92502. this._slerping = true;
  92503. }
  92504. else {
  92505. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  92506. this._bone1Mat.copyFrom(mat1);
  92507. this._slerping = false;
  92508. }
  92509. }
  92510. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  92511. this._bone2Ang = angC;
  92512. };
  92513. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  92514. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  92515. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  92516. return BoneIKController;
  92517. }());
  92518. BABYLON.BoneIKController = BoneIKController;
  92519. })(BABYLON || (BABYLON = {}));
  92520. //# sourceMappingURL=babylon.boneIKController.js.map
  92521. var BABYLON;
  92522. (function (BABYLON) {
  92523. /**
  92524. * Class used to make a bone look toward a point in space
  92525. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  92526. */
  92527. var BoneLookController = /** @class */ (function () {
  92528. /**
  92529. * Create a BoneLookController
  92530. * @param mesh the mesh that the bone belongs to
  92531. * @param bone the bone that will be looking to the target
  92532. * @param target the target Vector3 to look at
  92533. * @param settings optional settings:
  92534. * * maxYaw: the maximum angle the bone will yaw to
  92535. * * minYaw: the minimum angle the bone will yaw to
  92536. * * maxPitch: the maximum angle the bone will pitch to
  92537. * * minPitch: the minimum angle the bone will yaw to
  92538. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  92539. * * upAxis: the up axis of the coordinate system
  92540. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  92541. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  92542. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  92543. * * adjustYaw: used to make an adjustment to the yaw of the bone
  92544. * * adjustPitch: used to make an adjustment to the pitch of the bone
  92545. * * adjustRoll: used to make an adjustment to the roll of the bone
  92546. **/
  92547. function BoneLookController(mesh, bone, target, options) {
  92548. /**
  92549. * The up axis of the coordinate system that is used when the bone is rotated
  92550. */
  92551. this.upAxis = BABYLON.Vector3.Up();
  92552. /**
  92553. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  92554. */
  92555. this.upAxisSpace = BABYLON.Space.LOCAL;
  92556. /**
  92557. * Used to make an adjustment to the yaw of the bone
  92558. */
  92559. this.adjustYaw = 0;
  92560. /**
  92561. * Used to make an adjustment to the pitch of the bone
  92562. */
  92563. this.adjustPitch = 0;
  92564. /**
  92565. * Used to make an adjustment to the roll of the bone
  92566. */
  92567. this.adjustRoll = 0;
  92568. /**
  92569. * 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)
  92570. */
  92571. this.slerpAmount = 1;
  92572. this._boneQuat = BABYLON.Quaternion.Identity();
  92573. this._slerping = false;
  92574. this._firstFrameSkipped = false;
  92575. this._fowardAxis = BABYLON.Vector3.Forward();
  92576. this.mesh = mesh;
  92577. this.bone = bone;
  92578. this.target = target;
  92579. if (options) {
  92580. if (options.adjustYaw) {
  92581. this.adjustYaw = options.adjustYaw;
  92582. }
  92583. if (options.adjustPitch) {
  92584. this.adjustPitch = options.adjustPitch;
  92585. }
  92586. if (options.adjustRoll) {
  92587. this.adjustRoll = options.adjustRoll;
  92588. }
  92589. if (options.maxYaw != null) {
  92590. this.maxYaw = options.maxYaw;
  92591. }
  92592. else {
  92593. this.maxYaw = Math.PI;
  92594. }
  92595. if (options.minYaw != null) {
  92596. this.minYaw = options.minYaw;
  92597. }
  92598. else {
  92599. this.minYaw = -Math.PI;
  92600. }
  92601. if (options.maxPitch != null) {
  92602. this.maxPitch = options.maxPitch;
  92603. }
  92604. else {
  92605. this.maxPitch = Math.PI;
  92606. }
  92607. if (options.minPitch != null) {
  92608. this.minPitch = options.minPitch;
  92609. }
  92610. else {
  92611. this.minPitch = -Math.PI;
  92612. }
  92613. if (options.slerpAmount != null) {
  92614. this.slerpAmount = options.slerpAmount;
  92615. }
  92616. if (options.upAxis != null) {
  92617. this.upAxis = options.upAxis;
  92618. }
  92619. if (options.upAxisSpace != null) {
  92620. this.upAxisSpace = options.upAxisSpace;
  92621. }
  92622. if (options.yawAxis != null || options.pitchAxis != null) {
  92623. var newYawAxis = BABYLON.Axis.Y;
  92624. var newPitchAxis = BABYLON.Axis.X;
  92625. if (options.yawAxis != null) {
  92626. newYawAxis = options.yawAxis.clone();
  92627. newYawAxis.normalize();
  92628. }
  92629. if (options.pitchAxis != null) {
  92630. newPitchAxis = options.pitchAxis.clone();
  92631. newPitchAxis.normalize();
  92632. }
  92633. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  92634. this._transformYawPitch = BABYLON.Matrix.Identity();
  92635. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  92636. this._transformYawPitchInv = this._transformYawPitch.clone();
  92637. this._transformYawPitch.invert();
  92638. }
  92639. }
  92640. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  92641. this.upAxisSpace = BABYLON.Space.LOCAL;
  92642. }
  92643. }
  92644. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  92645. /**
  92646. * Gets or sets the minimum yaw angle that the bone can look to
  92647. */
  92648. get: function () {
  92649. return this._minYaw;
  92650. },
  92651. set: function (value) {
  92652. this._minYaw = value;
  92653. this._minYawSin = Math.sin(value);
  92654. this._minYawCos = Math.cos(value);
  92655. if (this._maxYaw != null) {
  92656. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  92657. this._yawRange = this._maxYaw - this._minYaw;
  92658. }
  92659. },
  92660. enumerable: true,
  92661. configurable: true
  92662. });
  92663. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  92664. /**
  92665. * Gets or sets the maximum yaw angle that the bone can look to
  92666. */
  92667. get: function () {
  92668. return this._maxYaw;
  92669. },
  92670. set: function (value) {
  92671. this._maxYaw = value;
  92672. this._maxYawSin = Math.sin(value);
  92673. this._maxYawCos = Math.cos(value);
  92674. if (this._minYaw != null) {
  92675. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  92676. this._yawRange = this._maxYaw - this._minYaw;
  92677. }
  92678. },
  92679. enumerable: true,
  92680. configurable: true
  92681. });
  92682. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  92683. /**
  92684. * Gets or sets the minimum pitch angle that the bone can look to
  92685. */
  92686. get: function () {
  92687. return this._minPitch;
  92688. },
  92689. set: function (value) {
  92690. this._minPitch = value;
  92691. this._minPitchTan = Math.tan(value);
  92692. },
  92693. enumerable: true,
  92694. configurable: true
  92695. });
  92696. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  92697. /**
  92698. * Gets or sets the maximum pitch angle that the bone can look to
  92699. */
  92700. get: function () {
  92701. return this._maxPitch;
  92702. },
  92703. set: function (value) {
  92704. this._maxPitch = value;
  92705. this._maxPitchTan = Math.tan(value);
  92706. },
  92707. enumerable: true,
  92708. configurable: true
  92709. });
  92710. /**
  92711. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  92712. */
  92713. BoneLookController.prototype.update = function () {
  92714. //skip the first frame when slerping so that the mesh rotation is correct
  92715. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  92716. this._firstFrameSkipped = true;
  92717. return;
  92718. }
  92719. var bone = this.bone;
  92720. var bonePos = BoneLookController._tmpVecs[0];
  92721. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  92722. var target = this.target;
  92723. var _tmpMat1 = BoneLookController._tmpMats[0];
  92724. var _tmpMat2 = BoneLookController._tmpMats[1];
  92725. var mesh = this.mesh;
  92726. var parentBone = bone.getParent();
  92727. var upAxis = BoneLookController._tmpVecs[1];
  92728. upAxis.copyFrom(this.upAxis);
  92729. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  92730. if (this._transformYawPitch) {
  92731. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  92732. }
  92733. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  92734. }
  92735. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  92736. mesh.getDirectionToRef(upAxis, upAxis);
  92737. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  92738. upAxis.normalize();
  92739. }
  92740. }
  92741. var checkYaw = false;
  92742. var checkPitch = false;
  92743. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  92744. checkYaw = true;
  92745. }
  92746. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  92747. checkPitch = true;
  92748. }
  92749. if (checkYaw || checkPitch) {
  92750. var spaceMat = BoneLookController._tmpMats[2];
  92751. var spaceMatInv = BoneLookController._tmpMats[3];
  92752. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  92753. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  92754. }
  92755. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  92756. spaceMat.copyFrom(mesh.getWorldMatrix());
  92757. }
  92758. else {
  92759. var forwardAxis = BoneLookController._tmpVecs[2];
  92760. forwardAxis.copyFrom(this._fowardAxis);
  92761. if (this._transformYawPitch) {
  92762. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  92763. }
  92764. if (parentBone) {
  92765. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  92766. }
  92767. else {
  92768. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  92769. }
  92770. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  92771. rightAxis.normalize();
  92772. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  92773. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  92774. }
  92775. spaceMat.invertToRef(spaceMatInv);
  92776. var xzlen = null;
  92777. if (checkPitch) {
  92778. var localTarget = BoneLookController._tmpVecs[3];
  92779. target.subtractToRef(bonePos, localTarget);
  92780. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  92781. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  92782. var pitch = Math.atan2(localTarget.y, xzlen);
  92783. var newPitch = pitch;
  92784. if (pitch > this._maxPitch) {
  92785. localTarget.y = this._maxPitchTan * xzlen;
  92786. newPitch = this._maxPitch;
  92787. }
  92788. else if (pitch < this._minPitch) {
  92789. localTarget.y = this._minPitchTan * xzlen;
  92790. newPitch = this._minPitch;
  92791. }
  92792. if (pitch != newPitch) {
  92793. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  92794. localTarget.addInPlace(bonePos);
  92795. target = localTarget;
  92796. }
  92797. }
  92798. if (checkYaw) {
  92799. var localTarget = BoneLookController._tmpVecs[4];
  92800. target.subtractToRef(bonePos, localTarget);
  92801. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  92802. var yaw = Math.atan2(localTarget.x, localTarget.z);
  92803. var newYaw = yaw;
  92804. if (yaw > this._maxYaw || yaw < this._minYaw) {
  92805. if (xzlen == null) {
  92806. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  92807. }
  92808. if (this._yawRange > Math.PI) {
  92809. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  92810. localTarget.z = this._maxYawCos * xzlen;
  92811. localTarget.x = this._maxYawSin * xzlen;
  92812. newYaw = this._maxYaw;
  92813. }
  92814. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  92815. localTarget.z = this._minYawCos * xzlen;
  92816. localTarget.x = this._minYawSin * xzlen;
  92817. newYaw = this._minYaw;
  92818. }
  92819. }
  92820. else {
  92821. if (yaw > this._maxYaw) {
  92822. localTarget.z = this._maxYawCos * xzlen;
  92823. localTarget.x = this._maxYawSin * xzlen;
  92824. newYaw = this._maxYaw;
  92825. }
  92826. else if (yaw < this._minYaw) {
  92827. localTarget.z = this._minYawCos * xzlen;
  92828. localTarget.x = this._minYawSin * xzlen;
  92829. newYaw = this._minYaw;
  92830. }
  92831. }
  92832. }
  92833. if (this._slerping && this._yawRange > Math.PI) {
  92834. //are we going to be crossing into the min/max region?
  92835. var boneFwd = BoneLookController._tmpVecs[8];
  92836. boneFwd.copyFrom(BABYLON.Axis.Z);
  92837. if (this._transformYawPitch) {
  92838. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  92839. }
  92840. var boneRotMat = BoneLookController._tmpMats[4];
  92841. this._boneQuat.toRotationMatrix(boneRotMat);
  92842. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  92843. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  92844. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  92845. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  92846. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  92847. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  92848. if (angBtwTar > angBtwMidYaw) {
  92849. if (xzlen == null) {
  92850. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  92851. }
  92852. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  92853. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  92854. if (angBtwMin < angBtwMax) {
  92855. newYaw = boneYaw + Math.PI * .75;
  92856. localTarget.z = Math.cos(newYaw) * xzlen;
  92857. localTarget.x = Math.sin(newYaw) * xzlen;
  92858. }
  92859. else {
  92860. newYaw = boneYaw - Math.PI * .75;
  92861. localTarget.z = Math.cos(newYaw) * xzlen;
  92862. localTarget.x = Math.sin(newYaw) * xzlen;
  92863. }
  92864. }
  92865. }
  92866. if (yaw != newYaw) {
  92867. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  92868. localTarget.addInPlace(bonePos);
  92869. target = localTarget;
  92870. }
  92871. }
  92872. }
  92873. var zaxis = BoneLookController._tmpVecs[5];
  92874. var xaxis = BoneLookController._tmpVecs[6];
  92875. var yaxis = BoneLookController._tmpVecs[7];
  92876. var _tmpQuat = BoneLookController._tmpQuat;
  92877. target.subtractToRef(bonePos, zaxis);
  92878. zaxis.normalize();
  92879. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  92880. xaxis.normalize();
  92881. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  92882. yaxis.normalize();
  92883. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  92884. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  92885. return;
  92886. }
  92887. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  92888. return;
  92889. }
  92890. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  92891. return;
  92892. }
  92893. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  92894. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  92895. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  92896. }
  92897. if (this.slerpAmount < 1) {
  92898. if (!this._slerping) {
  92899. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  92900. }
  92901. if (this._transformYawPitch) {
  92902. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  92903. }
  92904. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  92905. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  92906. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  92907. this._slerping = true;
  92908. }
  92909. else {
  92910. if (this._transformYawPitch) {
  92911. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  92912. }
  92913. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  92914. this._slerping = false;
  92915. }
  92916. };
  92917. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  92918. var angDiff = ang2 - ang1;
  92919. angDiff %= Math.PI * 2;
  92920. if (angDiff > Math.PI) {
  92921. angDiff -= Math.PI * 2;
  92922. }
  92923. else if (angDiff < -Math.PI) {
  92924. angDiff += Math.PI * 2;
  92925. }
  92926. return angDiff;
  92927. };
  92928. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  92929. ang1 %= (2 * Math.PI);
  92930. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  92931. ang2 %= (2 * Math.PI);
  92932. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  92933. var ab = 0;
  92934. if (ang1 < ang2) {
  92935. ab = ang2 - ang1;
  92936. }
  92937. else {
  92938. ab = ang1 - ang2;
  92939. }
  92940. if (ab > Math.PI) {
  92941. ab = Math.PI * 2 - ab;
  92942. }
  92943. return ab;
  92944. };
  92945. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  92946. ang %= (2 * Math.PI);
  92947. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  92948. ang1 %= (2 * Math.PI);
  92949. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  92950. ang2 %= (2 * Math.PI);
  92951. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  92952. if (ang1 < ang2) {
  92953. if (ang > ang1 && ang < ang2) {
  92954. return true;
  92955. }
  92956. }
  92957. else {
  92958. if (ang > ang2 && ang < ang1) {
  92959. return true;
  92960. }
  92961. }
  92962. return false;
  92963. };
  92964. BoneLookController._tmpVecs = BABYLON.Tools.BuildArray(10, BABYLON.Vector3.Zero);
  92965. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  92966. BoneLookController._tmpMats = BABYLON.Tools.BuildArray(5, BABYLON.Matrix.Identity);
  92967. return BoneLookController;
  92968. }());
  92969. BABYLON.BoneLookController = BoneLookController;
  92970. })(BABYLON || (BABYLON = {}));
  92971. //# sourceMappingURL=babylon.boneLookController.js.map
  92972. var BABYLON;
  92973. (function (BABYLON) {
  92974. /**
  92975. * Class used to handle skinning animations
  92976. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  92977. */
  92978. var Skeleton = /** @class */ (function () {
  92979. /**
  92980. * Creates a new skeleton
  92981. * @param name defines the skeleton name
  92982. * @param id defines the skeleton Id
  92983. * @param scene defines the hosting scene
  92984. */
  92985. function Skeleton(
  92986. /** defines the skeleton name */
  92987. name,
  92988. /** defines the skeleton Id */
  92989. id, scene) {
  92990. this.name = name;
  92991. this.id = id;
  92992. /**
  92993. * Gets the list of child bones
  92994. */
  92995. this.bones = new Array();
  92996. /**
  92997. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  92998. */
  92999. this.needInitialSkinMatrix = false;
  93000. this._isDirty = true;
  93001. this._meshesWithPoseMatrix = new Array();
  93002. this._identity = BABYLON.Matrix.Identity();
  93003. this._ranges = {};
  93004. this._lastAbsoluteTransformsUpdateId = -1;
  93005. this._canUseTextureForBones = false;
  93006. /**
  93007. * Specifies if the skeleton should be serialized
  93008. */
  93009. this.doNotSerialize = false;
  93010. /**
  93011. * Gets or sets a boolean indicating that bone matrices should be stored as a texture instead of using shader uniforms (default is true).
  93012. * Please note that this option is not available when needInitialSkinMatrix === true or if the hardware does not support it
  93013. */
  93014. this.useTextureToStoreBoneMatrices = true;
  93015. this._animationPropertiesOverride = null;
  93016. // Events
  93017. /**
  93018. * An observable triggered before computing the skeleton's matrices
  93019. */
  93020. this.onBeforeComputeObservable = new BABYLON.Observable();
  93021. this.bones = [];
  93022. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93023. this._scene.skeletons.push(this);
  93024. //make sure it will recalculate the matrix next time prepare is called.
  93025. this._isDirty = true;
  93026. var engineCaps = this._scene.getEngine().getCaps();
  93027. this._canUseTextureForBones = engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0;
  93028. }
  93029. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  93030. /**
  93031. * Gets or sets the animation properties override
  93032. */
  93033. get: function () {
  93034. if (!this._animationPropertiesOverride) {
  93035. return this._scene.animationPropertiesOverride;
  93036. }
  93037. return this._animationPropertiesOverride;
  93038. },
  93039. set: function (value) {
  93040. this._animationPropertiesOverride = value;
  93041. },
  93042. enumerable: true,
  93043. configurable: true
  93044. });
  93045. Object.defineProperty(Skeleton.prototype, "isUsingTextureForMatrices", {
  93046. /**
  93047. * Gets a boolean indicating that the skeleton effectively stores matrices into a texture
  93048. */
  93049. get: function () {
  93050. return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones && !this.needInitialSkinMatrix;
  93051. },
  93052. enumerable: true,
  93053. configurable: true
  93054. });
  93055. // Members
  93056. /**
  93057. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  93058. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  93059. * @returns a Float32Array containing matrices data
  93060. */
  93061. Skeleton.prototype.getTransformMatrices = function (mesh) {
  93062. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  93063. return mesh._bonesTransformMatrices;
  93064. }
  93065. if (!this._transformMatrices) {
  93066. this.prepare();
  93067. }
  93068. return this._transformMatrices;
  93069. };
  93070. /**
  93071. * Gets the list of transform matrices to send to shaders inside a texture (one matrix per bone)
  93072. * @returns a raw texture containing the data
  93073. */
  93074. Skeleton.prototype.getTransformMatrixTexture = function () {
  93075. return this._transformMatrixTexture;
  93076. };
  93077. /**
  93078. * Gets the current hosting scene
  93079. * @returns a scene object
  93080. */
  93081. Skeleton.prototype.getScene = function () {
  93082. return this._scene;
  93083. };
  93084. // Methods
  93085. /**
  93086. * Gets a string representing the current skeleton data
  93087. * @param fullDetails defines a boolean indicating if we want a verbose version
  93088. * @returns a string representing the current skeleton data
  93089. */
  93090. Skeleton.prototype.toString = function (fullDetails) {
  93091. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  93092. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  93093. if (fullDetails) {
  93094. ret += ", Ranges: {";
  93095. var first = true;
  93096. for (var name_1 in this._ranges) {
  93097. if (first) {
  93098. ret += ", ";
  93099. first = false;
  93100. }
  93101. ret += name_1;
  93102. }
  93103. ret += "}";
  93104. }
  93105. return ret;
  93106. };
  93107. /**
  93108. * Get bone's index searching by name
  93109. * @param name defines bone's name to search for
  93110. * @return the indice of the bone. Returns -1 if not found
  93111. */
  93112. Skeleton.prototype.getBoneIndexByName = function (name) {
  93113. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  93114. if (this.bones[boneIndex].name === name) {
  93115. return boneIndex;
  93116. }
  93117. }
  93118. return -1;
  93119. };
  93120. /**
  93121. * Creater a new animation range
  93122. * @param name defines the name of the range
  93123. * @param from defines the start key
  93124. * @param to defines the end key
  93125. */
  93126. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  93127. // check name not already in use
  93128. if (!this._ranges[name]) {
  93129. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  93130. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93131. if (this.bones[i].animations[0]) {
  93132. this.bones[i].animations[0].createRange(name, from, to);
  93133. }
  93134. }
  93135. }
  93136. };
  93137. /**
  93138. * Delete a specific animation range
  93139. * @param name defines the name of the range
  93140. * @param deleteFrames defines if frames must be removed as well
  93141. */
  93142. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  93143. if (deleteFrames === void 0) { deleteFrames = true; }
  93144. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93145. if (this.bones[i].animations[0]) {
  93146. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  93147. }
  93148. }
  93149. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  93150. };
  93151. /**
  93152. * Gets a specific animation range
  93153. * @param name defines the name of the range to look for
  93154. * @returns the requested animation range or null if not found
  93155. */
  93156. Skeleton.prototype.getAnimationRange = function (name) {
  93157. return this._ranges[name];
  93158. };
  93159. /**
  93160. * Gets the list of all animation ranges defined on this skeleton
  93161. * @returns an array
  93162. */
  93163. Skeleton.prototype.getAnimationRanges = function () {
  93164. var animationRanges = [];
  93165. var name;
  93166. var i = 0;
  93167. for (name in this._ranges) {
  93168. animationRanges[i] = this._ranges[name];
  93169. i++;
  93170. }
  93171. return animationRanges;
  93172. };
  93173. /**
  93174. * Copy animation range from a source skeleton.
  93175. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  93176. * @param source defines the source skeleton
  93177. * @param name defines the name of the range to copy
  93178. * @param rescaleAsRequired defines if rescaling must be applied if required
  93179. * @returns true if operation was successful
  93180. */
  93181. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  93182. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  93183. if (this._ranges[name] || !source.getAnimationRange(name)) {
  93184. return false;
  93185. }
  93186. var ret = true;
  93187. var frameOffset = this._getHighestAnimationFrame() + 1;
  93188. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  93189. var boneDict = {};
  93190. var sourceBones = source.bones;
  93191. var nBones;
  93192. var i;
  93193. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  93194. boneDict[sourceBones[i].name] = sourceBones[i];
  93195. }
  93196. if (this.bones.length !== sourceBones.length) {
  93197. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  93198. ret = false;
  93199. }
  93200. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  93201. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  93202. var boneName = this.bones[i].name;
  93203. var sourceBone = boneDict[boneName];
  93204. if (sourceBone) {
  93205. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  93206. }
  93207. else {
  93208. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  93209. ret = false;
  93210. }
  93211. }
  93212. // do not call createAnimationRange(), since it also is done to bones, which was already done
  93213. var range = source.getAnimationRange(name);
  93214. if (range) {
  93215. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  93216. }
  93217. return ret;
  93218. };
  93219. /**
  93220. * Forces the skeleton to go to rest pose
  93221. */
  93222. Skeleton.prototype.returnToRest = function () {
  93223. for (var index = 0; index < this.bones.length; index++) {
  93224. this.bones[index].returnToRest();
  93225. }
  93226. };
  93227. Skeleton.prototype._getHighestAnimationFrame = function () {
  93228. var ret = 0;
  93229. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93230. if (this.bones[i].animations[0]) {
  93231. var highest = this.bones[i].animations[0].getHighestFrame();
  93232. if (ret < highest) {
  93233. ret = highest;
  93234. }
  93235. }
  93236. }
  93237. return ret;
  93238. };
  93239. /**
  93240. * Begin a specific animation range
  93241. * @param name defines the name of the range to start
  93242. * @param loop defines if looping must be turned on (false by default)
  93243. * @param speedRatio defines the speed ratio to apply (1 by default)
  93244. * @param onAnimationEnd defines a callback which will be called when animation will end
  93245. * @returns a new animatable
  93246. */
  93247. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  93248. var range = this.getAnimationRange(name);
  93249. if (!range) {
  93250. return null;
  93251. }
  93252. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  93253. };
  93254. /** @hidden */
  93255. Skeleton.prototype._markAsDirty = function () {
  93256. this._isDirty = true;
  93257. };
  93258. /** @hidden */
  93259. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  93260. this._meshesWithPoseMatrix.push(mesh);
  93261. };
  93262. /** @hidden */
  93263. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  93264. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  93265. if (index > -1) {
  93266. this._meshesWithPoseMatrix.splice(index, 1);
  93267. }
  93268. };
  93269. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  93270. this.onBeforeComputeObservable.notifyObservers(this);
  93271. for (var index = 0; index < this.bones.length; index++) {
  93272. var bone = this.bones[index];
  93273. var parentBone = bone.getParent();
  93274. if (parentBone) {
  93275. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  93276. }
  93277. else {
  93278. if (initialSkinMatrix) {
  93279. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  93280. }
  93281. else {
  93282. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  93283. }
  93284. }
  93285. if (bone._index !== -1) {
  93286. var mappedIndex = bone._index === null ? index : bone._index;
  93287. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  93288. }
  93289. }
  93290. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  93291. };
  93292. /**
  93293. * Build all resources required to render a skeleton
  93294. */
  93295. Skeleton.prototype.prepare = function () {
  93296. if (!this._isDirty) {
  93297. return;
  93298. }
  93299. if (this.needInitialSkinMatrix) {
  93300. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  93301. var mesh = this._meshesWithPoseMatrix[index];
  93302. var poseMatrix = mesh.getPoseMatrix();
  93303. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  93304. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  93305. }
  93306. if (this._synchronizedWithMesh !== mesh) {
  93307. this._synchronizedWithMesh = mesh;
  93308. // Prepare bones
  93309. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  93310. var bone = this.bones[boneIndex];
  93311. if (!bone.getParent()) {
  93312. var matrix = bone.getBaseMatrix();
  93313. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  93314. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  93315. }
  93316. }
  93317. }
  93318. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  93319. }
  93320. }
  93321. else {
  93322. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  93323. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  93324. if (this.isUsingTextureForMatrices) {
  93325. if (this._transformMatrixTexture) {
  93326. this._transformMatrixTexture.dispose();
  93327. }
  93328. 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);
  93329. }
  93330. }
  93331. this._computeTransformMatrices(this._transformMatrices, null);
  93332. if (this.isUsingTextureForMatrices && this._transformMatrixTexture) {
  93333. this._transformMatrixTexture.update(this._transformMatrices);
  93334. }
  93335. }
  93336. this._isDirty = false;
  93337. this._scene._activeBones.addCount(this.bones.length, false);
  93338. };
  93339. /**
  93340. * Gets the list of animatables currently running for this skeleton
  93341. * @returns an array of animatables
  93342. */
  93343. Skeleton.prototype.getAnimatables = function () {
  93344. if (!this._animatables || this._animatables.length !== this.bones.length) {
  93345. this._animatables = [];
  93346. for (var index = 0; index < this.bones.length; index++) {
  93347. this._animatables.push(this.bones[index]);
  93348. }
  93349. }
  93350. return this._animatables;
  93351. };
  93352. /**
  93353. * Clone the current skeleton
  93354. * @param name defines the name of the new skeleton
  93355. * @param id defines the id of the enw skeleton
  93356. * @returns the new skeleton
  93357. */
  93358. Skeleton.prototype.clone = function (name, id) {
  93359. var result = new Skeleton(name, id || name, this._scene);
  93360. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  93361. for (var index = 0; index < this.bones.length; index++) {
  93362. var source = this.bones[index];
  93363. var parentBone = null;
  93364. var parent_1 = source.getParent();
  93365. if (parent_1) {
  93366. var parentIndex = this.bones.indexOf(parent_1);
  93367. parentBone = result.bones[parentIndex];
  93368. }
  93369. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  93370. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  93371. }
  93372. if (this._ranges) {
  93373. result._ranges = {};
  93374. for (var rangeName in this._ranges) {
  93375. var range = this._ranges[rangeName];
  93376. if (range) {
  93377. result._ranges[rangeName] = range.clone();
  93378. }
  93379. }
  93380. }
  93381. this._isDirty = true;
  93382. return result;
  93383. };
  93384. /**
  93385. * Enable animation blending for this skeleton
  93386. * @param blendingSpeed defines the blending speed to apply
  93387. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  93388. */
  93389. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  93390. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  93391. this.bones.forEach(function (bone) {
  93392. bone.animations.forEach(function (animation) {
  93393. animation.enableBlending = true;
  93394. animation.blendingSpeed = blendingSpeed;
  93395. });
  93396. });
  93397. };
  93398. /**
  93399. * Releases all resources associated with the current skeleton
  93400. */
  93401. Skeleton.prototype.dispose = function () {
  93402. this._meshesWithPoseMatrix = [];
  93403. // Animations
  93404. this.getScene().stopAnimation(this);
  93405. // Remove from scene
  93406. this.getScene().removeSkeleton(this);
  93407. if (this._transformMatrixTexture) {
  93408. this._transformMatrixTexture.dispose();
  93409. this._transformMatrixTexture = null;
  93410. }
  93411. };
  93412. /**
  93413. * Serialize the skeleton in a JSON object
  93414. * @returns a JSON object
  93415. */
  93416. Skeleton.prototype.serialize = function () {
  93417. var serializationObject = {};
  93418. serializationObject.name = this.name;
  93419. serializationObject.id = this.id;
  93420. if (this.dimensionsAtRest) {
  93421. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  93422. }
  93423. serializationObject.bones = [];
  93424. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  93425. for (var index = 0; index < this.bones.length; index++) {
  93426. var bone = this.bones[index];
  93427. var parent_2 = bone.getParent();
  93428. var serializedBone = {
  93429. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  93430. name: bone.name,
  93431. matrix: bone.getBaseMatrix().toArray(),
  93432. rest: bone.getRestPose().toArray()
  93433. };
  93434. serializationObject.bones.push(serializedBone);
  93435. if (bone.length) {
  93436. serializedBone.length = bone.length;
  93437. }
  93438. if (bone.metadata) {
  93439. serializedBone.metadata = bone.metadata;
  93440. }
  93441. if (bone.animations && bone.animations.length > 0) {
  93442. serializedBone.animation = bone.animations[0].serialize();
  93443. }
  93444. serializationObject.ranges = [];
  93445. for (var name in this._ranges) {
  93446. var source = this._ranges[name];
  93447. if (!source) {
  93448. continue;
  93449. }
  93450. var range = {};
  93451. range.name = name;
  93452. range.from = source.from;
  93453. range.to = source.to;
  93454. serializationObject.ranges.push(range);
  93455. }
  93456. }
  93457. return serializationObject;
  93458. };
  93459. /**
  93460. * Creates a new skeleton from serialized data
  93461. * @param parsedSkeleton defines the serialized data
  93462. * @param scene defines the hosting scene
  93463. * @returns a new skeleton
  93464. */
  93465. Skeleton.Parse = function (parsedSkeleton, scene) {
  93466. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  93467. if (parsedSkeleton.dimensionsAtRest) {
  93468. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  93469. }
  93470. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  93471. var index;
  93472. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  93473. var parsedBone = parsedSkeleton.bones[index];
  93474. var parentBone = null;
  93475. if (parsedBone.parentBoneIndex > -1) {
  93476. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  93477. }
  93478. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  93479. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  93480. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  93481. bone.id = parsedBone.id;
  93482. }
  93483. if (parsedBone.length) {
  93484. bone.length = parsedBone.length;
  93485. }
  93486. if (parsedBone.metadata) {
  93487. bone.metadata = parsedBone.metadata;
  93488. }
  93489. if (parsedBone.animation) {
  93490. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  93491. }
  93492. }
  93493. // placed after bones, so createAnimationRange can cascade down
  93494. if (parsedSkeleton.ranges) {
  93495. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  93496. var data = parsedSkeleton.ranges[index];
  93497. skeleton.createAnimationRange(data.name, data.from, data.to);
  93498. }
  93499. }
  93500. return skeleton;
  93501. };
  93502. /**
  93503. * Compute all node absolute transforms
  93504. * @param forceUpdate defines if computation must be done even if cache is up to date
  93505. */
  93506. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  93507. if (forceUpdate === void 0) { forceUpdate = false; }
  93508. var renderId = this._scene.getRenderId();
  93509. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  93510. this.bones[0].computeAbsoluteTransforms();
  93511. this._lastAbsoluteTransformsUpdateId = renderId;
  93512. }
  93513. };
  93514. /**
  93515. * Gets the root pose matrix
  93516. * @returns a matrix
  93517. */
  93518. Skeleton.prototype.getPoseMatrix = function () {
  93519. var poseMatrix = null;
  93520. if (this._meshesWithPoseMatrix.length > 0) {
  93521. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  93522. }
  93523. return poseMatrix;
  93524. };
  93525. /**
  93526. * Sorts bones per internal index
  93527. */
  93528. Skeleton.prototype.sortBones = function () {
  93529. var bones = new Array();
  93530. var visited = new Array(this.bones.length);
  93531. for (var index = 0; index < this.bones.length; index++) {
  93532. this._sortBones(index, bones, visited);
  93533. }
  93534. this.bones = bones;
  93535. };
  93536. Skeleton.prototype._sortBones = function (index, bones, visited) {
  93537. if (visited[index]) {
  93538. return;
  93539. }
  93540. visited[index] = true;
  93541. var bone = this.bones[index];
  93542. if (bone._index === undefined) {
  93543. bone._index = index;
  93544. }
  93545. var parentBone = bone.getParent();
  93546. if (parentBone) {
  93547. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  93548. }
  93549. bones.push(bone);
  93550. };
  93551. return Skeleton;
  93552. }());
  93553. BABYLON.Skeleton = Skeleton;
  93554. })(BABYLON || (BABYLON = {}));
  93555. //# sourceMappingURL=babylon.skeleton.js.map
  93556. var BABYLON;
  93557. (function (BABYLON) {
  93558. /**
  93559. * This groups tools to convert HDR texture to native colors array.
  93560. */
  93561. var HDRTools = /** @class */ (function () {
  93562. function HDRTools() {
  93563. }
  93564. HDRTools.Ldexp = function (mantissa, exponent) {
  93565. if (exponent > 1023) {
  93566. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  93567. }
  93568. if (exponent < -1074) {
  93569. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  93570. }
  93571. return mantissa * Math.pow(2, exponent);
  93572. };
  93573. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  93574. if (exponent > 0) { /*nonzero pixel*/
  93575. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  93576. float32array[index + 0] = red * exponent;
  93577. float32array[index + 1] = green * exponent;
  93578. float32array[index + 2] = blue * exponent;
  93579. }
  93580. else {
  93581. float32array[index + 0] = 0;
  93582. float32array[index + 1] = 0;
  93583. float32array[index + 2] = 0;
  93584. }
  93585. };
  93586. HDRTools.readStringLine = function (uint8array, startIndex) {
  93587. var line = "";
  93588. var character = "";
  93589. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  93590. character = String.fromCharCode(uint8array[i]);
  93591. if (character == "\n") {
  93592. break;
  93593. }
  93594. line += character;
  93595. }
  93596. return line;
  93597. };
  93598. /**
  93599. * Reads header information from an RGBE texture stored in a native array.
  93600. * More information on this format are available here:
  93601. * https://en.wikipedia.org/wiki/RGBE_image_format
  93602. *
  93603. * @param uint8array The binary file stored in native array.
  93604. * @return The header information.
  93605. */
  93606. HDRTools.RGBE_ReadHeader = function (uint8array) {
  93607. var height = 0;
  93608. var width = 0;
  93609. var line = this.readStringLine(uint8array, 0);
  93610. if (line[0] != '#' || line[1] != '?') {
  93611. throw "Bad HDR Format.";
  93612. }
  93613. var endOfHeader = false;
  93614. var findFormat = false;
  93615. var lineIndex = 0;
  93616. do {
  93617. lineIndex += (line.length + 1);
  93618. line = this.readStringLine(uint8array, lineIndex);
  93619. if (line == "FORMAT=32-bit_rle_rgbe") {
  93620. findFormat = true;
  93621. }
  93622. else if (line.length == 0) {
  93623. endOfHeader = true;
  93624. }
  93625. } while (!endOfHeader);
  93626. if (!findFormat) {
  93627. throw "HDR Bad header format, unsupported FORMAT";
  93628. }
  93629. lineIndex += (line.length + 1);
  93630. line = this.readStringLine(uint8array, lineIndex);
  93631. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  93632. var match = sizeRegexp.exec(line);
  93633. // TODO. Support +Y and -X if needed.
  93634. if (!match || match.length < 3) {
  93635. throw "HDR Bad header format, no size";
  93636. }
  93637. width = parseInt(match[2]);
  93638. height = parseInt(match[1]);
  93639. if (width < 8 || width > 0x7fff) {
  93640. throw "HDR Bad header format, unsupported size";
  93641. }
  93642. lineIndex += (line.length + 1);
  93643. return {
  93644. height: height,
  93645. width: width,
  93646. dataPosition: lineIndex
  93647. };
  93648. };
  93649. /**
  93650. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  93651. * This RGBE texture needs to store the information as a panorama.
  93652. *
  93653. * More information on this format are available here:
  93654. * https://en.wikipedia.org/wiki/RGBE_image_format
  93655. *
  93656. * @param buffer The binary file stored in an array buffer.
  93657. * @param size The expected size of the extracted cubemap.
  93658. * @return The Cube Map information.
  93659. */
  93660. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  93661. var uint8array = new Uint8Array(buffer);
  93662. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  93663. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  93664. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  93665. return cubeMapData;
  93666. };
  93667. /**
  93668. * Returns the pixels data extracted from an RGBE texture.
  93669. * This pixels will be stored left to right up to down in the R G B order in one array.
  93670. *
  93671. * More information on this format are available here:
  93672. * https://en.wikipedia.org/wiki/RGBE_image_format
  93673. *
  93674. * @param uint8array The binary file stored in an array buffer.
  93675. * @param hdrInfo The header information of the file.
  93676. * @return The pixels data in RGB right to left up to down order.
  93677. */
  93678. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  93679. // Keep for multi format supports.
  93680. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  93681. };
  93682. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  93683. var num_scanlines = hdrInfo.height;
  93684. var scanline_width = hdrInfo.width;
  93685. var a, b, c, d, count;
  93686. var dataIndex = hdrInfo.dataPosition;
  93687. var index = 0, endIndex = 0, i = 0;
  93688. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  93689. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  93690. // 3 channels of 4 bytes per pixel in float.
  93691. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  93692. var resultArray = new Float32Array(resultBuffer);
  93693. // read in each successive scanline
  93694. while (num_scanlines > 0) {
  93695. a = uint8array[dataIndex++];
  93696. b = uint8array[dataIndex++];
  93697. c = uint8array[dataIndex++];
  93698. d = uint8array[dataIndex++];
  93699. if (a != 2 || b != 2 || (c & 0x80)) {
  93700. // this file is not run length encoded
  93701. throw "HDR Bad header format, not RLE";
  93702. }
  93703. if (((c << 8) | d) != scanline_width) {
  93704. throw "HDR Bad header format, wrong scan line width";
  93705. }
  93706. index = 0;
  93707. // read each of the four channels for the scanline into the buffer
  93708. for (i = 0; i < 4; i++) {
  93709. endIndex = (i + 1) * scanline_width;
  93710. while (index < endIndex) {
  93711. a = uint8array[dataIndex++];
  93712. b = uint8array[dataIndex++];
  93713. if (a > 128) {
  93714. // a run of the same value
  93715. count = a - 128;
  93716. if ((count == 0) || (count > endIndex - index)) {
  93717. throw "HDR Bad Format, bad scanline data (run)";
  93718. }
  93719. while (count-- > 0) {
  93720. scanLineArray[index++] = b;
  93721. }
  93722. }
  93723. else {
  93724. // a non-run
  93725. count = a;
  93726. if ((count == 0) || (count > endIndex - index)) {
  93727. throw "HDR Bad Format, bad scanline data (non-run)";
  93728. }
  93729. scanLineArray[index++] = b;
  93730. if (--count > 0) {
  93731. for (var j = 0; j < count; j++) {
  93732. scanLineArray[index++] = uint8array[dataIndex++];
  93733. }
  93734. }
  93735. }
  93736. }
  93737. }
  93738. // now convert data from buffer into floats
  93739. for (i = 0; i < scanline_width; i++) {
  93740. a = scanLineArray[i];
  93741. b = scanLineArray[i + scanline_width];
  93742. c = scanLineArray[i + 2 * scanline_width];
  93743. d = scanLineArray[i + 3 * scanline_width];
  93744. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  93745. }
  93746. num_scanlines--;
  93747. }
  93748. return resultArray;
  93749. };
  93750. return HDRTools;
  93751. }());
  93752. BABYLON.HDRTools = HDRTools;
  93753. })(BABYLON || (BABYLON = {}));
  93754. //# sourceMappingURL=babylon.hdr.js.map
  93755. var BABYLON;
  93756. (function (BABYLON) {
  93757. /**
  93758. * This represents a texture coming from an HDR input.
  93759. *
  93760. * The only supported format is currently panorama picture stored in RGBE format.
  93761. * Example of such files can be found on HDRLib: http://hdrlib.com/
  93762. */
  93763. var HDRCubeTexture = /** @class */ (function (_super) {
  93764. __extends(HDRCubeTexture, _super);
  93765. /**
  93766. * Instantiates an HDRTexture from the following parameters.
  93767. *
  93768. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  93769. * @param scene The scene the texture will be used in
  93770. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  93771. * @param noMipmap Forces to not generate the mipmap if true
  93772. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  93773. * @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)
  93774. * @param reserved Reserved flag for internal use.
  93775. */
  93776. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  93777. if (noMipmap === void 0) { noMipmap = false; }
  93778. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93779. if (gammaSpace === void 0) { gammaSpace = false; }
  93780. if (reserved === void 0) { reserved = false; }
  93781. if (onLoad === void 0) { onLoad = null; }
  93782. if (onError === void 0) { onError = null; }
  93783. var _this = _super.call(this, scene) || this;
  93784. _this._generateHarmonics = true;
  93785. _this._onLoad = null;
  93786. _this._onError = null;
  93787. /**
  93788. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  93789. */
  93790. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  93791. _this._isBlocking = true;
  93792. _this._rotationY = 0;
  93793. /**
  93794. * Gets or sets the center of the bounding box associated with the cube texture
  93795. * It must define where the camera used to render the texture was set
  93796. */
  93797. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  93798. if (!url) {
  93799. return _this;
  93800. }
  93801. _this.name = url;
  93802. _this.url = url;
  93803. _this.hasAlpha = false;
  93804. _this.isCube = true;
  93805. _this._textureMatrix = BABYLON.Matrix.Identity();
  93806. _this._onLoad = onLoad;
  93807. _this._onError = onError;
  93808. _this.gammaSpace = gammaSpace;
  93809. _this._noMipmap = noMipmap;
  93810. _this._size = size;
  93811. _this._texture = _this._getFromCache(url, _this._noMipmap);
  93812. if (!_this._texture) {
  93813. if (!scene.useDelayedTextureLoading) {
  93814. _this.loadTexture();
  93815. }
  93816. else {
  93817. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  93818. }
  93819. }
  93820. return _this;
  93821. }
  93822. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  93823. /**
  93824. * Gets wether or not the texture is blocking during loading.
  93825. */
  93826. get: function () {
  93827. return this._isBlocking;
  93828. },
  93829. /**
  93830. * Sets wether or not the texture is blocking during loading.
  93831. */
  93832. set: function (value) {
  93833. this._isBlocking = value;
  93834. },
  93835. enumerable: true,
  93836. configurable: true
  93837. });
  93838. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  93839. /**
  93840. * Gets texture matrix rotation angle around Y axis radians.
  93841. */
  93842. get: function () {
  93843. return this._rotationY;
  93844. },
  93845. /**
  93846. * Sets texture matrix rotation angle around Y axis in radians.
  93847. */
  93848. set: function (value) {
  93849. this._rotationY = value;
  93850. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  93851. },
  93852. enumerable: true,
  93853. configurable: true
  93854. });
  93855. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  93856. get: function () {
  93857. return this._boundingBoxSize;
  93858. },
  93859. /**
  93860. * Gets or sets the size of the bounding box associated with the cube texture
  93861. * When defined, the cubemap will switch to local mode
  93862. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  93863. * @example https://www.babylonjs-playground.com/#RNASML
  93864. */
  93865. set: function (value) {
  93866. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  93867. return;
  93868. }
  93869. this._boundingBoxSize = value;
  93870. var scene = this.getScene();
  93871. if (scene) {
  93872. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  93873. }
  93874. },
  93875. enumerable: true,
  93876. configurable: true
  93877. });
  93878. /**
  93879. * Occurs when the file is raw .hdr file.
  93880. */
  93881. HDRCubeTexture.prototype.loadTexture = function () {
  93882. var _this = this;
  93883. var callback = function (buffer) {
  93884. _this.lodGenerationOffset = 0.0;
  93885. _this.lodGenerationScale = 0.8;
  93886. var scene = _this.getScene();
  93887. if (!scene) {
  93888. return null;
  93889. }
  93890. // Extract the raw linear data.
  93891. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  93892. // Generate harmonics if needed.
  93893. if (_this._generateHarmonics) {
  93894. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  93895. _this.sphericalPolynomial = sphericalPolynomial;
  93896. }
  93897. var results = [];
  93898. var byteArray = null;
  93899. // Push each faces.
  93900. for (var j = 0; j < 6; j++) {
  93901. // Create uintarray fallback.
  93902. if (!scene.getEngine().getCaps().textureFloat) {
  93903. // 3 channels of 1 bytes per pixel in bytes.
  93904. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  93905. byteArray = new Uint8Array(byteBuffer);
  93906. }
  93907. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  93908. // If special cases.
  93909. if (_this.gammaSpace || byteArray) {
  93910. for (var i = 0; i < _this._size * _this._size; i++) {
  93911. // Put in gamma space if requested.
  93912. if (_this.gammaSpace) {
  93913. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  93914. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  93915. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  93916. }
  93917. // Convert to int texture for fallback.
  93918. if (byteArray) {
  93919. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  93920. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  93921. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  93922. // May use luminance instead if the result is not accurate.
  93923. var max = Math.max(Math.max(r, g), b);
  93924. if (max > 255) {
  93925. var scale = 255 / max;
  93926. r *= scale;
  93927. g *= scale;
  93928. b *= scale;
  93929. }
  93930. byteArray[(i * 3) + 0] = r;
  93931. byteArray[(i * 3) + 1] = g;
  93932. byteArray[(i * 3) + 2] = b;
  93933. }
  93934. }
  93935. }
  93936. if (byteArray) {
  93937. results.push(byteArray);
  93938. }
  93939. else {
  93940. results.push(dataFace);
  93941. }
  93942. }
  93943. return results;
  93944. };
  93945. var scene = this.getScene();
  93946. if (scene) {
  93947. 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);
  93948. }
  93949. };
  93950. HDRCubeTexture.prototype.clone = function () {
  93951. var scene = this.getScene();
  93952. if (!scene) {
  93953. return this;
  93954. }
  93955. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  93956. // Base texture
  93957. newTexture.level = this.level;
  93958. newTexture.wrapU = this.wrapU;
  93959. newTexture.wrapV = this.wrapV;
  93960. newTexture.coordinatesIndex = this.coordinatesIndex;
  93961. newTexture.coordinatesMode = this.coordinatesMode;
  93962. return newTexture;
  93963. };
  93964. // Methods
  93965. HDRCubeTexture.prototype.delayLoad = function () {
  93966. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  93967. return;
  93968. }
  93969. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  93970. this._texture = this._getFromCache(this.url, this._noMipmap);
  93971. if (!this._texture) {
  93972. this.loadTexture();
  93973. }
  93974. };
  93975. /**
  93976. * Get the texture reflection matrix used to rotate/transform the reflection.
  93977. * @returns the reflection matrix
  93978. */
  93979. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  93980. return this._textureMatrix;
  93981. };
  93982. /**
  93983. * Set the texture reflection matrix used to rotate/transform the reflection.
  93984. * @param value Define the reflection matrix to set
  93985. */
  93986. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  93987. this._textureMatrix = value;
  93988. };
  93989. /**
  93990. * Parses a JSON representation of an HDR Texture in order to create the texture
  93991. * @param parsedTexture Define the JSON representation
  93992. * @param scene Define the scene the texture should be created in
  93993. * @param rootUrl Define the root url in case we need to load relative dependencies
  93994. * @returns the newly created texture after parsing
  93995. */
  93996. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  93997. var texture = null;
  93998. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  93999. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  94000. texture.name = parsedTexture.name;
  94001. texture.hasAlpha = parsedTexture.hasAlpha;
  94002. texture.level = parsedTexture.level;
  94003. texture.coordinatesMode = parsedTexture.coordinatesMode;
  94004. texture.isBlocking = parsedTexture.isBlocking;
  94005. }
  94006. if (texture) {
  94007. if (parsedTexture.boundingBoxPosition) {
  94008. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  94009. }
  94010. if (parsedTexture.boundingBoxSize) {
  94011. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  94012. }
  94013. if (parsedTexture.rotationY) {
  94014. texture.rotationY = parsedTexture.rotationY;
  94015. }
  94016. }
  94017. return texture;
  94018. };
  94019. HDRCubeTexture.prototype.serialize = function () {
  94020. if (!this.name) {
  94021. return null;
  94022. }
  94023. var serializationObject = {};
  94024. serializationObject.name = this.name;
  94025. serializationObject.hasAlpha = this.hasAlpha;
  94026. serializationObject.isCube = true;
  94027. serializationObject.level = this.level;
  94028. serializationObject.size = this._size;
  94029. serializationObject.coordinatesMode = this.coordinatesMode;
  94030. serializationObject.useInGammaSpace = this.gammaSpace;
  94031. serializationObject.generateHarmonics = this._generateHarmonics;
  94032. serializationObject.customType = "BABYLON.HDRCubeTexture";
  94033. serializationObject.noMipmap = this._noMipmap;
  94034. serializationObject.isBlocking = this._isBlocking;
  94035. serializationObject.rotationY = this._rotationY;
  94036. return serializationObject;
  94037. };
  94038. HDRCubeTexture._facesMapping = [
  94039. "right",
  94040. "left",
  94041. "up",
  94042. "down",
  94043. "front",
  94044. "back"
  94045. ];
  94046. return HDRCubeTexture;
  94047. }(BABYLON.BaseTexture));
  94048. BABYLON.HDRCubeTexture = HDRCubeTexture;
  94049. })(BABYLON || (BABYLON = {}));
  94050. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  94051. var BABYLON;
  94052. (function (BABYLON) {
  94053. /**
  94054. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  94055. */
  94056. var PanoramaToCubeMapTools = /** @class */ (function () {
  94057. function PanoramaToCubeMapTools() {
  94058. }
  94059. /**
  94060. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  94061. *
  94062. * @param float32Array The source data.
  94063. * @param inputWidth The width of the input panorama.
  94064. * @param inputHeight The height of the input panorama.
  94065. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  94066. * @return The cubemap data
  94067. */
  94068. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  94069. if (!float32Array) {
  94070. throw "ConvertPanoramaToCubemap: input cannot be null";
  94071. }
  94072. if (float32Array.length != inputWidth * inputHeight * 3) {
  94073. throw "ConvertPanoramaToCubemap: input size is wrong";
  94074. }
  94075. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  94076. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  94077. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  94078. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  94079. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  94080. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  94081. return {
  94082. front: textureFront,
  94083. back: textureBack,
  94084. left: textureLeft,
  94085. right: textureRight,
  94086. up: textureUp,
  94087. down: textureDown,
  94088. size: size,
  94089. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  94090. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  94091. gammaSpace: false,
  94092. };
  94093. };
  94094. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  94095. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  94096. var textureArray = new Float32Array(buffer);
  94097. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  94098. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  94099. var dy = 1 / texSize;
  94100. var fy = 0;
  94101. for (var y = 0; y < texSize; y++) {
  94102. var xv1 = faceData[0];
  94103. var xv2 = faceData[2];
  94104. for (var x = 0; x < texSize; x++) {
  94105. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  94106. v.normalize();
  94107. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  94108. // 3 channels per pixels
  94109. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  94110. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  94111. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  94112. xv1 = xv1.add(rotDX1);
  94113. xv2 = xv2.add(rotDX2);
  94114. }
  94115. fy += dy;
  94116. }
  94117. return textureArray;
  94118. };
  94119. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  94120. var theta = Math.atan2(vDir.z, vDir.x);
  94121. var phi = Math.acos(vDir.y);
  94122. while (theta < -Math.PI) {
  94123. theta += 2 * Math.PI;
  94124. }
  94125. while (theta > Math.PI) {
  94126. theta -= 2 * Math.PI;
  94127. }
  94128. var dx = theta / Math.PI;
  94129. var dy = phi / Math.PI;
  94130. // recenter.
  94131. dx = dx * 0.5 + 0.5;
  94132. var px = Math.round(dx * inputWidth);
  94133. if (px < 0) {
  94134. px = 0;
  94135. }
  94136. else if (px >= inputWidth) {
  94137. px = inputWidth - 1;
  94138. }
  94139. var py = Math.round(dy * inputHeight);
  94140. if (py < 0) {
  94141. py = 0;
  94142. }
  94143. else if (py >= inputHeight) {
  94144. py = inputHeight - 1;
  94145. }
  94146. var inputY = (inputHeight - py - 1);
  94147. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  94148. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  94149. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  94150. return {
  94151. r: r,
  94152. g: g,
  94153. b: b
  94154. };
  94155. };
  94156. PanoramaToCubeMapTools.FACE_FRONT = [
  94157. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94158. new BABYLON.Vector3(1.0, -1.0, -1.0),
  94159. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  94160. new BABYLON.Vector3(1.0, 1.0, -1.0)
  94161. ];
  94162. PanoramaToCubeMapTools.FACE_BACK = [
  94163. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94164. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94165. new BABYLON.Vector3(1.0, 1.0, 1.0),
  94166. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  94167. ];
  94168. PanoramaToCubeMapTools.FACE_RIGHT = [
  94169. new BABYLON.Vector3(1.0, -1.0, -1.0),
  94170. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94171. new BABYLON.Vector3(1.0, 1.0, -1.0),
  94172. new BABYLON.Vector3(1.0, 1.0, 1.0)
  94173. ];
  94174. PanoramaToCubeMapTools.FACE_LEFT = [
  94175. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94176. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94177. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  94178. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  94179. ];
  94180. PanoramaToCubeMapTools.FACE_DOWN = [
  94181. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  94182. new BABYLON.Vector3(1.0, 1.0, -1.0),
  94183. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  94184. new BABYLON.Vector3(1.0, 1.0, 1.0)
  94185. ];
  94186. PanoramaToCubeMapTools.FACE_UP = [
  94187. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94188. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94189. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94190. new BABYLON.Vector3(1.0, -1.0, -1.0)
  94191. ];
  94192. return PanoramaToCubeMapTools;
  94193. }());
  94194. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  94195. })(BABYLON || (BABYLON = {}));
  94196. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  94197. var BABYLON;
  94198. (function (BABYLON) {
  94199. /**
  94200. * Vector2 wth index property
  94201. */
  94202. var IndexedVector2 = /** @class */ (function (_super) {
  94203. __extends(IndexedVector2, _super);
  94204. function IndexedVector2(original,
  94205. /** Index of the vector2 */
  94206. index) {
  94207. var _this = _super.call(this, original.x, original.y) || this;
  94208. _this.index = index;
  94209. return _this;
  94210. }
  94211. return IndexedVector2;
  94212. }(BABYLON.Vector2));
  94213. /**
  94214. * Defines points to create a polygon
  94215. */
  94216. var PolygonPoints = /** @class */ (function () {
  94217. function PolygonPoints() {
  94218. this.elements = new Array();
  94219. }
  94220. PolygonPoints.prototype.add = function (originalPoints) {
  94221. var _this = this;
  94222. var result = new Array();
  94223. originalPoints.forEach(function (point) {
  94224. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  94225. var newPoint = new IndexedVector2(point, _this.elements.length);
  94226. result.push(newPoint);
  94227. _this.elements.push(newPoint);
  94228. }
  94229. });
  94230. return result;
  94231. };
  94232. PolygonPoints.prototype.computeBounds = function () {
  94233. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  94234. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  94235. this.elements.forEach(function (point) {
  94236. // x
  94237. if (point.x < lmin.x) {
  94238. lmin.x = point.x;
  94239. }
  94240. else if (point.x > lmax.x) {
  94241. lmax.x = point.x;
  94242. }
  94243. // y
  94244. if (point.y < lmin.y) {
  94245. lmin.y = point.y;
  94246. }
  94247. else if (point.y > lmax.y) {
  94248. lmax.y = point.y;
  94249. }
  94250. });
  94251. return {
  94252. min: lmin,
  94253. max: lmax,
  94254. width: lmax.x - lmin.x,
  94255. height: lmax.y - lmin.y
  94256. };
  94257. };
  94258. return PolygonPoints;
  94259. }());
  94260. /**
  94261. * Polygon
  94262. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  94263. */
  94264. var Polygon = /** @class */ (function () {
  94265. function Polygon() {
  94266. }
  94267. /**
  94268. * Creates a rectangle
  94269. * @param xmin bottom X coord
  94270. * @param ymin bottom Y coord
  94271. * @param xmax top X coord
  94272. * @param ymax top Y coord
  94273. * @returns points that make the resulting rectation
  94274. */
  94275. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  94276. return [
  94277. new BABYLON.Vector2(xmin, ymin),
  94278. new BABYLON.Vector2(xmax, ymin),
  94279. new BABYLON.Vector2(xmax, ymax),
  94280. new BABYLON.Vector2(xmin, ymax)
  94281. ];
  94282. };
  94283. /**
  94284. * Creates a circle
  94285. * @param radius radius of circle
  94286. * @param cx scale in x
  94287. * @param cy scale in y
  94288. * @param numberOfSides number of sides that make up the circle
  94289. * @returns points that make the resulting circle
  94290. */
  94291. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  94292. if (cx === void 0) { cx = 0; }
  94293. if (cy === void 0) { cy = 0; }
  94294. if (numberOfSides === void 0) { numberOfSides = 32; }
  94295. var result = new Array();
  94296. var angle = 0;
  94297. var increment = (Math.PI * 2) / numberOfSides;
  94298. for (var i = 0; i < numberOfSides; i++) {
  94299. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  94300. angle -= increment;
  94301. }
  94302. return result;
  94303. };
  94304. /**
  94305. * Creates a polygon from input string
  94306. * @param input Input polygon data
  94307. * @returns the parsed points
  94308. */
  94309. Polygon.Parse = function (input) {
  94310. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  94311. var i, result = [];
  94312. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  94313. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  94314. }
  94315. return result;
  94316. };
  94317. /**
  94318. * Starts building a polygon from x and y coordinates
  94319. * @param x x coordinate
  94320. * @param y y coordinate
  94321. * @returns the started path2
  94322. */
  94323. Polygon.StartingAt = function (x, y) {
  94324. return BABYLON.Path2.StartingAt(x, y);
  94325. };
  94326. return Polygon;
  94327. }());
  94328. BABYLON.Polygon = Polygon;
  94329. /**
  94330. * Builds a polygon
  94331. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  94332. */
  94333. var PolygonMeshBuilder = /** @class */ (function () {
  94334. /**
  94335. * Creates a PolygonMeshBuilder
  94336. * @param name name of the builder
  94337. * @param contours Path of the polygon
  94338. * @param scene scene to add to
  94339. */
  94340. function PolygonMeshBuilder(name, contours, scene) {
  94341. this._points = new PolygonPoints();
  94342. this._outlinepoints = new PolygonPoints();
  94343. this._holes = new Array();
  94344. this._epoints = new Array();
  94345. this._eholes = new Array();
  94346. this._name = name;
  94347. this._scene = scene;
  94348. var points;
  94349. if (contours instanceof BABYLON.Path2) {
  94350. points = contours.getPoints();
  94351. }
  94352. else {
  94353. points = contours;
  94354. }
  94355. this._addToepoint(points);
  94356. this._points.add(points);
  94357. this._outlinepoints.add(points);
  94358. if (typeof earcut === 'undefined') {
  94359. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  94360. }
  94361. }
  94362. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  94363. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  94364. var p = points_1[_i];
  94365. this._epoints.push(p.x, p.y);
  94366. }
  94367. };
  94368. /**
  94369. * Adds a whole within the polygon
  94370. * @param hole Array of points defining the hole
  94371. * @returns this
  94372. */
  94373. PolygonMeshBuilder.prototype.addHole = function (hole) {
  94374. this._points.add(hole);
  94375. var holepoints = new PolygonPoints();
  94376. holepoints.add(hole);
  94377. this._holes.push(holepoints);
  94378. this._eholes.push(this._epoints.length / 2);
  94379. this._addToepoint(hole);
  94380. return this;
  94381. };
  94382. /**
  94383. * Creates the polygon
  94384. * @param updatable If the mesh should be updatable
  94385. * @param depth The depth of the mesh created
  94386. * @returns the created mesh
  94387. */
  94388. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  94389. var _this = this;
  94390. if (updatable === void 0) { updatable = false; }
  94391. if (depth === void 0) { depth = 0; }
  94392. var result = new BABYLON.Mesh(this._name, this._scene);
  94393. var normals = new Array();
  94394. var positions = new Array();
  94395. var uvs = new Array();
  94396. var bounds = this._points.computeBounds();
  94397. this._points.elements.forEach(function (p) {
  94398. normals.push(0, 1.0, 0);
  94399. positions.push(p.x, 0, p.y);
  94400. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  94401. });
  94402. var indices = new Array();
  94403. var res = earcut(this._epoints, this._eholes, 2);
  94404. for (var i = 0; i < res.length; i++) {
  94405. indices.push(res[i]);
  94406. }
  94407. if (depth > 0) {
  94408. var positionscount = (positions.length / 3); //get the current pointcount
  94409. this._points.elements.forEach(function (p) {
  94410. normals.push(0, -1.0, 0);
  94411. positions.push(p.x, -depth, p.y);
  94412. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  94413. });
  94414. var totalCount = indices.length;
  94415. for (var i = 0; i < totalCount; i += 3) {
  94416. var i0 = indices[i + 0];
  94417. var i1 = indices[i + 1];
  94418. var i2 = indices[i + 2];
  94419. indices.push(i2 + positionscount);
  94420. indices.push(i1 + positionscount);
  94421. indices.push(i0 + positionscount);
  94422. }
  94423. //Add the sides
  94424. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  94425. this._holes.forEach(function (hole) {
  94426. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  94427. });
  94428. }
  94429. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  94430. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  94431. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  94432. result.setIndices(indices);
  94433. return result;
  94434. };
  94435. /**
  94436. * Adds a side to the polygon
  94437. * @param positions points that make the polygon
  94438. * @param normals normals of the polygon
  94439. * @param uvs uvs of the polygon
  94440. * @param indices indices of the polygon
  94441. * @param bounds bounds of the polygon
  94442. * @param points points of the polygon
  94443. * @param depth depth of the polygon
  94444. * @param flip flip of the polygon
  94445. */
  94446. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  94447. var StartIndex = positions.length / 3;
  94448. var ulength = 0;
  94449. for (var i = 0; i < points.elements.length; i++) {
  94450. var p = points.elements[i];
  94451. var p1;
  94452. if ((i + 1) > points.elements.length - 1) {
  94453. p1 = points.elements[0];
  94454. }
  94455. else {
  94456. p1 = points.elements[i + 1];
  94457. }
  94458. positions.push(p.x, 0, p.y);
  94459. positions.push(p.x, -depth, p.y);
  94460. positions.push(p1.x, 0, p1.y);
  94461. positions.push(p1.x, -depth, p1.y);
  94462. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  94463. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  94464. var v3 = v2.subtract(v1);
  94465. var v4 = new BABYLON.Vector3(0, 1, 0);
  94466. var vn = BABYLON.Vector3.Cross(v3, v4);
  94467. vn = vn.normalize();
  94468. uvs.push(ulength / bounds.width, 0);
  94469. uvs.push(ulength / bounds.width, 1);
  94470. ulength += v3.length();
  94471. uvs.push((ulength / bounds.width), 0);
  94472. uvs.push((ulength / bounds.width), 1);
  94473. if (!flip) {
  94474. normals.push(-vn.x, -vn.y, -vn.z);
  94475. normals.push(-vn.x, -vn.y, -vn.z);
  94476. normals.push(-vn.x, -vn.y, -vn.z);
  94477. normals.push(-vn.x, -vn.y, -vn.z);
  94478. indices.push(StartIndex);
  94479. indices.push(StartIndex + 1);
  94480. indices.push(StartIndex + 2);
  94481. indices.push(StartIndex + 1);
  94482. indices.push(StartIndex + 3);
  94483. indices.push(StartIndex + 2);
  94484. }
  94485. else {
  94486. normals.push(vn.x, vn.y, vn.z);
  94487. normals.push(vn.x, vn.y, vn.z);
  94488. normals.push(vn.x, vn.y, vn.z);
  94489. normals.push(vn.x, vn.y, vn.z);
  94490. indices.push(StartIndex);
  94491. indices.push(StartIndex + 2);
  94492. indices.push(StartIndex + 1);
  94493. indices.push(StartIndex + 1);
  94494. indices.push(StartIndex + 2);
  94495. indices.push(StartIndex + 3);
  94496. }
  94497. StartIndex += 4;
  94498. }
  94499. };
  94500. return PolygonMeshBuilder;
  94501. }());
  94502. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  94503. })(BABYLON || (BABYLON = {}));
  94504. //# sourceMappingURL=babylon.polygonMesh.js.map
  94505. var BABYLON;
  94506. (function (BABYLON) {
  94507. /**
  94508. * Unique ID when we import meshes from Babylon to CSG
  94509. */
  94510. var currentCSGMeshId = 0;
  94511. /**
  94512. * Represents a vertex of a polygon. Use your own vertex class instead of this
  94513. * one to provide additional features like texture coordinates and vertex
  94514. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  94515. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  94516. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  94517. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  94518. * is not used anywhere else.
  94519. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  94520. */
  94521. var Vertex = /** @class */ (function () {
  94522. /**
  94523. * Initializes the vertex
  94524. * @param pos The position of the vertex
  94525. * @param normal The normal of the vertex
  94526. * @param uv The texture coordinate of the vertex
  94527. */
  94528. function Vertex(
  94529. /**
  94530. * The position of the vertex
  94531. */
  94532. pos,
  94533. /**
  94534. * The normal of the vertex
  94535. */
  94536. normal,
  94537. /**
  94538. * The texture coordinate of the vertex
  94539. */
  94540. uv) {
  94541. this.pos = pos;
  94542. this.normal = normal;
  94543. this.uv = uv;
  94544. }
  94545. /**
  94546. * Make a clone, or deep copy, of the vertex
  94547. * @returns A new Vertex
  94548. */
  94549. Vertex.prototype.clone = function () {
  94550. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  94551. };
  94552. /**
  94553. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  94554. * orientation of a polygon is flipped.
  94555. */
  94556. Vertex.prototype.flip = function () {
  94557. this.normal = this.normal.scale(-1);
  94558. };
  94559. /**
  94560. * Create a new vertex between this vertex and `other` by linearly
  94561. * interpolating all properties using a parameter of `t`. Subclasses should
  94562. * override this to interpolate additional properties.
  94563. * @param other the vertex to interpolate against
  94564. * @param t The factor used to linearly interpolate between the vertices
  94565. */
  94566. Vertex.prototype.interpolate = function (other, t) {
  94567. 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));
  94568. };
  94569. return Vertex;
  94570. }());
  94571. /**
  94572. * Represents a plane in 3D space.
  94573. */
  94574. var Plane = /** @class */ (function () {
  94575. /**
  94576. * Initializes the plane
  94577. * @param normal The normal for the plane
  94578. * @param w
  94579. */
  94580. function Plane(normal, w) {
  94581. this.normal = normal;
  94582. this.w = w;
  94583. }
  94584. /**
  94585. * Construct a plane from three points
  94586. * @param a Point a
  94587. * @param b Point b
  94588. * @param c Point c
  94589. */
  94590. Plane.FromPoints = function (a, b, c) {
  94591. var v0 = c.subtract(a);
  94592. var v1 = b.subtract(a);
  94593. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  94594. return null;
  94595. }
  94596. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  94597. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  94598. };
  94599. /**
  94600. * Clone, or make a deep copy of the plane
  94601. * @returns a new Plane
  94602. */
  94603. Plane.prototype.clone = function () {
  94604. return new Plane(this.normal.clone(), this.w);
  94605. };
  94606. /**
  94607. * Flip the face of the plane
  94608. */
  94609. Plane.prototype.flip = function () {
  94610. this.normal.scaleInPlace(-1);
  94611. this.w = -this.w;
  94612. };
  94613. /**
  94614. * Split `polygon` by this plane if needed, then put the polygon or polygon
  94615. * fragments in the appropriate lists. Coplanar polygons go into either
  94616. `* coplanarFront` or `coplanarBack` depending on their orientation with
  94617. * respect to this plane. Polygons in front or in back of this plane go into
  94618. * either `front` or `back`
  94619. * @param polygon The polygon to be split
  94620. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  94621. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  94622. * @param front Will contain the polygons in front of the plane
  94623. * @param back Will contain the polygons begind the plane
  94624. */
  94625. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  94626. var COPLANAR = 0;
  94627. var FRONT = 1;
  94628. var BACK = 2;
  94629. var SPANNING = 3;
  94630. // Classify each point as well as the entire polygon into one of the above
  94631. // four classes.
  94632. var polygonType = 0;
  94633. var types = [];
  94634. var i;
  94635. var t;
  94636. for (i = 0; i < polygon.vertices.length; i++) {
  94637. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  94638. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  94639. polygonType |= type;
  94640. types.push(type);
  94641. }
  94642. // Put the polygon in the correct list, splitting it when necessary
  94643. switch (polygonType) {
  94644. case COPLANAR:
  94645. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  94646. break;
  94647. case FRONT:
  94648. front.push(polygon);
  94649. break;
  94650. case BACK:
  94651. back.push(polygon);
  94652. break;
  94653. case SPANNING:
  94654. var f = [], b = [];
  94655. for (i = 0; i < polygon.vertices.length; i++) {
  94656. var j = (i + 1) % polygon.vertices.length;
  94657. var ti = types[i], tj = types[j];
  94658. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  94659. if (ti !== BACK) {
  94660. f.push(vi);
  94661. }
  94662. if (ti !== FRONT) {
  94663. b.push(ti !== BACK ? vi.clone() : vi);
  94664. }
  94665. if ((ti | tj) === SPANNING) {
  94666. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  94667. var v = vi.interpolate(vj, t);
  94668. f.push(v);
  94669. b.push(v.clone());
  94670. }
  94671. }
  94672. var poly;
  94673. if (f.length >= 3) {
  94674. poly = new Polygon(f, polygon.shared);
  94675. if (poly.plane) {
  94676. front.push(poly);
  94677. }
  94678. }
  94679. if (b.length >= 3) {
  94680. poly = new Polygon(b, polygon.shared);
  94681. if (poly.plane) {
  94682. back.push(poly);
  94683. }
  94684. }
  94685. break;
  94686. }
  94687. };
  94688. /**
  94689. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  94690. * point is on the plane
  94691. */
  94692. Plane.EPSILON = 1e-5;
  94693. return Plane;
  94694. }());
  94695. /**
  94696. * Represents a convex polygon. The vertices used to initialize a polygon must
  94697. * be coplanar and form a convex loop.
  94698. *
  94699. * Each convex polygon has a `shared` property, which is shared between all
  94700. * polygons that are clones of each other or were split from the same polygon.
  94701. * This can be used to define per-polygon properties (such as surface color)
  94702. */
  94703. var Polygon = /** @class */ (function () {
  94704. /**
  94705. * Initializes the polygon
  94706. * @param vertices The vertices of the polygon
  94707. * @param shared The properties shared across all polygons
  94708. */
  94709. function Polygon(vertices, shared) {
  94710. this.vertices = vertices;
  94711. this.shared = shared;
  94712. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  94713. }
  94714. /**
  94715. * Clones, or makes a deep copy, or the polygon
  94716. */
  94717. Polygon.prototype.clone = function () {
  94718. var vertices = this.vertices.map(function (v) { return v.clone(); });
  94719. return new Polygon(vertices, this.shared);
  94720. };
  94721. /**
  94722. * Flips the faces of the polygon
  94723. */
  94724. Polygon.prototype.flip = function () {
  94725. this.vertices.reverse().map(function (v) { v.flip(); });
  94726. this.plane.flip();
  94727. };
  94728. return Polygon;
  94729. }());
  94730. /**
  94731. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  94732. * by picking a polygon to split along. That polygon (and all other coplanar
  94733. * polygons) are added directly to that node and the other polygons are added to
  94734. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  94735. * no distinction between internal and leaf nodes
  94736. */
  94737. var Node = /** @class */ (function () {
  94738. /**
  94739. * Initializes the node
  94740. * @param polygons A collection of polygons held in the node
  94741. */
  94742. function Node(polygons) {
  94743. this.plane = null;
  94744. this.front = null;
  94745. this.back = null;
  94746. this.polygons = new Array();
  94747. if (polygons) {
  94748. this.build(polygons);
  94749. }
  94750. }
  94751. /**
  94752. * Clones, or makes a deep copy, of the node
  94753. * @returns The cloned node
  94754. */
  94755. Node.prototype.clone = function () {
  94756. var node = new Node();
  94757. node.plane = this.plane && this.plane.clone();
  94758. node.front = this.front && this.front.clone();
  94759. node.back = this.back && this.back.clone();
  94760. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  94761. return node;
  94762. };
  94763. /**
  94764. * Convert solid space to empty space and empty space to solid space
  94765. */
  94766. Node.prototype.invert = function () {
  94767. for (var i = 0; i < this.polygons.length; i++) {
  94768. this.polygons[i].flip();
  94769. }
  94770. if (this.plane) {
  94771. this.plane.flip();
  94772. }
  94773. if (this.front) {
  94774. this.front.invert();
  94775. }
  94776. if (this.back) {
  94777. this.back.invert();
  94778. }
  94779. var temp = this.front;
  94780. this.front = this.back;
  94781. this.back = temp;
  94782. };
  94783. /**
  94784. * Recursively remove all polygons in `polygons` that are inside this BSP
  94785. * tree.
  94786. * @param polygons Polygons to remove from the BSP
  94787. * @returns Polygons clipped from the BSP
  94788. */
  94789. Node.prototype.clipPolygons = function (polygons) {
  94790. if (!this.plane) {
  94791. return polygons.slice();
  94792. }
  94793. var front = new Array(), back = new Array();
  94794. for (var i = 0; i < polygons.length; i++) {
  94795. this.plane.splitPolygon(polygons[i], front, back, front, back);
  94796. }
  94797. if (this.front) {
  94798. front = this.front.clipPolygons(front);
  94799. }
  94800. if (this.back) {
  94801. back = this.back.clipPolygons(back);
  94802. }
  94803. else {
  94804. back = [];
  94805. }
  94806. return front.concat(back);
  94807. };
  94808. /**
  94809. * Remove all polygons in this BSP tree that are inside the other BSP tree
  94810. * `bsp`.
  94811. * @param bsp BSP containing polygons to remove from this BSP
  94812. */
  94813. Node.prototype.clipTo = function (bsp) {
  94814. this.polygons = bsp.clipPolygons(this.polygons);
  94815. if (this.front) {
  94816. this.front.clipTo(bsp);
  94817. }
  94818. if (this.back) {
  94819. this.back.clipTo(bsp);
  94820. }
  94821. };
  94822. /**
  94823. * Return a list of all polygons in this BSP tree
  94824. * @returns List of all polygons in this BSP tree
  94825. */
  94826. Node.prototype.allPolygons = function () {
  94827. var polygons = this.polygons.slice();
  94828. if (this.front) {
  94829. polygons = polygons.concat(this.front.allPolygons());
  94830. }
  94831. if (this.back) {
  94832. polygons = polygons.concat(this.back.allPolygons());
  94833. }
  94834. return polygons;
  94835. };
  94836. /**
  94837. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  94838. * new polygons are filtered down to the bottom of the tree and become new
  94839. * nodes there. Each set of polygons is partitioned using the first polygon
  94840. * (no heuristic is used to pick a good split)
  94841. * @param polygons Polygons used to construct the BSP tree
  94842. */
  94843. Node.prototype.build = function (polygons) {
  94844. if (!polygons.length) {
  94845. return;
  94846. }
  94847. if (!this.plane) {
  94848. this.plane = polygons[0].plane.clone();
  94849. }
  94850. var front = new Array(), back = new Array();
  94851. for (var i = 0; i < polygons.length; i++) {
  94852. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  94853. }
  94854. if (front.length) {
  94855. if (!this.front) {
  94856. this.front = new Node();
  94857. }
  94858. this.front.build(front);
  94859. }
  94860. if (back.length) {
  94861. if (!this.back) {
  94862. this.back = new Node();
  94863. }
  94864. this.back.build(back);
  94865. }
  94866. };
  94867. return Node;
  94868. }());
  94869. /**
  94870. * Class for building Constructive Solid Geometry
  94871. */
  94872. var CSG = /** @class */ (function () {
  94873. function CSG() {
  94874. this.polygons = new Array();
  94875. }
  94876. /**
  94877. * Convert the BABYLON.Mesh to BABYLON.CSG
  94878. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  94879. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  94880. */
  94881. CSG.FromMesh = function (mesh) {
  94882. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  94883. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  94884. if (mesh instanceof BABYLON.Mesh) {
  94885. mesh.computeWorldMatrix(true);
  94886. matrix = mesh.getWorldMatrix();
  94887. meshPosition = mesh.position.clone();
  94888. meshRotation = mesh.rotation.clone();
  94889. if (mesh.rotationQuaternion) {
  94890. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  94891. }
  94892. meshScaling = mesh.scaling.clone();
  94893. }
  94894. else {
  94895. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  94896. }
  94897. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94898. var subMeshes = mesh.subMeshes;
  94899. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  94900. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  94901. vertices = [];
  94902. for (var j = 0; j < 3; j++) {
  94903. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  94904. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  94905. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  94906. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  94907. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  94908. vertex = new Vertex(position, normal, uv);
  94909. vertices.push(vertex);
  94910. }
  94911. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  94912. // To handle the case of degenerated triangle
  94913. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  94914. if (polygon.plane) {
  94915. polygons.push(polygon);
  94916. }
  94917. }
  94918. }
  94919. var csg = CSG.FromPolygons(polygons);
  94920. csg.matrix = matrix;
  94921. csg.position = meshPosition;
  94922. csg.rotation = meshRotation;
  94923. csg.scaling = meshScaling;
  94924. csg.rotationQuaternion = meshRotationQuaternion;
  94925. currentCSGMeshId++;
  94926. return csg;
  94927. };
  94928. /**
  94929. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  94930. * @param polygons Polygons used to construct a BABYLON.CSG solid
  94931. */
  94932. CSG.FromPolygons = function (polygons) {
  94933. var csg = new CSG();
  94934. csg.polygons = polygons;
  94935. return csg;
  94936. };
  94937. /**
  94938. * Clones, or makes a deep copy, of the BABYLON.CSG
  94939. * @returns A new BABYLON.CSG
  94940. */
  94941. CSG.prototype.clone = function () {
  94942. var csg = new CSG();
  94943. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  94944. csg.copyTransformAttributes(this);
  94945. return csg;
  94946. };
  94947. /**
  94948. * Unions this CSG with another CSG
  94949. * @param csg The CSG to union against this CSG
  94950. * @returns The unioned CSG
  94951. */
  94952. CSG.prototype.union = function (csg) {
  94953. var a = new Node(this.clone().polygons);
  94954. var b = new Node(csg.clone().polygons);
  94955. a.clipTo(b);
  94956. b.clipTo(a);
  94957. b.invert();
  94958. b.clipTo(a);
  94959. b.invert();
  94960. a.build(b.allPolygons());
  94961. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  94962. };
  94963. /**
  94964. * Unions this CSG with another CSG in place
  94965. * @param csg The CSG to union against this CSG
  94966. */
  94967. CSG.prototype.unionInPlace = function (csg) {
  94968. var a = new Node(this.polygons);
  94969. var b = new Node(csg.polygons);
  94970. a.clipTo(b);
  94971. b.clipTo(a);
  94972. b.invert();
  94973. b.clipTo(a);
  94974. b.invert();
  94975. a.build(b.allPolygons());
  94976. this.polygons = a.allPolygons();
  94977. };
  94978. /**
  94979. * Subtracts this CSG with another CSG
  94980. * @param csg The CSG to subtract against this CSG
  94981. * @returns A new BABYLON.CSG
  94982. */
  94983. CSG.prototype.subtract = function (csg) {
  94984. var a = new Node(this.clone().polygons);
  94985. var b = new Node(csg.clone().polygons);
  94986. a.invert();
  94987. a.clipTo(b);
  94988. b.clipTo(a);
  94989. b.invert();
  94990. b.clipTo(a);
  94991. b.invert();
  94992. a.build(b.allPolygons());
  94993. a.invert();
  94994. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  94995. };
  94996. /**
  94997. * Subtracts this CSG with another CSG in place
  94998. * @param csg The CSG to subtact against this CSG
  94999. */
  95000. CSG.prototype.subtractInPlace = function (csg) {
  95001. var a = new Node(this.polygons);
  95002. var b = new Node(csg.polygons);
  95003. a.invert();
  95004. a.clipTo(b);
  95005. b.clipTo(a);
  95006. b.invert();
  95007. b.clipTo(a);
  95008. b.invert();
  95009. a.build(b.allPolygons());
  95010. a.invert();
  95011. this.polygons = a.allPolygons();
  95012. };
  95013. /**
  95014. * Intersect this CSG with another CSG
  95015. * @param csg The CSG to intersect against this CSG
  95016. * @returns A new BABYLON.CSG
  95017. */
  95018. CSG.prototype.intersect = function (csg) {
  95019. var a = new Node(this.clone().polygons);
  95020. var b = new Node(csg.clone().polygons);
  95021. a.invert();
  95022. b.clipTo(a);
  95023. b.invert();
  95024. a.clipTo(b);
  95025. b.clipTo(a);
  95026. a.build(b.allPolygons());
  95027. a.invert();
  95028. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  95029. };
  95030. /**
  95031. * Intersects this CSG with another CSG in place
  95032. * @param csg The CSG to intersect against this CSG
  95033. */
  95034. CSG.prototype.intersectInPlace = function (csg) {
  95035. var a = new Node(this.polygons);
  95036. var b = new Node(csg.polygons);
  95037. a.invert();
  95038. b.clipTo(a);
  95039. b.invert();
  95040. a.clipTo(b);
  95041. b.clipTo(a);
  95042. a.build(b.allPolygons());
  95043. a.invert();
  95044. this.polygons = a.allPolygons();
  95045. };
  95046. /**
  95047. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  95048. * not modified.
  95049. * @returns A new BABYLON.CSG solid with solid and empty space switched
  95050. */
  95051. CSG.prototype.inverse = function () {
  95052. var csg = this.clone();
  95053. csg.inverseInPlace();
  95054. return csg;
  95055. };
  95056. /**
  95057. * Inverses the BABYLON.CSG in place
  95058. */
  95059. CSG.prototype.inverseInPlace = function () {
  95060. this.polygons.map(function (p) { p.flip(); });
  95061. };
  95062. /**
  95063. * This is used to keep meshes transformations so they can be restored
  95064. * when we build back a Babylon Mesh
  95065. * NB : All CSG operations are performed in world coordinates
  95066. * @param csg The BABYLON.CSG to copy the transform attributes from
  95067. * @returns This BABYLON.CSG
  95068. */
  95069. CSG.prototype.copyTransformAttributes = function (csg) {
  95070. this.matrix = csg.matrix;
  95071. this.position = csg.position;
  95072. this.rotation = csg.rotation;
  95073. this.scaling = csg.scaling;
  95074. this.rotationQuaternion = csg.rotationQuaternion;
  95075. return this;
  95076. };
  95077. /**
  95078. * Build Raw mesh from CSG
  95079. * Coordinates here are in world space
  95080. * @param name The name of the mesh geometry
  95081. * @param scene The BABYLON.Scene
  95082. * @param keepSubMeshes Specifies if the submeshes should be kept
  95083. * @returns A new BABYLON.Mesh
  95084. */
  95085. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  95086. var matrix = this.matrix.clone();
  95087. matrix.invert();
  95088. 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;
  95089. if (keepSubMeshes) {
  95090. // Sort Polygons, since subMeshes are indices range
  95091. polygons.sort(function (a, b) {
  95092. if (a.shared.meshId === b.shared.meshId) {
  95093. return a.shared.subMeshId - b.shared.subMeshId;
  95094. }
  95095. else {
  95096. return a.shared.meshId - b.shared.meshId;
  95097. }
  95098. });
  95099. }
  95100. for (var i = 0, il = polygons.length; i < il; i++) {
  95101. polygon = polygons[i];
  95102. // Building SubMeshes
  95103. if (!subMesh_dict[polygon.shared.meshId]) {
  95104. subMesh_dict[polygon.shared.meshId] = {};
  95105. }
  95106. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  95107. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  95108. indexStart: +Infinity,
  95109. indexEnd: -Infinity,
  95110. materialIndex: polygon.shared.materialIndex
  95111. };
  95112. }
  95113. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  95114. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  95115. polygonIndices[0] = 0;
  95116. polygonIndices[1] = j - 1;
  95117. polygonIndices[2] = j;
  95118. for (var k = 0; k < 3; k++) {
  95119. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  95120. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  95121. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  95122. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  95123. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  95124. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  95125. // Check if 2 points can be merged
  95126. if (!(typeof vertex_idx !== 'undefined' &&
  95127. normals[vertex_idx * 3] === localNormal.x &&
  95128. normals[vertex_idx * 3 + 1] === localNormal.y &&
  95129. normals[vertex_idx * 3 + 2] === localNormal.z &&
  95130. uvs[vertex_idx * 2] === uv.x &&
  95131. uvs[vertex_idx * 2 + 1] === uv.y)) {
  95132. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  95133. uvs.push(uv.x, uv.y);
  95134. normals.push(normal.x, normal.y, normal.z);
  95135. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  95136. }
  95137. indices.push(vertex_idx);
  95138. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  95139. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  95140. currentIndex++;
  95141. }
  95142. }
  95143. }
  95144. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  95145. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  95146. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  95147. mesh.setIndices(indices, null);
  95148. if (keepSubMeshes) {
  95149. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  95150. var materialIndexOffset = 0, materialMaxIndex;
  95151. mesh.subMeshes = new Array();
  95152. for (var m in subMesh_dict) {
  95153. materialMaxIndex = -1;
  95154. for (var sm in subMesh_dict[m]) {
  95155. subMesh_obj = subMesh_dict[m][sm];
  95156. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  95157. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  95158. }
  95159. materialIndexOffset += ++materialMaxIndex;
  95160. }
  95161. }
  95162. return mesh;
  95163. };
  95164. /**
  95165. * Build Mesh from CSG taking material and transforms into account
  95166. * @param name The name of the BABYLON.Mesh
  95167. * @param material The material of the BABYLON.Mesh
  95168. * @param scene The BABYLON.Scene
  95169. * @param keepSubMeshes Specifies if submeshes should be kept
  95170. * @returns The new BABYLON.Mesh
  95171. */
  95172. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  95173. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  95174. mesh.material = material;
  95175. mesh.position.copyFrom(this.position);
  95176. mesh.rotation.copyFrom(this.rotation);
  95177. if (this.rotationQuaternion) {
  95178. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  95179. }
  95180. mesh.scaling.copyFrom(this.scaling);
  95181. mesh.computeWorldMatrix(true);
  95182. return mesh;
  95183. };
  95184. return CSG;
  95185. }());
  95186. BABYLON.CSG = CSG;
  95187. })(BABYLON || (BABYLON = {}));
  95188. //# sourceMappingURL=babylon.csg.js.map
  95189. var BABYLON;
  95190. (function (BABYLON) {
  95191. /**
  95192. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95193. * It controls one of the indiviual texture used in the effect.
  95194. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95195. */
  95196. var LensFlare = /** @class */ (function () {
  95197. /**
  95198. * Instantiates a new Lens Flare.
  95199. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95200. * It controls one of the indiviual texture used in the effect.
  95201. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95202. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  95203. * @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.
  95204. * @param color Define the lens color
  95205. * @param imgUrl Define the lens texture url
  95206. * @param system Define the `lensFlareSystem` this flare is part of
  95207. */
  95208. function LensFlare(
  95209. /**
  95210. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  95211. */
  95212. size,
  95213. /**
  95214. * 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.
  95215. */
  95216. position, color, imgUrl, system) {
  95217. this.size = size;
  95218. this.position = position;
  95219. /**
  95220. * Define the alpha mode to render this particular lens.
  95221. */
  95222. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  95223. this.color = color || new BABYLON.Color3(1, 1, 1);
  95224. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  95225. this._system = system;
  95226. system.lensFlares.push(this);
  95227. }
  95228. /**
  95229. * Creates a new Lens Flare.
  95230. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95231. * It controls one of the indiviual texture used in the effect.
  95232. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95233. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  95234. * @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.
  95235. * @param color Define the lens color
  95236. * @param imgUrl Define the lens texture url
  95237. * @param system Define the `lensFlareSystem` this flare is part of
  95238. * @returns The newly created Lens Flare
  95239. */
  95240. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  95241. return new LensFlare(size, position, color, imgUrl, system);
  95242. };
  95243. /**
  95244. * Dispose and release the lens flare with its associated resources.
  95245. */
  95246. LensFlare.prototype.dispose = function () {
  95247. if (this.texture) {
  95248. this.texture.dispose();
  95249. }
  95250. // Remove from scene
  95251. var index = this._system.lensFlares.indexOf(this);
  95252. this._system.lensFlares.splice(index, 1);
  95253. };
  95254. return LensFlare;
  95255. }());
  95256. BABYLON.LensFlare = LensFlare;
  95257. })(BABYLON || (BABYLON = {}));
  95258. //# sourceMappingURL=babylon.lensFlare.js.map
  95259. var BABYLON;
  95260. (function (BABYLON) {
  95261. // Adds the parser to the scene parsers.
  95262. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  95263. // Lens flares
  95264. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  95265. if (!container.lensFlareSystems) {
  95266. container.lensFlareSystems = new Array();
  95267. }
  95268. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  95269. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  95270. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  95271. container.lensFlareSystems.push(lf);
  95272. }
  95273. }
  95274. });
  95275. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  95276. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  95277. if (this.lensFlareSystems[index].name === name) {
  95278. return this.lensFlareSystems[index];
  95279. }
  95280. }
  95281. return null;
  95282. };
  95283. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  95284. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  95285. if (this.lensFlareSystems[index].id === id) {
  95286. return this.lensFlareSystems[index];
  95287. }
  95288. }
  95289. return null;
  95290. };
  95291. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  95292. var index = this.lensFlareSystems.indexOf(toRemove);
  95293. if (index !== -1) {
  95294. this.lensFlareSystems.splice(index, 1);
  95295. }
  95296. return index;
  95297. };
  95298. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  95299. this.lensFlareSystems.push(newLensFlareSystem);
  95300. };
  95301. /**
  95302. * Defines the lens flare scene component responsible to manage any lens flares
  95303. * in a given scene.
  95304. */
  95305. var LensFlareSystemSceneComponent = /** @class */ (function () {
  95306. /**
  95307. * Creates a new instance of the component for the given scene
  95308. * @param scene Defines the scene to register the component in
  95309. */
  95310. function LensFlareSystemSceneComponent(scene) {
  95311. /**
  95312. * The component name helpfull to identify the component in the list of scene components.
  95313. */
  95314. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  95315. this.scene = scene;
  95316. scene.lensFlareSystems = new Array();
  95317. }
  95318. /**
  95319. * Registers the component in a given scene
  95320. */
  95321. LensFlareSystemSceneComponent.prototype.register = function () {
  95322. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  95323. };
  95324. /**
  95325. * Rebuilds the elements related to this component in case of
  95326. * context lost for instance.
  95327. */
  95328. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  95329. // Nothing to do for lens flare
  95330. };
  95331. /**
  95332. * Adds all the element from the container to the scene
  95333. * @param container the container holding the elements
  95334. */
  95335. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  95336. var _this = this;
  95337. if (!container.lensFlareSystems) {
  95338. return;
  95339. }
  95340. container.lensFlareSystems.forEach(function (o) {
  95341. _this.scene.addLensFlareSystem(o);
  95342. });
  95343. };
  95344. /**
  95345. * Removes all the elements in the container from the scene
  95346. * @param container contains the elements to remove
  95347. */
  95348. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  95349. var _this = this;
  95350. if (!container.lensFlareSystems) {
  95351. return;
  95352. }
  95353. container.lensFlareSystems.forEach(function (o) {
  95354. _this.scene.removeLensFlareSystem(o);
  95355. });
  95356. };
  95357. /**
  95358. * Serializes the component data to the specified json object
  95359. * @param serializationObject The object to serialize to
  95360. */
  95361. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  95362. // Lens flares
  95363. serializationObject.lensFlareSystems = [];
  95364. var lensFlareSystems = this.scene.lensFlareSystems;
  95365. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  95366. var lensFlareSystem = lensFlareSystems_1[_i];
  95367. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  95368. }
  95369. };
  95370. /**
  95371. * Disposes the component and the associated ressources.
  95372. */
  95373. LensFlareSystemSceneComponent.prototype.dispose = function () {
  95374. var lensFlareSystems = this.scene.lensFlareSystems;
  95375. while (lensFlareSystems.length) {
  95376. lensFlareSystems[0].dispose();
  95377. }
  95378. };
  95379. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  95380. // Lens flares
  95381. if (this.scene.lensFlaresEnabled) {
  95382. var lensFlareSystems = this.scene.lensFlareSystems;
  95383. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  95384. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  95385. var lensFlareSystem = lensFlareSystems_2[_i];
  95386. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  95387. lensFlareSystem.render();
  95388. }
  95389. }
  95390. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  95391. }
  95392. };
  95393. return LensFlareSystemSceneComponent;
  95394. }());
  95395. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  95396. })(BABYLON || (BABYLON = {}));
  95397. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  95398. var BABYLON;
  95399. (function (BABYLON) {
  95400. /**
  95401. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  95402. * It is usually composed of several `BABYLON.lensFlare`.
  95403. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95404. */
  95405. var LensFlareSystem = /** @class */ (function () {
  95406. /**
  95407. * Instantiates a lens flare system.
  95408. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  95409. * It is usually composed of several `BABYLON.lensFlare`.
  95410. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95411. * @param name Define the name of the lens flare system in the scene
  95412. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  95413. * @param scene Define the scene the lens flare system belongs to
  95414. */
  95415. function LensFlareSystem(
  95416. /**
  95417. * Define the name of the lens flare system
  95418. */
  95419. name, emitter, scene) {
  95420. this.name = name;
  95421. /**
  95422. * List of lens flares used in this system.
  95423. */
  95424. this.lensFlares = new Array();
  95425. /**
  95426. * Define a limit from the border the lens flare can be visible.
  95427. */
  95428. this.borderLimit = 300;
  95429. /**
  95430. * Define a viewport border we do not want to see the lens flare in.
  95431. */
  95432. this.viewportBorder = 0;
  95433. /**
  95434. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  95435. */
  95436. this.layerMask = 0x0FFFFFFF;
  95437. this._vertexBuffers = {};
  95438. this._isEnabled = true;
  95439. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95440. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  95441. if (!component) {
  95442. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  95443. scene._addComponent(component);
  95444. }
  95445. this._emitter = emitter;
  95446. this.id = name;
  95447. scene.lensFlareSystems.push(this);
  95448. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  95449. var engine = scene.getEngine();
  95450. // VBO
  95451. var vertices = [];
  95452. vertices.push(1, 1);
  95453. vertices.push(-1, 1);
  95454. vertices.push(-1, -1);
  95455. vertices.push(1, -1);
  95456. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95457. // Indices
  95458. var indices = [];
  95459. indices.push(0);
  95460. indices.push(1);
  95461. indices.push(2);
  95462. indices.push(0);
  95463. indices.push(2);
  95464. indices.push(3);
  95465. this._indexBuffer = engine.createIndexBuffer(indices);
  95466. // Effects
  95467. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  95468. }
  95469. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  95470. /**
  95471. * Define if the lens flare system is enabled.
  95472. */
  95473. get: function () {
  95474. return this._isEnabled;
  95475. },
  95476. set: function (value) {
  95477. this._isEnabled = value;
  95478. },
  95479. enumerable: true,
  95480. configurable: true
  95481. });
  95482. /**
  95483. * Get the scene the effects belongs to.
  95484. * @returns the scene holding the lens flare system
  95485. */
  95486. LensFlareSystem.prototype.getScene = function () {
  95487. return this._scene;
  95488. };
  95489. /**
  95490. * Get the emitter of the lens flare system.
  95491. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  95492. * @returns the emitter of the lens flare system
  95493. */
  95494. LensFlareSystem.prototype.getEmitter = function () {
  95495. return this._emitter;
  95496. };
  95497. /**
  95498. * Set the emitter of the lens flare system.
  95499. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  95500. * @param newEmitter Define the new emitter of the system
  95501. */
  95502. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  95503. this._emitter = newEmitter;
  95504. };
  95505. /**
  95506. * Get the lens flare system emitter position.
  95507. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  95508. * @returns the position
  95509. */
  95510. LensFlareSystem.prototype.getEmitterPosition = function () {
  95511. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  95512. };
  95513. /**
  95514. * @hidden
  95515. */
  95516. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  95517. var position = this.getEmitterPosition();
  95518. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  95519. this._positionX = position.x;
  95520. this._positionY = position.y;
  95521. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  95522. if (this.viewportBorder > 0) {
  95523. globalViewport.x -= this.viewportBorder;
  95524. globalViewport.y -= this.viewportBorder;
  95525. globalViewport.width += this.viewportBorder * 2;
  95526. globalViewport.height += this.viewportBorder * 2;
  95527. position.x += this.viewportBorder;
  95528. position.y += this.viewportBorder;
  95529. this._positionX += this.viewportBorder;
  95530. this._positionY += this.viewportBorder;
  95531. }
  95532. if (position.z > 0) {
  95533. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  95534. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) {
  95535. return true;
  95536. }
  95537. }
  95538. return true;
  95539. }
  95540. return false;
  95541. };
  95542. /** @hidden */
  95543. LensFlareSystem.prototype._isVisible = function () {
  95544. if (!this._isEnabled || !this._scene.activeCamera) {
  95545. return false;
  95546. }
  95547. var emitterPosition = this.getEmitterPosition();
  95548. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  95549. var distance = direction.length();
  95550. direction.normalize();
  95551. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  95552. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  95553. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  95554. };
  95555. /**
  95556. * @hidden
  95557. */
  95558. LensFlareSystem.prototype.render = function () {
  95559. if (!this._effect.isReady() || !this._scene.activeCamera) {
  95560. return false;
  95561. }
  95562. var engine = this._scene.getEngine();
  95563. var viewport = this._scene.activeCamera.viewport;
  95564. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  95565. // Position
  95566. if (!this.computeEffectivePosition(globalViewport)) {
  95567. return false;
  95568. }
  95569. // Visibility
  95570. if (!this._isVisible()) {
  95571. return false;
  95572. }
  95573. // Intensity
  95574. var awayX;
  95575. var awayY;
  95576. if (this._positionX < this.borderLimit + globalViewport.x) {
  95577. awayX = this.borderLimit + globalViewport.x - this._positionX;
  95578. }
  95579. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  95580. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  95581. }
  95582. else {
  95583. awayX = 0;
  95584. }
  95585. if (this._positionY < this.borderLimit + globalViewport.y) {
  95586. awayY = this.borderLimit + globalViewport.y - this._positionY;
  95587. }
  95588. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  95589. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  95590. }
  95591. else {
  95592. awayY = 0;
  95593. }
  95594. var away = (awayX > awayY) ? awayX : awayY;
  95595. away -= this.viewportBorder;
  95596. if (away > this.borderLimit) {
  95597. away = this.borderLimit;
  95598. }
  95599. var intensity = 1.0 - BABYLON.Scalar.Clamp(away / this.borderLimit, 0, 1);
  95600. if (intensity < 0) {
  95601. return false;
  95602. }
  95603. if (intensity > 1.0) {
  95604. intensity = 1.0;
  95605. }
  95606. if (this.viewportBorder > 0) {
  95607. globalViewport.x += this.viewportBorder;
  95608. globalViewport.y += this.viewportBorder;
  95609. globalViewport.width -= this.viewportBorder * 2;
  95610. globalViewport.height -= this.viewportBorder * 2;
  95611. this._positionX -= this.viewportBorder;
  95612. this._positionY -= this.viewportBorder;
  95613. }
  95614. // Position
  95615. var centerX = globalViewport.x + globalViewport.width / 2;
  95616. var centerY = globalViewport.y + globalViewport.height / 2;
  95617. var distX = centerX - this._positionX;
  95618. var distY = centerY - this._positionY;
  95619. // Effects
  95620. engine.enableEffect(this._effect);
  95621. engine.setState(false);
  95622. engine.setDepthBuffer(false);
  95623. // VBOs
  95624. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  95625. // Flares
  95626. for (var index = 0; index < this.lensFlares.length; index++) {
  95627. var flare = this.lensFlares[index];
  95628. engine.setAlphaMode(flare.alphaMode);
  95629. var x = centerX - (distX * flare.position);
  95630. var y = centerY - (distY * flare.position);
  95631. var cw = flare.size;
  95632. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  95633. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  95634. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  95635. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  95636. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  95637. // Texture
  95638. this._effect.setTexture("textureSampler", flare.texture);
  95639. // Color
  95640. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  95641. // Draw order
  95642. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95643. }
  95644. engine.setDepthBuffer(true);
  95645. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  95646. return true;
  95647. };
  95648. /**
  95649. * Dispose and release the lens flare with its associated resources.
  95650. */
  95651. LensFlareSystem.prototype.dispose = function () {
  95652. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95653. if (vertexBuffer) {
  95654. vertexBuffer.dispose();
  95655. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  95656. }
  95657. if (this._indexBuffer) {
  95658. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  95659. this._indexBuffer = null;
  95660. }
  95661. while (this.lensFlares.length) {
  95662. this.lensFlares[0].dispose();
  95663. }
  95664. // Remove from scene
  95665. var index = this._scene.lensFlareSystems.indexOf(this);
  95666. this._scene.lensFlareSystems.splice(index, 1);
  95667. };
  95668. /**
  95669. * Parse a lens flare system from a JSON repressentation
  95670. * @param parsedLensFlareSystem Define the JSON to parse
  95671. * @param scene Define the scene the parsed system should be instantiated in
  95672. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  95673. * @returns the parsed system
  95674. */
  95675. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  95676. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  95677. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  95678. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  95679. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  95680. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  95681. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  95682. var parsedFlare = parsedLensFlareSystem.flares[index];
  95683. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  95684. }
  95685. return lensFlareSystem;
  95686. };
  95687. /**
  95688. * Serialize the current Lens Flare System into a JSON representation.
  95689. * @returns the serialized JSON
  95690. */
  95691. LensFlareSystem.prototype.serialize = function () {
  95692. var serializationObject = {};
  95693. serializationObject.id = this.id;
  95694. serializationObject.name = this.name;
  95695. serializationObject.emitterId = this.getEmitter().id;
  95696. serializationObject.borderLimit = this.borderLimit;
  95697. serializationObject.flares = [];
  95698. for (var index = 0; index < this.lensFlares.length; index++) {
  95699. var flare = this.lensFlares[index];
  95700. serializationObject.flares.push({
  95701. size: flare.size,
  95702. position: flare.position,
  95703. color: flare.color.asArray(),
  95704. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  95705. });
  95706. }
  95707. return serializationObject;
  95708. };
  95709. return LensFlareSystem;
  95710. }());
  95711. BABYLON.LensFlareSystem = LensFlareSystem;
  95712. })(BABYLON || (BABYLON = {}));
  95713. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  95714. var BABYLON;
  95715. (function (BABYLON) {
  95716. /**
  95717. * This is a holder class for the physics joint created by the physics plugin
  95718. * It holds a set of functions to control the underlying joint
  95719. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95720. */
  95721. var PhysicsJoint = /** @class */ (function () {
  95722. /**
  95723. * Initializes the physics joint
  95724. * @param type The type of the physics joint
  95725. * @param jointData The data for the physics joint
  95726. */
  95727. function PhysicsJoint(
  95728. /**
  95729. * The type of the physics joint
  95730. */
  95731. type,
  95732. /**
  95733. * The data for the physics joint
  95734. */
  95735. jointData) {
  95736. this.type = type;
  95737. this.jointData = jointData;
  95738. jointData.nativeParams = jointData.nativeParams || {};
  95739. }
  95740. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  95741. /**
  95742. * Gets the physics joint
  95743. */
  95744. get: function () {
  95745. return this._physicsJoint;
  95746. },
  95747. /**
  95748. * Sets the physics joint
  95749. */
  95750. set: function (newJoint) {
  95751. if (this._physicsJoint) {
  95752. //remove from the wolrd
  95753. }
  95754. this._physicsJoint = newJoint;
  95755. },
  95756. enumerable: true,
  95757. configurable: true
  95758. });
  95759. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  95760. /**
  95761. * Sets the physics plugin
  95762. */
  95763. set: function (physicsPlugin) {
  95764. this._physicsPlugin = physicsPlugin;
  95765. },
  95766. enumerable: true,
  95767. configurable: true
  95768. });
  95769. /**
  95770. * Execute a function that is physics-plugin specific.
  95771. * @param {Function} func the function that will be executed.
  95772. * It accepts two parameters: the physics world and the physics joint
  95773. */
  95774. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  95775. func(this._physicsPlugin.world, this._physicsJoint);
  95776. };
  95777. //TODO check if the native joints are the same
  95778. //Joint Types
  95779. /**
  95780. * Distance-Joint type
  95781. */
  95782. PhysicsJoint.DistanceJoint = 0;
  95783. /**
  95784. * Hinge-Joint type
  95785. */
  95786. PhysicsJoint.HingeJoint = 1;
  95787. /**
  95788. * Ball-and-Socket joint type
  95789. */
  95790. PhysicsJoint.BallAndSocketJoint = 2;
  95791. /**
  95792. * Wheel-Joint type
  95793. */
  95794. PhysicsJoint.WheelJoint = 3;
  95795. /**
  95796. * Slider-Joint type
  95797. */
  95798. PhysicsJoint.SliderJoint = 4;
  95799. //OIMO
  95800. /**
  95801. * Prismatic-Joint type
  95802. */
  95803. PhysicsJoint.PrismaticJoint = 5;
  95804. //
  95805. /**
  95806. * Universal-Joint type
  95807. * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  95808. */
  95809. PhysicsJoint.UniversalJoint = 6;
  95810. /**
  95811. * Hinge-Joint 2 type
  95812. */
  95813. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  95814. //Cannon
  95815. /**
  95816. * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters
  95817. */
  95818. PhysicsJoint.PointToPointJoint = 8;
  95819. //Cannon only at the moment
  95820. /**
  95821. * Spring-Joint type
  95822. */
  95823. PhysicsJoint.SpringJoint = 9;
  95824. /**
  95825. * Lock-Joint type
  95826. */
  95827. PhysicsJoint.LockJoint = 10;
  95828. return PhysicsJoint;
  95829. }());
  95830. BABYLON.PhysicsJoint = PhysicsJoint;
  95831. /**
  95832. * A class representing a physics distance joint
  95833. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95834. */
  95835. var DistanceJoint = /** @class */ (function (_super) {
  95836. __extends(DistanceJoint, _super);
  95837. /**
  95838. *
  95839. * @param jointData The data for the Distance-Joint
  95840. */
  95841. function DistanceJoint(jointData) {
  95842. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  95843. }
  95844. /**
  95845. * Update the predefined distance.
  95846. * @param maxDistance The maximum preferred distance
  95847. * @param minDistance The minimum preferred distance
  95848. */
  95849. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  95850. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  95851. };
  95852. return DistanceJoint;
  95853. }(PhysicsJoint));
  95854. BABYLON.DistanceJoint = DistanceJoint;
  95855. /**
  95856. * Represents a Motor-Enabled Joint
  95857. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95858. */
  95859. var MotorEnabledJoint = /** @class */ (function (_super) {
  95860. __extends(MotorEnabledJoint, _super);
  95861. /**
  95862. * Initializes the Motor-Enabled Joint
  95863. * @param type The type of the joint
  95864. * @param jointData The physica joint data for the joint
  95865. */
  95866. function MotorEnabledJoint(type, jointData) {
  95867. return _super.call(this, type, jointData) || this;
  95868. }
  95869. /**
  95870. * Set the motor values.
  95871. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95872. * @param force the force to apply
  95873. * @param maxForce max force for this motor.
  95874. */
  95875. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  95876. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  95877. };
  95878. /**
  95879. * Set the motor's limits.
  95880. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95881. * @param upperLimit The upper limit of the motor
  95882. * @param lowerLimit The lower limit of the motor
  95883. */
  95884. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  95885. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  95886. };
  95887. return MotorEnabledJoint;
  95888. }(PhysicsJoint));
  95889. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  95890. /**
  95891. * This class represents a single physics Hinge-Joint
  95892. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95893. */
  95894. var HingeJoint = /** @class */ (function (_super) {
  95895. __extends(HingeJoint, _super);
  95896. /**
  95897. * Initializes the Hinge-Joint
  95898. * @param jointData The joint data for the Hinge-Joint
  95899. */
  95900. function HingeJoint(jointData) {
  95901. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  95902. }
  95903. /**
  95904. * Set the motor values.
  95905. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95906. * @param {number} force the force to apply
  95907. * @param {number} maxForce max force for this motor.
  95908. */
  95909. HingeJoint.prototype.setMotor = function (force, maxForce) {
  95910. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  95911. };
  95912. /**
  95913. * Set the motor's limits.
  95914. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95915. * @param upperLimit The upper limit of the motor
  95916. * @param lowerLimit The lower limit of the motor
  95917. */
  95918. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  95919. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  95920. };
  95921. return HingeJoint;
  95922. }(MotorEnabledJoint));
  95923. BABYLON.HingeJoint = HingeJoint;
  95924. /**
  95925. * This class represents a dual hinge physics joint (same as wheel joint)
  95926. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95927. */
  95928. var Hinge2Joint = /** @class */ (function (_super) {
  95929. __extends(Hinge2Joint, _super);
  95930. /**
  95931. * Initializes the Hinge2-Joint
  95932. * @param jointData The joint data for the Hinge2-Joint
  95933. */
  95934. function Hinge2Joint(jointData) {
  95935. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  95936. }
  95937. /**
  95938. * Set the motor values.
  95939. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95940. * @param {number} force the force to apply
  95941. * @param {number} maxForce max force for this motor.
  95942. * @param {motorIndex} the motor's index, 0 or 1.
  95943. */
  95944. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  95945. if (motorIndex === void 0) { motorIndex = 0; }
  95946. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  95947. };
  95948. /**
  95949. * Set the motor limits.
  95950. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95951. * @param {number} upperLimit the upper limit
  95952. * @param {number} lowerLimit lower limit
  95953. * @param {motorIndex} the motor's index, 0 or 1.
  95954. */
  95955. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  95956. if (motorIndex === void 0) { motorIndex = 0; }
  95957. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  95958. };
  95959. return Hinge2Joint;
  95960. }(MotorEnabledJoint));
  95961. BABYLON.Hinge2Joint = Hinge2Joint;
  95962. })(BABYLON || (BABYLON = {}));
  95963. //# sourceMappingURL=babylon.physicsJoint.js.map
  95964. var BABYLON;
  95965. (function (BABYLON) {
  95966. /**
  95967. * Represents a physics imposter
  95968. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95969. */
  95970. var PhysicsImpostor = /** @class */ (function () {
  95971. /**
  95972. * Initializes the physics imposter
  95973. * @param object The physics-enabled object used as the physics imposter
  95974. * @param type The type of the physics imposter
  95975. * @param _options The options for the physics imposter
  95976. * @param _scene The Babylon scene
  95977. */
  95978. function PhysicsImpostor(
  95979. /**
  95980. * The physics-enabled object used as the physics imposter
  95981. */
  95982. object,
  95983. /**
  95984. * The type of the physics imposter
  95985. */
  95986. type, _options, _scene) {
  95987. if (_options === void 0) { _options = { mass: 0 }; }
  95988. var _this = this;
  95989. this.object = object;
  95990. this.type = type;
  95991. this._options = _options;
  95992. this._scene = _scene;
  95993. this._bodyUpdateRequired = false;
  95994. this._onBeforePhysicsStepCallbacks = new Array();
  95995. this._onAfterPhysicsStepCallbacks = new Array();
  95996. this._onPhysicsCollideCallbacks = [];
  95997. this._deltaPosition = BABYLON.Vector3.Zero();
  95998. this._isDisposed = false;
  95999. //temp variables for parent rotation calculations
  96000. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  96001. this._tmpQuat = new BABYLON.Quaternion();
  96002. this._tmpQuat2 = new BABYLON.Quaternion();
  96003. /**
  96004. * this function is executed by the physics engine.
  96005. */
  96006. this.beforeStep = function () {
  96007. if (!_this._physicsEngine) {
  96008. return;
  96009. }
  96010. _this.object.translate(_this._deltaPosition, -1);
  96011. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  96012. _this.object.computeWorldMatrix(false);
  96013. if (_this.object.parent && _this.object.rotationQuaternion) {
  96014. _this.getParentsRotation();
  96015. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  96016. }
  96017. else {
  96018. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  96019. }
  96020. if (!_this._options.disableBidirectionalTransformation) {
  96021. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  96022. }
  96023. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  96024. func(_this);
  96025. });
  96026. };
  96027. /**
  96028. * this function is executed by the physics engine
  96029. */
  96030. this.afterStep = function () {
  96031. if (!_this._physicsEngine) {
  96032. return;
  96033. }
  96034. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  96035. func(_this);
  96036. });
  96037. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  96038. // object has now its world rotation. needs to be converted to local.
  96039. if (_this.object.parent && _this.object.rotationQuaternion) {
  96040. _this.getParentsRotation();
  96041. _this._tmpQuat.conjugateInPlace();
  96042. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  96043. }
  96044. // take the position set and make it the absolute position of this object.
  96045. _this.object.setAbsolutePosition(_this.object.position);
  96046. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  96047. _this.object.translate(_this._deltaPosition, 1);
  96048. };
  96049. /**
  96050. * Legacy collision detection event support
  96051. */
  96052. this.onCollideEvent = null;
  96053. /**
  96054. * event and body object due to cannon's event-based architecture.
  96055. */
  96056. this.onCollide = function (e) {
  96057. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  96058. return;
  96059. }
  96060. if (!_this._physicsEngine) {
  96061. return;
  96062. }
  96063. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  96064. if (otherImpostor) {
  96065. // Legacy collision detection event support
  96066. if (_this.onCollideEvent) {
  96067. _this.onCollideEvent(_this, otherImpostor);
  96068. }
  96069. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  96070. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  96071. }).forEach(function (obj) {
  96072. obj.callback(_this, otherImpostor);
  96073. });
  96074. }
  96075. };
  96076. //sanity check!
  96077. if (!this.object) {
  96078. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  96079. return;
  96080. }
  96081. //legacy support for old syntax.
  96082. if (!this._scene && object.getScene) {
  96083. this._scene = object.getScene();
  96084. }
  96085. if (!this._scene) {
  96086. return;
  96087. }
  96088. this._physicsEngine = this._scene.getPhysicsEngine();
  96089. if (!this._physicsEngine) {
  96090. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  96091. }
  96092. else {
  96093. //set the object's quaternion, if not set
  96094. if (!this.object.rotationQuaternion) {
  96095. if (this.object.rotation) {
  96096. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  96097. }
  96098. else {
  96099. this.object.rotationQuaternion = new BABYLON.Quaternion();
  96100. }
  96101. }
  96102. //default options params
  96103. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  96104. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  96105. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  96106. this._joints = [];
  96107. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  96108. if (!this.object.parent || this._options.ignoreParent) {
  96109. this._init();
  96110. }
  96111. else if (this.object.parent.physicsImpostor) {
  96112. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  96113. }
  96114. }
  96115. }
  96116. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  96117. /**
  96118. * Specifies if the physics imposter is disposed
  96119. */
  96120. get: function () {
  96121. return this._isDisposed;
  96122. },
  96123. enumerable: true,
  96124. configurable: true
  96125. });
  96126. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  96127. /**
  96128. * Gets the mass of the physics imposter
  96129. */
  96130. get: function () {
  96131. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  96132. },
  96133. set: function (value) {
  96134. this.setMass(value);
  96135. },
  96136. enumerable: true,
  96137. configurable: true
  96138. });
  96139. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  96140. /**
  96141. * Gets the coefficient of friction
  96142. */
  96143. get: function () {
  96144. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  96145. },
  96146. /**
  96147. * Sets the coefficient of friction
  96148. */
  96149. set: function (value) {
  96150. if (!this._physicsEngine) {
  96151. return;
  96152. }
  96153. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  96154. },
  96155. enumerable: true,
  96156. configurable: true
  96157. });
  96158. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  96159. /**
  96160. * Gets the coefficient of restitution
  96161. */
  96162. get: function () {
  96163. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  96164. },
  96165. /**
  96166. * Sets the coefficient of restitution
  96167. */
  96168. set: function (value) {
  96169. if (!this._physicsEngine) {
  96170. return;
  96171. }
  96172. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  96173. },
  96174. enumerable: true,
  96175. configurable: true
  96176. });
  96177. /**
  96178. * This function will completly initialize this impostor.
  96179. * It will create a new body - but only if this mesh has no parent.
  96180. * If it has, this impostor will not be used other than to define the impostor
  96181. * of the child mesh.
  96182. * @hidden
  96183. */
  96184. PhysicsImpostor.prototype._init = function () {
  96185. if (!this._physicsEngine) {
  96186. return;
  96187. }
  96188. this._physicsEngine.removeImpostor(this);
  96189. this.physicsBody = null;
  96190. this._parent = this._parent || this._getPhysicsParent();
  96191. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  96192. this._physicsEngine.addImpostor(this);
  96193. }
  96194. };
  96195. PhysicsImpostor.prototype._getPhysicsParent = function () {
  96196. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  96197. var parentMesh = this.object.parent;
  96198. return parentMesh.physicsImpostor;
  96199. }
  96200. return null;
  96201. };
  96202. /**
  96203. * Should a new body be generated.
  96204. * @returns boolean specifying if body initialization is required
  96205. */
  96206. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  96207. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  96208. };
  96209. /**
  96210. * Sets the updated scaling
  96211. * @param updated Specifies if the scaling is updated
  96212. */
  96213. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  96214. this.forceUpdate();
  96215. };
  96216. /**
  96217. * Force a regeneration of this or the parent's impostor's body.
  96218. * Use under cautious - This will remove all joints already implemented.
  96219. */
  96220. PhysicsImpostor.prototype.forceUpdate = function () {
  96221. this._init();
  96222. if (this.parent && !this._options.ignoreParent) {
  96223. this.parent.forceUpdate();
  96224. }
  96225. };
  96226. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  96227. /*public get mesh(): AbstractMesh {
  96228. return this._mesh;
  96229. }*/
  96230. /**
  96231. * Gets the body that holds this impostor. Either its own, or its parent.
  96232. */
  96233. get: function () {
  96234. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  96235. },
  96236. /**
  96237. * Set the physics body. Used mainly by the physics engine/plugin
  96238. */
  96239. set: function (physicsBody) {
  96240. if (this._physicsBody && this._physicsEngine) {
  96241. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  96242. }
  96243. this._physicsBody = physicsBody;
  96244. this.resetUpdateFlags();
  96245. },
  96246. enumerable: true,
  96247. configurable: true
  96248. });
  96249. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  96250. /**
  96251. * Get the parent of the physics imposter
  96252. * @returns Physics imposter or null
  96253. */
  96254. get: function () {
  96255. return !this._options.ignoreParent && this._parent ? this._parent : null;
  96256. },
  96257. /**
  96258. * Sets the parent of the physics imposter
  96259. */
  96260. set: function (value) {
  96261. this._parent = value;
  96262. },
  96263. enumerable: true,
  96264. configurable: true
  96265. });
  96266. /**
  96267. * Resets the update flags
  96268. */
  96269. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  96270. this._bodyUpdateRequired = false;
  96271. };
  96272. /**
  96273. * Gets the object extend size
  96274. * @returns the object extend size
  96275. */
  96276. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  96277. if (this.object.getBoundingInfo) {
  96278. var q = this.object.rotationQuaternion;
  96279. //reset rotation
  96280. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  96281. //calculate the world matrix with no rotation
  96282. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  96283. var boundingInfo = this.object.getBoundingInfo();
  96284. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  96285. //bring back the rotation
  96286. this.object.rotationQuaternion = q;
  96287. //calculate the world matrix with the new rotation
  96288. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  96289. return size;
  96290. }
  96291. else {
  96292. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  96293. }
  96294. };
  96295. /**
  96296. * Gets the object center
  96297. * @returns The object center
  96298. */
  96299. PhysicsImpostor.prototype.getObjectCenter = function () {
  96300. if (this.object.getBoundingInfo) {
  96301. var boundingInfo = this.object.getBoundingInfo();
  96302. return boundingInfo.boundingBox.centerWorld;
  96303. }
  96304. else {
  96305. return this.object.position;
  96306. }
  96307. };
  96308. /**
  96309. * Get a specific parametes from the options parameter
  96310. * @param paramName The object parameter name
  96311. * @returns The object parameter
  96312. */
  96313. PhysicsImpostor.prototype.getParam = function (paramName) {
  96314. return this._options[paramName];
  96315. };
  96316. /**
  96317. * Sets a specific parameter in the options given to the physics plugin
  96318. * @param paramName The parameter name
  96319. * @param value The value of the parameter
  96320. */
  96321. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  96322. this._options[paramName] = value;
  96323. this._bodyUpdateRequired = true;
  96324. };
  96325. /**
  96326. * Specifically change the body's mass option. Won't recreate the physics body object
  96327. * @param mass The mass of the physics imposter
  96328. */
  96329. PhysicsImpostor.prototype.setMass = function (mass) {
  96330. if (this.getParam("mass") !== mass) {
  96331. this.setParam("mass", mass);
  96332. }
  96333. if (this._physicsEngine) {
  96334. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  96335. }
  96336. };
  96337. /**
  96338. * Gets the linear velocity
  96339. * @returns linear velocity or null
  96340. */
  96341. PhysicsImpostor.prototype.getLinearVelocity = function () {
  96342. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  96343. };
  96344. /**
  96345. * Sets the linear velocity
  96346. * @param velocity linear velocity or null
  96347. */
  96348. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  96349. if (this._physicsEngine) {
  96350. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  96351. }
  96352. };
  96353. /**
  96354. * Gets the angular velocity
  96355. * @returns angular velocity or null
  96356. */
  96357. PhysicsImpostor.prototype.getAngularVelocity = function () {
  96358. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  96359. };
  96360. /**
  96361. * Sets the angular velocity
  96362. * @param velocity The velocity or null
  96363. */
  96364. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  96365. if (this._physicsEngine) {
  96366. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  96367. }
  96368. };
  96369. /**
  96370. * Execute a function with the physics plugin native code
  96371. * Provide a function the will have two variables - the world object and the physics body object
  96372. * @param func The function to execute with the physics plugin native code
  96373. */
  96374. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  96375. if (this._physicsEngine) {
  96376. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  96377. }
  96378. };
  96379. /**
  96380. * Register a function that will be executed before the physics world is stepping forward
  96381. * @param func The function to execute before the physics world is stepped forward
  96382. */
  96383. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  96384. this._onBeforePhysicsStepCallbacks.push(func);
  96385. };
  96386. /**
  96387. * Unregister a function that will be executed before the physics world is stepping forward
  96388. * @param func The function to execute before the physics world is stepped forward
  96389. */
  96390. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  96391. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  96392. if (index > -1) {
  96393. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  96394. }
  96395. else {
  96396. BABYLON.Tools.Warn("Function to remove was not found");
  96397. }
  96398. };
  96399. /**
  96400. * Register a function that will be executed after the physics step
  96401. * @param func The function to execute after physics step
  96402. */
  96403. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  96404. this._onAfterPhysicsStepCallbacks.push(func);
  96405. };
  96406. /**
  96407. * Unregisters a function that will be executed after the physics step
  96408. * @param func The function to execute after physics step
  96409. */
  96410. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  96411. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  96412. if (index > -1) {
  96413. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  96414. }
  96415. else {
  96416. BABYLON.Tools.Warn("Function to remove was not found");
  96417. }
  96418. };
  96419. /**
  96420. * register a function that will be executed when this impostor collides against a different body
  96421. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  96422. * @param func Callback that is executed on collision
  96423. */
  96424. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  96425. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  96426. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  96427. };
  96428. /**
  96429. * Unregisters the physics imposter on contact
  96430. * @param collideAgainst The physics object to collide against
  96431. * @param func Callback to execute on collision
  96432. */
  96433. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  96434. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  96435. var index = -1;
  96436. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  96437. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  96438. // chcek the arrays match
  96439. var sameList = cbDef.otherImpostors.every(function (impostor) {
  96440. return collidedAgainstList.indexOf(impostor) > -1;
  96441. });
  96442. if (sameList) {
  96443. index = idx;
  96444. }
  96445. return sameList;
  96446. }
  96447. return false;
  96448. });
  96449. if (found) {
  96450. this._onPhysicsCollideCallbacks.splice(index, 1);
  96451. }
  96452. else {
  96453. BABYLON.Tools.Warn("Function to remove was not found");
  96454. }
  96455. };
  96456. /**
  96457. * Get the parent rotation
  96458. * @returns The parent rotation
  96459. */
  96460. PhysicsImpostor.prototype.getParentsRotation = function () {
  96461. var parent = this.object.parent;
  96462. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  96463. while (parent) {
  96464. if (parent.rotationQuaternion) {
  96465. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  96466. }
  96467. else {
  96468. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  96469. }
  96470. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  96471. parent = parent.parent;
  96472. }
  96473. return this._tmpQuat;
  96474. };
  96475. /**
  96476. * Apply a force
  96477. * @param force The force to apply
  96478. * @param contactPoint The contact point for the force
  96479. * @returns The physics imposter
  96480. */
  96481. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  96482. if (this._physicsEngine) {
  96483. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  96484. }
  96485. return this;
  96486. };
  96487. /**
  96488. * Apply an impulse
  96489. * @param force The impulse force
  96490. * @param contactPoint The contact point for the impulse force
  96491. * @returns The physics imposter
  96492. */
  96493. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  96494. if (this._physicsEngine) {
  96495. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  96496. }
  96497. return this;
  96498. };
  96499. /**
  96500. * A help function to create a joint
  96501. * @param otherImpostor A physics imposter used to create a joint
  96502. * @param jointType The type of joint
  96503. * @param jointData The data for the joint
  96504. * @returns The physics imposter
  96505. */
  96506. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  96507. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  96508. this.addJoint(otherImpostor, joint);
  96509. return this;
  96510. };
  96511. /**
  96512. * Add a joint to this impostor with a different impostor
  96513. * @param otherImpostor A physics imposter used to add a joint
  96514. * @param joint The joint to add
  96515. * @returns The physics imposter
  96516. */
  96517. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  96518. this._joints.push({
  96519. otherImpostor: otherImpostor,
  96520. joint: joint
  96521. });
  96522. if (this._physicsEngine) {
  96523. this._physicsEngine.addJoint(this, otherImpostor, joint);
  96524. }
  96525. return this;
  96526. };
  96527. /**
  96528. * Will keep this body still, in a sleep mode.
  96529. * @returns the physics imposter
  96530. */
  96531. PhysicsImpostor.prototype.sleep = function () {
  96532. if (this._physicsEngine) {
  96533. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  96534. }
  96535. return this;
  96536. };
  96537. /**
  96538. * Wake the body up.
  96539. * @returns The physics imposter
  96540. */
  96541. PhysicsImpostor.prototype.wakeUp = function () {
  96542. if (this._physicsEngine) {
  96543. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  96544. }
  96545. return this;
  96546. };
  96547. /**
  96548. * Clones the physics imposter
  96549. * @param newObject The physics imposter clones to this physics-enabled object
  96550. * @returns A nullable physics imposter
  96551. */
  96552. PhysicsImpostor.prototype.clone = function (newObject) {
  96553. if (!newObject) {
  96554. return null;
  96555. }
  96556. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  96557. };
  96558. /**
  96559. * Disposes the physics imposter
  96560. */
  96561. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  96562. var _this = this;
  96563. //no dispose if no physics engine is available.
  96564. if (!this._physicsEngine) {
  96565. return;
  96566. }
  96567. this._joints.forEach(function (j) {
  96568. if (_this._physicsEngine) {
  96569. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  96570. }
  96571. });
  96572. //dispose the physics body
  96573. this._physicsEngine.removeImpostor(this);
  96574. if (this.parent) {
  96575. this.parent.forceUpdate();
  96576. }
  96577. else {
  96578. /*this._object.getChildMeshes().forEach(function(mesh) {
  96579. if (mesh.physicsImpostor) {
  96580. if (disposeChildren) {
  96581. mesh.physicsImpostor.dispose();
  96582. mesh.physicsImpostor = null;
  96583. }
  96584. }
  96585. })*/
  96586. }
  96587. this._isDisposed = true;
  96588. };
  96589. /**
  96590. * Sets the delta position
  96591. * @param position The delta position amount
  96592. */
  96593. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  96594. this._deltaPosition.copyFrom(position);
  96595. };
  96596. /**
  96597. * Sets the delta rotation
  96598. * @param rotation The delta rotation amount
  96599. */
  96600. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  96601. if (!this._deltaRotation) {
  96602. this._deltaRotation = new BABYLON.Quaternion();
  96603. }
  96604. this._deltaRotation.copyFrom(rotation);
  96605. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  96606. };
  96607. /**
  96608. * Gets the box size of the physics imposter and stores the result in the input parameter
  96609. * @param result Stores the box size
  96610. * @returns The physics imposter
  96611. */
  96612. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  96613. if (this._physicsEngine) {
  96614. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  96615. }
  96616. return this;
  96617. };
  96618. /**
  96619. * Gets the radius of the physics imposter
  96620. * @returns Radius of the physics imposter
  96621. */
  96622. PhysicsImpostor.prototype.getRadius = function () {
  96623. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  96624. };
  96625. /**
  96626. * Sync a bone with this impostor
  96627. * @param bone The bone to sync to the impostor.
  96628. * @param boneMesh The mesh that the bone is influencing.
  96629. * @param jointPivot The pivot of the joint / bone in local space.
  96630. * @param distToJoint Optional distance from the impostor to the joint.
  96631. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  96632. */
  96633. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  96634. var tempVec = PhysicsImpostor._tmpVecs[0];
  96635. var mesh = this.object;
  96636. if (mesh.rotationQuaternion) {
  96637. if (adjustRotation) {
  96638. var tempQuat = PhysicsImpostor._tmpQuat;
  96639. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  96640. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  96641. }
  96642. else {
  96643. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  96644. }
  96645. }
  96646. tempVec.x = 0;
  96647. tempVec.y = 0;
  96648. tempVec.z = 0;
  96649. if (jointPivot) {
  96650. tempVec.x = jointPivot.x;
  96651. tempVec.y = jointPivot.y;
  96652. tempVec.z = jointPivot.z;
  96653. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  96654. if (distToJoint === undefined || distToJoint === null) {
  96655. distToJoint = jointPivot.length();
  96656. }
  96657. tempVec.x *= distToJoint;
  96658. tempVec.y *= distToJoint;
  96659. tempVec.z *= distToJoint;
  96660. }
  96661. if (bone.getParent()) {
  96662. tempVec.addInPlace(mesh.getAbsolutePosition());
  96663. bone.setAbsolutePosition(tempVec, boneMesh);
  96664. }
  96665. else {
  96666. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  96667. boneMesh.position.x -= tempVec.x;
  96668. boneMesh.position.y -= tempVec.y;
  96669. boneMesh.position.z -= tempVec.z;
  96670. }
  96671. };
  96672. /**
  96673. * Sync impostor to a bone
  96674. * @param bone The bone that the impostor will be synced to.
  96675. * @param boneMesh The mesh that the bone is influencing.
  96676. * @param jointPivot The pivot of the joint / bone in local space.
  96677. * @param distToJoint Optional distance from the impostor to the joint.
  96678. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  96679. * @param boneAxis Optional vector3 axis the bone is aligned with
  96680. */
  96681. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  96682. var mesh = this.object;
  96683. if (mesh.rotationQuaternion) {
  96684. if (adjustRotation) {
  96685. var tempQuat = PhysicsImpostor._tmpQuat;
  96686. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  96687. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  96688. }
  96689. else {
  96690. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  96691. }
  96692. }
  96693. var pos = PhysicsImpostor._tmpVecs[0];
  96694. var boneDir = PhysicsImpostor._tmpVecs[1];
  96695. if (!boneAxis) {
  96696. boneAxis = PhysicsImpostor._tmpVecs[2];
  96697. boneAxis.x = 0;
  96698. boneAxis.y = 1;
  96699. boneAxis.z = 0;
  96700. }
  96701. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  96702. bone.getAbsolutePositionToRef(boneMesh, pos);
  96703. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  96704. distToJoint = jointPivot.length();
  96705. }
  96706. if (distToJoint !== undefined && distToJoint !== null) {
  96707. pos.x += boneDir.x * distToJoint;
  96708. pos.y += boneDir.y * distToJoint;
  96709. pos.z += boneDir.z * distToJoint;
  96710. }
  96711. mesh.setAbsolutePosition(pos);
  96712. };
  96713. /**
  96714. * The default object size of the imposter
  96715. */
  96716. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  96717. /**
  96718. * The identity quaternion of the imposter
  96719. */
  96720. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  96721. PhysicsImpostor._tmpVecs = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  96722. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  96723. //Impostor types
  96724. /**
  96725. * No-Imposter type
  96726. */
  96727. PhysicsImpostor.NoImpostor = 0;
  96728. /**
  96729. * Sphere-Imposter type
  96730. */
  96731. PhysicsImpostor.SphereImpostor = 1;
  96732. /**
  96733. * Box-Imposter type
  96734. */
  96735. PhysicsImpostor.BoxImpostor = 2;
  96736. /**
  96737. * Plane-Imposter type
  96738. */
  96739. PhysicsImpostor.PlaneImpostor = 3;
  96740. /**
  96741. * Mesh-imposter type
  96742. */
  96743. PhysicsImpostor.MeshImpostor = 4;
  96744. /**
  96745. * Cylinder-Imposter type
  96746. */
  96747. PhysicsImpostor.CylinderImpostor = 7;
  96748. /**
  96749. * Particle-Imposter type
  96750. */
  96751. PhysicsImpostor.ParticleImpostor = 8;
  96752. /**
  96753. * Heightmap-Imposter type
  96754. */
  96755. PhysicsImpostor.HeightmapImpostor = 9;
  96756. return PhysicsImpostor;
  96757. }());
  96758. BABYLON.PhysicsImpostor = PhysicsImpostor;
  96759. })(BABYLON || (BABYLON = {}));
  96760. //# sourceMappingURL=babylon.physicsImpostor.js.map
  96761. var BABYLON;
  96762. (function (BABYLON) {
  96763. /**
  96764. * Class used to control physics engine
  96765. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  96766. */
  96767. var PhysicsEngine = /** @class */ (function () {
  96768. /**
  96769. * Creates a new Physics Engine
  96770. * @param gravity defines the gravity vector used by the simulation
  96771. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  96772. */
  96773. function PhysicsEngine(gravity, _physicsPlugin) {
  96774. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  96775. this._physicsPlugin = _physicsPlugin;
  96776. this._impostors = [];
  96777. this._joints = [];
  96778. if (!this._physicsPlugin.isSupported()) {
  96779. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  96780. + "Please make sure it is included.");
  96781. }
  96782. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  96783. this.setGravity(gravity);
  96784. this.setTimeStep();
  96785. }
  96786. /**
  96787. * Sets the gravity vector used by the simulation
  96788. * @param gravity defines the gravity vector to use
  96789. */
  96790. PhysicsEngine.prototype.setGravity = function (gravity) {
  96791. this.gravity = gravity;
  96792. this._physicsPlugin.setGravity(this.gravity);
  96793. };
  96794. /**
  96795. * Set the time step of the physics engine.
  96796. * Default is 1/60.
  96797. * To slow it down, enter 1/600 for example.
  96798. * To speed it up, 1/30
  96799. * @param newTimeStep defines the new timestep to apply to this world.
  96800. */
  96801. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  96802. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  96803. this._physicsPlugin.setTimeStep(newTimeStep);
  96804. };
  96805. /**
  96806. * Get the time step of the physics engine.
  96807. * @returns the current time step
  96808. */
  96809. PhysicsEngine.prototype.getTimeStep = function () {
  96810. return this._physicsPlugin.getTimeStep();
  96811. };
  96812. /**
  96813. * Release all resources
  96814. */
  96815. PhysicsEngine.prototype.dispose = function () {
  96816. this._impostors.forEach(function (impostor) {
  96817. impostor.dispose();
  96818. });
  96819. this._physicsPlugin.dispose();
  96820. };
  96821. /**
  96822. * Gets the name of the current physics plugin
  96823. * @returns the name of the plugin
  96824. */
  96825. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  96826. return this._physicsPlugin.name;
  96827. };
  96828. /**
  96829. * Adding a new impostor for the impostor tracking.
  96830. * This will be done by the impostor itself.
  96831. * @param impostor the impostor to add
  96832. */
  96833. PhysicsEngine.prototype.addImpostor = function (impostor) {
  96834. impostor.uniqueId = this._impostors.push(impostor);
  96835. //if no parent, generate the body
  96836. if (!impostor.parent) {
  96837. this._physicsPlugin.generatePhysicsBody(impostor);
  96838. }
  96839. };
  96840. /**
  96841. * Remove an impostor from the engine.
  96842. * This impostor and its mesh will not longer be updated by the physics engine.
  96843. * @param impostor the impostor to remove
  96844. */
  96845. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  96846. var index = this._impostors.indexOf(impostor);
  96847. if (index > -1) {
  96848. var removed = this._impostors.splice(index, 1);
  96849. //Is it needed?
  96850. if (removed.length) {
  96851. //this will also remove it from the world.
  96852. removed[0].physicsBody = null;
  96853. }
  96854. }
  96855. };
  96856. /**
  96857. * Add a joint to the physics engine
  96858. * @param mainImpostor defines the main impostor to which the joint is added.
  96859. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  96860. * @param joint defines the joint that will connect both impostors.
  96861. */
  96862. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  96863. var impostorJoint = {
  96864. mainImpostor: mainImpostor,
  96865. connectedImpostor: connectedImpostor,
  96866. joint: joint
  96867. };
  96868. joint.physicsPlugin = this._physicsPlugin;
  96869. this._joints.push(impostorJoint);
  96870. this._physicsPlugin.generateJoint(impostorJoint);
  96871. };
  96872. /**
  96873. * Removes a joint from the simulation
  96874. * @param mainImpostor defines the impostor used with the joint
  96875. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  96876. * @param joint defines the joint to remove
  96877. */
  96878. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  96879. var matchingJoints = this._joints.filter(function (impostorJoint) {
  96880. return (impostorJoint.connectedImpostor === connectedImpostor
  96881. && impostorJoint.joint === joint
  96882. && impostorJoint.mainImpostor === mainImpostor);
  96883. });
  96884. if (matchingJoints.length) {
  96885. this._physicsPlugin.removeJoint(matchingJoints[0]);
  96886. //TODO remove it from the list as well
  96887. }
  96888. };
  96889. /**
  96890. * Called by the scene. No need to call it.
  96891. * @param delta defines the timespam between frames
  96892. */
  96893. PhysicsEngine.prototype._step = function (delta) {
  96894. var _this = this;
  96895. //check if any mesh has no body / requires an update
  96896. this._impostors.forEach(function (impostor) {
  96897. if (impostor.isBodyInitRequired()) {
  96898. _this._physicsPlugin.generatePhysicsBody(impostor);
  96899. }
  96900. });
  96901. if (delta > 0.1) {
  96902. delta = 0.1;
  96903. }
  96904. else if (delta <= 0) {
  96905. delta = 1.0 / 60.0;
  96906. }
  96907. this._physicsPlugin.executeStep(delta, this._impostors);
  96908. };
  96909. /**
  96910. * Gets the current plugin used to run the simulation
  96911. * @returns current plugin
  96912. */
  96913. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  96914. return this._physicsPlugin;
  96915. };
  96916. /**
  96917. * Gets the list of physic impostors
  96918. * @returns an array of PhysicsImpostor
  96919. */
  96920. PhysicsEngine.prototype.getImpostors = function () {
  96921. return this._impostors;
  96922. };
  96923. /**
  96924. * Gets the impostor for a physics enabled object
  96925. * @param object defines the object impersonated by the impostor
  96926. * @returns the PhysicsImpostor or null if not found
  96927. */
  96928. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  96929. for (var i = 0; i < this._impostors.length; ++i) {
  96930. if (this._impostors[i].object === object) {
  96931. return this._impostors[i];
  96932. }
  96933. }
  96934. return null;
  96935. };
  96936. /**
  96937. * Gets the impostor for a physics body object
  96938. * @param body defines physics body used by the impostor
  96939. * @returns the PhysicsImpostor or null if not found
  96940. */
  96941. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  96942. for (var i = 0; i < this._impostors.length; ++i) {
  96943. if (this._impostors[i].physicsBody === body) {
  96944. return this._impostors[i];
  96945. }
  96946. }
  96947. return null;
  96948. };
  96949. /**
  96950. * Global value used to control the smallest number supported by the simulation
  96951. */
  96952. PhysicsEngine.Epsilon = 0.001;
  96953. return PhysicsEngine;
  96954. }());
  96955. BABYLON.PhysicsEngine = PhysicsEngine;
  96956. })(BABYLON || (BABYLON = {}));
  96957. //# sourceMappingURL=babylon.physicsEngine.js.map
  96958. var BABYLON;
  96959. (function (BABYLON) {
  96960. /**
  96961. * A helper for physics simulations
  96962. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96963. */
  96964. var PhysicsHelper = /** @class */ (function () {
  96965. /**
  96966. * Initializes the Physics helper
  96967. * @param scene Babylon.js scene
  96968. */
  96969. function PhysicsHelper(scene) {
  96970. this._scene = scene;
  96971. this._physicsEngine = this._scene.getPhysicsEngine();
  96972. if (!this._physicsEngine) {
  96973. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  96974. }
  96975. }
  96976. /**
  96977. * Applies a radial explosion impulse
  96978. * @param origin the origin of the explosion
  96979. * @param radius the explosion radius
  96980. * @param strength the explosion strength
  96981. * @param falloff possible options: Constant & Linear. Defaults to Constant
  96982. * @returns A physics radial explosion event, or null
  96983. */
  96984. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  96985. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  96986. if (!this._physicsEngine) {
  96987. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  96988. return null;
  96989. }
  96990. var impostors = this._physicsEngine.getImpostors();
  96991. if (impostors.length === 0) {
  96992. return null;
  96993. }
  96994. var event = new PhysicsRadialExplosionEvent(this._scene);
  96995. impostors.forEach(function (impostor) {
  96996. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  96997. if (!impostorForceAndContactPoint) {
  96998. return;
  96999. }
  97000. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97001. });
  97002. event.dispose(false);
  97003. return event;
  97004. };
  97005. /**
  97006. * Applies a radial explosion force
  97007. * @param origin the origin of the explosion
  97008. * @param radius the explosion radius
  97009. * @param strength the explosion strength
  97010. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97011. * @returns A physics radial explosion event, or null
  97012. */
  97013. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  97014. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97015. if (!this._physicsEngine) {
  97016. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97017. return null;
  97018. }
  97019. var impostors = this._physicsEngine.getImpostors();
  97020. if (impostors.length === 0) {
  97021. return null;
  97022. }
  97023. var event = new PhysicsRadialExplosionEvent(this._scene);
  97024. impostors.forEach(function (impostor) {
  97025. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  97026. if (!impostorForceAndContactPoint) {
  97027. return;
  97028. }
  97029. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97030. });
  97031. event.dispose(false);
  97032. return event;
  97033. };
  97034. /**
  97035. * Creates a gravitational field
  97036. * @param origin the origin of the explosion
  97037. * @param radius the explosion radius
  97038. * @param strength the explosion strength
  97039. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97040. * @returns A physics gravitational field event, or null
  97041. */
  97042. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  97043. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97044. if (!this._physicsEngine) {
  97045. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97046. return null;
  97047. }
  97048. var impostors = this._physicsEngine.getImpostors();
  97049. if (impostors.length === 0) {
  97050. return null;
  97051. }
  97052. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  97053. event.dispose(false);
  97054. return event;
  97055. };
  97056. /**
  97057. * Creates a physics updraft event
  97058. * @param origin the origin of the updraft
  97059. * @param radius the radius of the updraft
  97060. * @param strength the strength of the updraft
  97061. * @param height the height of the updraft
  97062. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  97063. * @returns A physics updraft event, or null
  97064. */
  97065. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  97066. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  97067. if (!this._physicsEngine) {
  97068. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97069. return null;
  97070. }
  97071. if (this._physicsEngine.getImpostors().length === 0) {
  97072. return null;
  97073. }
  97074. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  97075. event.dispose(false);
  97076. return event;
  97077. };
  97078. /**
  97079. * Creates a physics vortex event
  97080. * @param origin the of the vortex
  97081. * @param radius the radius of the vortex
  97082. * @param strength the strength of the vortex
  97083. * @param height the height of the vortex
  97084. * @returns a Physics vortex event, or null
  97085. * A physics vortex event or null
  97086. */
  97087. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  97088. if (!this._physicsEngine) {
  97089. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97090. return null;
  97091. }
  97092. if (this._physicsEngine.getImpostors().length === 0) {
  97093. return null;
  97094. }
  97095. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  97096. event.dispose(false);
  97097. return event;
  97098. };
  97099. return PhysicsHelper;
  97100. }());
  97101. BABYLON.PhysicsHelper = PhysicsHelper;
  97102. /**
  97103. * Represents a physics radial explosion event
  97104. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97105. */
  97106. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  97107. /**
  97108. * Initializes a radial explosioin event
  97109. * @param scene BabylonJS scene
  97110. */
  97111. function PhysicsRadialExplosionEvent(scene) {
  97112. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  97113. this._rays = [];
  97114. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  97115. this._scene = scene;
  97116. }
  97117. /**
  97118. * Returns the data related to the radial explosion event (sphere & rays).
  97119. * @returns The radial explosion event data
  97120. */
  97121. PhysicsRadialExplosionEvent.prototype.getData = function () {
  97122. this._dataFetched = true;
  97123. return {
  97124. sphere: this._sphere,
  97125. rays: this._rays,
  97126. };
  97127. };
  97128. /**
  97129. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  97130. * @param impostor A physics imposter
  97131. * @param origin the origin of the explosion
  97132. * @param radius the explosion radius
  97133. * @param strength the explosion strength
  97134. * @param falloff possible options: Constant & Linear
  97135. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  97136. */
  97137. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  97138. if (impostor.mass === 0) {
  97139. return null;
  97140. }
  97141. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  97142. return null;
  97143. }
  97144. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  97145. return null;
  97146. }
  97147. var impostorObjectCenter = impostor.getObjectCenter();
  97148. var direction = impostorObjectCenter.subtract(origin);
  97149. var ray = new BABYLON.Ray(origin, direction, radius);
  97150. this._rays.push(ray);
  97151. var hit = ray.intersectsMesh(impostor.object);
  97152. var contactPoint = hit.pickedPoint;
  97153. if (!contactPoint) {
  97154. return null;
  97155. }
  97156. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  97157. if (distanceFromOrigin > radius) {
  97158. return null;
  97159. }
  97160. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  97161. ? strength
  97162. : strength * (1 - (distanceFromOrigin / radius));
  97163. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  97164. return { force: force, contactPoint: contactPoint };
  97165. };
  97166. /**
  97167. * Disposes the sphere.
  97168. * @param force Specifies if the sphere should be disposed by force
  97169. */
  97170. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  97171. var _this = this;
  97172. if (force === void 0) { force = true; }
  97173. if (force) {
  97174. this._sphere.dispose();
  97175. }
  97176. else {
  97177. setTimeout(function () {
  97178. if (!_this._dataFetched) {
  97179. _this._sphere.dispose();
  97180. }
  97181. }, 0);
  97182. }
  97183. };
  97184. /*** Helpers ***/
  97185. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  97186. if (!this._sphere) {
  97187. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  97188. this._sphere.isVisible = false;
  97189. }
  97190. };
  97191. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  97192. var impostorObject = impostor.object;
  97193. this._prepareSphere();
  97194. this._sphere.position = origin;
  97195. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  97196. this._sphere._updateBoundingInfo();
  97197. this._sphere.computeWorldMatrix(true);
  97198. return this._sphere.intersectsMesh(impostorObject, true);
  97199. };
  97200. return PhysicsRadialExplosionEvent;
  97201. }());
  97202. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  97203. /**
  97204. * Represents a gravitational field event
  97205. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97206. */
  97207. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  97208. /**
  97209. * Initializes the physics gravitational field event
  97210. * @param physicsHelper A physics helper
  97211. * @param scene BabylonJS scene
  97212. * @param origin The origin position of the gravitational field event
  97213. * @param radius The radius of the gravitational field event
  97214. * @param strength The strength of the gravitational field event
  97215. * @param falloff The falloff for the gravitational field event
  97216. */
  97217. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  97218. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97219. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97220. this._physicsHelper = physicsHelper;
  97221. this._scene = scene;
  97222. this._origin = origin;
  97223. this._radius = radius;
  97224. this._strength = strength;
  97225. this._falloff = falloff;
  97226. this._tickCallback = this._tick.bind(this);
  97227. }
  97228. /**
  97229. * Returns the data related to the gravitational field event (sphere).
  97230. * @returns A gravitational field event
  97231. */
  97232. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  97233. this._dataFetched = true;
  97234. return {
  97235. sphere: this._sphere,
  97236. };
  97237. };
  97238. /**
  97239. * Enables the gravitational field.
  97240. */
  97241. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  97242. this._tickCallback.call(this);
  97243. this._scene.registerBeforeRender(this._tickCallback);
  97244. };
  97245. /**
  97246. * Disables the gravitational field.
  97247. */
  97248. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  97249. this._scene.unregisterBeforeRender(this._tickCallback);
  97250. };
  97251. /**
  97252. * Disposes the sphere.
  97253. * @param force The force to dispose from the gravitational field event
  97254. */
  97255. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  97256. var _this = this;
  97257. if (force === void 0) { force = true; }
  97258. if (force) {
  97259. this._sphere.dispose();
  97260. }
  97261. else {
  97262. setTimeout(function () {
  97263. if (!_this._dataFetched) {
  97264. _this._sphere.dispose();
  97265. }
  97266. }, 0);
  97267. }
  97268. };
  97269. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  97270. // Since the params won't change, we fetch the event only once
  97271. if (this._sphere) {
  97272. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  97273. }
  97274. else {
  97275. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  97276. if (radialExplosionEvent) {
  97277. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  97278. }
  97279. }
  97280. };
  97281. return PhysicsGravitationalFieldEvent;
  97282. }());
  97283. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  97284. /**
  97285. * Represents a physics updraft event
  97286. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97287. */
  97288. var PhysicsUpdraftEvent = /** @class */ (function () {
  97289. /**
  97290. * Initializes the physics updraft event
  97291. * @param _scene BabylonJS scene
  97292. * @param _origin The origin position of the updraft
  97293. * @param _radius The radius of the updraft
  97294. * @param _strength The strength of the updraft
  97295. * @param _height The height of the updraft
  97296. * @param _updraftMode The mode of the updraft
  97297. */
  97298. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  97299. this._scene = _scene;
  97300. this._origin = _origin;
  97301. this._radius = _radius;
  97302. this._strength = _strength;
  97303. this._height = _height;
  97304. this._updraftMode = _updraftMode;
  97305. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  97306. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  97307. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  97308. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97309. this._physicsEngine = this._scene.getPhysicsEngine();
  97310. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  97311. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  97312. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  97313. this._originDirection = this._origin.subtract(this._originTop).normalize();
  97314. }
  97315. this._tickCallback = this._tick.bind(this);
  97316. }
  97317. /**
  97318. * Returns the data related to the updraft event (cylinder).
  97319. * @returns A physics updraft event
  97320. */
  97321. PhysicsUpdraftEvent.prototype.getData = function () {
  97322. this._dataFetched = true;
  97323. return {
  97324. cylinder: this._cylinder,
  97325. };
  97326. };
  97327. /**
  97328. * Enables the updraft.
  97329. */
  97330. PhysicsUpdraftEvent.prototype.enable = function () {
  97331. this._tickCallback.call(this);
  97332. this._scene.registerBeforeRender(this._tickCallback);
  97333. };
  97334. /**
  97335. * Disables the cortex.
  97336. */
  97337. PhysicsUpdraftEvent.prototype.disable = function () {
  97338. this._scene.unregisterBeforeRender(this._tickCallback);
  97339. };
  97340. /**
  97341. * Disposes the sphere.
  97342. * @param force Specifies if the updraft should be disposed by force
  97343. */
  97344. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  97345. var _this = this;
  97346. if (force === void 0) { force = true; }
  97347. if (force) {
  97348. this._cylinder.dispose();
  97349. }
  97350. else {
  97351. setTimeout(function () {
  97352. if (!_this._dataFetched) {
  97353. _this._cylinder.dispose();
  97354. }
  97355. }, 0);
  97356. }
  97357. };
  97358. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  97359. if (impostor.mass === 0) {
  97360. return null;
  97361. }
  97362. if (!this._intersectsWithCylinder(impostor)) {
  97363. return null;
  97364. }
  97365. var impostorObjectCenter = impostor.getObjectCenter();
  97366. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  97367. var direction = this._originDirection;
  97368. }
  97369. else {
  97370. var direction = impostorObjectCenter.subtract(this._originTop);
  97371. }
  97372. var multiplier = this._strength * -1;
  97373. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  97374. return { force: force, contactPoint: impostorObjectCenter };
  97375. };
  97376. PhysicsUpdraftEvent.prototype._tick = function () {
  97377. var _this = this;
  97378. this._physicsEngine.getImpostors().forEach(function (impostor) {
  97379. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  97380. if (!impostorForceAndContactPoint) {
  97381. return;
  97382. }
  97383. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97384. });
  97385. };
  97386. /*** Helpers ***/
  97387. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  97388. if (!this._cylinder) {
  97389. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  97390. height: this._height,
  97391. diameter: this._radius * 2,
  97392. }, this._scene);
  97393. this._cylinder.isVisible = false;
  97394. }
  97395. };
  97396. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  97397. var impostorObject = impostor.object;
  97398. this._prepareCylinder();
  97399. this._cylinder.position = this._cylinderPosition;
  97400. return this._cylinder.intersectsMesh(impostorObject, true);
  97401. };
  97402. return PhysicsUpdraftEvent;
  97403. }());
  97404. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  97405. /**
  97406. * Represents a physics vortex event
  97407. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97408. */
  97409. var PhysicsVortexEvent = /** @class */ (function () {
  97410. /**
  97411. * Initializes the physics vortex event
  97412. * @param _scene The BabylonJS scene
  97413. * @param _origin The origin position of the vortex
  97414. * @param _radius The radius of the vortex
  97415. * @param _strength The strength of the vortex
  97416. * @param _height The height of the vortex
  97417. */
  97418. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  97419. this._scene = _scene;
  97420. this._origin = _origin;
  97421. this._radius = _radius;
  97422. this._strength = _strength;
  97423. this._height = _height;
  97424. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  97425. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  97426. this._updraftMultiplier = 0.02;
  97427. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  97428. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97429. this._physicsEngine = this._scene.getPhysicsEngine();
  97430. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  97431. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  97432. this._tickCallback = this._tick.bind(this);
  97433. }
  97434. /**
  97435. * Returns the data related to the vortex event (cylinder).
  97436. * @returns The physics vortex event data
  97437. */
  97438. PhysicsVortexEvent.prototype.getData = function () {
  97439. this._dataFetched = true;
  97440. return {
  97441. cylinder: this._cylinder,
  97442. };
  97443. };
  97444. /**
  97445. * Enables the vortex.
  97446. */
  97447. PhysicsVortexEvent.prototype.enable = function () {
  97448. this._tickCallback.call(this);
  97449. this._scene.registerBeforeRender(this._tickCallback);
  97450. };
  97451. /**
  97452. * Disables the cortex.
  97453. */
  97454. PhysicsVortexEvent.prototype.disable = function () {
  97455. this._scene.unregisterBeforeRender(this._tickCallback);
  97456. };
  97457. /**
  97458. * Disposes the sphere.
  97459. * @param force
  97460. */
  97461. PhysicsVortexEvent.prototype.dispose = function (force) {
  97462. var _this = this;
  97463. if (force === void 0) { force = true; }
  97464. if (force) {
  97465. this._cylinder.dispose();
  97466. }
  97467. else {
  97468. setTimeout(function () {
  97469. if (!_this._dataFetched) {
  97470. _this._cylinder.dispose();
  97471. }
  97472. }, 0);
  97473. }
  97474. };
  97475. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  97476. if (impostor.mass === 0) {
  97477. return null;
  97478. }
  97479. if (!this._intersectsWithCylinder(impostor)) {
  97480. return null;
  97481. }
  97482. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  97483. return null;
  97484. }
  97485. var impostorObjectCenter = impostor.getObjectCenter();
  97486. 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)
  97487. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  97488. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  97489. var hit = ray.intersectsMesh(impostor.object);
  97490. var contactPoint = hit.pickedPoint;
  97491. if (!contactPoint) {
  97492. return null;
  97493. }
  97494. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  97495. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  97496. var directionToOrigin = contactPoint.normalize();
  97497. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  97498. directionToOrigin = directionToOrigin.negate();
  97499. }
  97500. // TODO: find a more physically based solution
  97501. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  97502. var forceX = directionToOrigin.x * this._strength / 8;
  97503. var forceY = directionToOrigin.y * this._updraftMultiplier;
  97504. var forceZ = directionToOrigin.z * this._strength / 8;
  97505. }
  97506. else {
  97507. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  97508. var forceY = this._originTop.y * this._updraftMultiplier;
  97509. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  97510. }
  97511. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  97512. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  97513. return { force: force, contactPoint: impostorObjectCenter };
  97514. };
  97515. PhysicsVortexEvent.prototype._tick = function () {
  97516. var _this = this;
  97517. this._physicsEngine.getImpostors().forEach(function (impostor) {
  97518. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  97519. if (!impostorForceAndContactPoint) {
  97520. return;
  97521. }
  97522. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97523. });
  97524. };
  97525. /*** Helpers ***/
  97526. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  97527. if (!this._cylinder) {
  97528. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  97529. height: this._height,
  97530. diameter: this._radius * 2,
  97531. }, this._scene);
  97532. this._cylinder.isVisible = false;
  97533. }
  97534. };
  97535. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  97536. var impostorObject = impostor.object;
  97537. this._prepareCylinder();
  97538. this._cylinder.position = this._cylinderPosition;
  97539. return this._cylinder.intersectsMesh(impostorObject, true);
  97540. };
  97541. return PhysicsVortexEvent;
  97542. }());
  97543. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  97544. /**
  97545. * The strenght of the force in correspondence to the distance of the affected object
  97546. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97547. */
  97548. var PhysicsRadialImpulseFalloff;
  97549. (function (PhysicsRadialImpulseFalloff) {
  97550. /** Defines that impulse is constant in strength across it's whole radius */
  97551. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  97552. /** DEfines that impulse gets weaker if it's further from the origin */
  97553. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  97554. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  97555. /**
  97556. * The strength of the force in correspondence to the distance of the affected object
  97557. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97558. */
  97559. var PhysicsUpdraftMode;
  97560. (function (PhysicsUpdraftMode) {
  97561. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  97562. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  97563. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  97564. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  97565. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  97566. })(BABYLON || (BABYLON = {}));
  97567. //# sourceMappingURL=babylon.physicsHelper.js.map
  97568. var BABYLON;
  97569. (function (BABYLON) {
  97570. /** @hidden */
  97571. var CannonJSPlugin = /** @class */ (function () {
  97572. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  97573. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  97574. if (iterations === void 0) { iterations = 10; }
  97575. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  97576. this.name = "CannonJSPlugin";
  97577. this._physicsMaterials = new Array();
  97578. this._fixedTimeStep = 1 / 60;
  97579. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  97580. this.BJSCANNON = CANNON;
  97581. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  97582. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  97583. this._tmpPosition = BABYLON.Vector3.Zero();
  97584. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  97585. this._tmpUnityRotation = new BABYLON.Quaternion();
  97586. if (!this.isSupported()) {
  97587. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  97588. return;
  97589. }
  97590. this._extendNamespace();
  97591. this.world = new this.BJSCANNON.World();
  97592. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  97593. this.world.solver.iterations = iterations;
  97594. }
  97595. CannonJSPlugin.prototype.setGravity = function (gravity) {
  97596. this.world.gravity.copy(gravity);
  97597. };
  97598. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  97599. this._fixedTimeStep = timeStep;
  97600. };
  97601. CannonJSPlugin.prototype.getTimeStep = function () {
  97602. return this._fixedTimeStep;
  97603. };
  97604. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  97605. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  97606. };
  97607. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  97608. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  97609. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  97610. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  97611. };
  97612. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  97613. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  97614. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  97615. impostor.physicsBody.applyForce(impulse, worldPoint);
  97616. };
  97617. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  97618. //parent-child relationship. Does this impostor has a parent impostor?
  97619. if (impostor.parent) {
  97620. if (impostor.physicsBody) {
  97621. this.removePhysicsBody(impostor);
  97622. //TODO is that needed?
  97623. impostor.forceUpdate();
  97624. }
  97625. return;
  97626. }
  97627. //should a new body be created for this impostor?
  97628. if (impostor.isBodyInitRequired()) {
  97629. var shape = this._createShape(impostor);
  97630. //unregister events, if body is being changed
  97631. var oldBody = impostor.physicsBody;
  97632. if (oldBody) {
  97633. this.removePhysicsBody(impostor);
  97634. }
  97635. //create the body and material
  97636. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  97637. var bodyCreationObject = {
  97638. mass: impostor.getParam("mass"),
  97639. material: material
  97640. };
  97641. // A simple extend, in case native options were used.
  97642. var nativeOptions = impostor.getParam("nativeOptions");
  97643. for (var key in nativeOptions) {
  97644. if (nativeOptions.hasOwnProperty(key)) {
  97645. bodyCreationObject[key] = nativeOptions[key];
  97646. }
  97647. }
  97648. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  97649. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  97650. this.world.addEventListener("preStep", impostor.beforeStep);
  97651. this.world.addEventListener("postStep", impostor.afterStep);
  97652. impostor.physicsBody.addShape(shape);
  97653. this.world.add(impostor.physicsBody);
  97654. //try to keep the body moving in the right direction by taking old properties.
  97655. //Should be tested!
  97656. if (oldBody) {
  97657. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  97658. impostor.physicsBody[param].copy(oldBody[param]);
  97659. });
  97660. }
  97661. this._processChildMeshes(impostor);
  97662. }
  97663. //now update the body's transformation
  97664. this._updatePhysicsBodyTransformation(impostor);
  97665. };
  97666. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  97667. var _this = this;
  97668. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  97669. var currentRotation = mainImpostor.object.rotationQuaternion;
  97670. if (meshChildren.length) {
  97671. var processMesh = function (localPosition, mesh) {
  97672. if (!currentRotation || !mesh.rotationQuaternion) {
  97673. return;
  97674. }
  97675. var childImpostor = mesh.getPhysicsImpostor();
  97676. if (childImpostor) {
  97677. var parent = childImpostor.parent;
  97678. if (parent !== mainImpostor) {
  97679. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  97680. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  97681. if (childImpostor.physicsBody) {
  97682. _this.removePhysicsBody(childImpostor);
  97683. childImpostor.physicsBody = null;
  97684. }
  97685. childImpostor.parent = mainImpostor;
  97686. childImpostor.resetUpdateFlags();
  97687. 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));
  97688. //Add the mass of the children.
  97689. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  97690. }
  97691. }
  97692. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  97693. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  97694. };
  97695. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  97696. }
  97697. };
  97698. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  97699. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  97700. this.world.removeEventListener("preStep", impostor.beforeStep);
  97701. this.world.removeEventListener("postStep", impostor.afterStep);
  97702. this.world.remove(impostor.physicsBody);
  97703. };
  97704. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  97705. var mainBody = impostorJoint.mainImpostor.physicsBody;
  97706. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  97707. if (!mainBody || !connectedBody) {
  97708. return;
  97709. }
  97710. var constraint;
  97711. var jointData = impostorJoint.joint.jointData;
  97712. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  97713. var constraintData = {
  97714. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  97715. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  97716. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  97717. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  97718. maxForce: jointData.nativeParams.maxForce,
  97719. collideConnected: !!jointData.collision
  97720. };
  97721. switch (impostorJoint.joint.type) {
  97722. case BABYLON.PhysicsJoint.HingeJoint:
  97723. case BABYLON.PhysicsJoint.Hinge2Joint:
  97724. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  97725. break;
  97726. case BABYLON.PhysicsJoint.DistanceJoint:
  97727. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  97728. break;
  97729. case BABYLON.PhysicsJoint.SpringJoint:
  97730. var springData = jointData;
  97731. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  97732. restLength: springData.length,
  97733. stiffness: springData.stiffness,
  97734. damping: springData.damping,
  97735. localAnchorA: constraintData.pivotA,
  97736. localAnchorB: constraintData.pivotB
  97737. });
  97738. break;
  97739. case BABYLON.PhysicsJoint.LockJoint:
  97740. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  97741. break;
  97742. case BABYLON.PhysicsJoint.PointToPointJoint:
  97743. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  97744. default:
  97745. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  97746. break;
  97747. }
  97748. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  97749. constraint.collideConnected = !!jointData.collision;
  97750. impostorJoint.joint.physicsJoint = constraint;
  97751. //don't add spring as constraint, as it is not one.
  97752. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  97753. this.world.addConstraint(constraint);
  97754. }
  97755. else {
  97756. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  97757. constraint.applyForce();
  97758. };
  97759. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  97760. }
  97761. };
  97762. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  97763. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  97764. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  97765. }
  97766. else {
  97767. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  97768. }
  97769. };
  97770. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  97771. var index;
  97772. var mat;
  97773. for (index = 0; index < this._physicsMaterials.length; index++) {
  97774. mat = this._physicsMaterials[index];
  97775. if (mat.friction === friction && mat.restitution === restitution) {
  97776. return mat;
  97777. }
  97778. }
  97779. var currentMat = new this.BJSCANNON.Material(name);
  97780. currentMat.friction = friction;
  97781. currentMat.restitution = restitution;
  97782. this._physicsMaterials.push(currentMat);
  97783. return currentMat;
  97784. };
  97785. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  97786. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  97787. };
  97788. CannonJSPlugin.prototype._createShape = function (impostor) {
  97789. var object = impostor.object;
  97790. var returnValue;
  97791. var extendSize = impostor.getObjectExtendSize();
  97792. switch (impostor.type) {
  97793. case BABYLON.PhysicsImpostor.SphereImpostor:
  97794. var radiusX = extendSize.x;
  97795. var radiusY = extendSize.y;
  97796. var radiusZ = extendSize.z;
  97797. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  97798. break;
  97799. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  97800. case BABYLON.PhysicsImpostor.CylinderImpostor:
  97801. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  97802. break;
  97803. case BABYLON.PhysicsImpostor.BoxImpostor:
  97804. var box = extendSize.scale(0.5);
  97805. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  97806. break;
  97807. case BABYLON.PhysicsImpostor.PlaneImpostor:
  97808. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  97809. returnValue = new this.BJSCANNON.Plane();
  97810. break;
  97811. case BABYLON.PhysicsImpostor.MeshImpostor:
  97812. // should transform the vertex data to world coordinates!!
  97813. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  97814. var rawFaces = object.getIndices ? object.getIndices() : [];
  97815. if (!rawVerts) {
  97816. return;
  97817. }
  97818. // get only scale! so the object could transform correctly.
  97819. var oldPosition = object.position.clone();
  97820. var oldRotation = object.rotation && object.rotation.clone();
  97821. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  97822. object.position.copyFromFloats(0, 0, 0);
  97823. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  97824. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  97825. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  97826. var transform = object.computeWorldMatrix(true);
  97827. // convert rawVerts to object space
  97828. var temp = new Array();
  97829. var index;
  97830. for (index = 0; index < rawVerts.length; index += 3) {
  97831. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  97832. }
  97833. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  97834. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  97835. //now set back the transformation!
  97836. object.position.copyFrom(oldPosition);
  97837. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  97838. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  97839. break;
  97840. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  97841. var oldPosition2 = object.position.clone();
  97842. var oldRotation2 = object.rotation && object.rotation.clone();
  97843. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  97844. object.position.copyFromFloats(0, 0, 0);
  97845. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  97846. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  97847. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  97848. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  97849. returnValue = this._createHeightmap(object);
  97850. object.position.copyFrom(oldPosition2);
  97851. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  97852. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  97853. object.computeWorldMatrix(true);
  97854. break;
  97855. case BABYLON.PhysicsImpostor.ParticleImpostor:
  97856. returnValue = new this.BJSCANNON.Particle();
  97857. break;
  97858. }
  97859. return returnValue;
  97860. };
  97861. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  97862. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  97863. var transform = object.computeWorldMatrix(true);
  97864. // convert rawVerts to object space
  97865. var temp = new Array();
  97866. var index;
  97867. for (index = 0; index < pos.length; index += 3) {
  97868. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  97869. }
  97870. pos = temp;
  97871. var matrix = new Array();
  97872. //For now pointDepth will not be used and will be automatically calculated.
  97873. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  97874. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  97875. var boundingInfo = object.getBoundingInfo();
  97876. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  97877. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  97878. var elementSize = dim * 2 / arraySize;
  97879. for (var i = 0; i < pos.length; i = i + 3) {
  97880. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  97881. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  97882. var y = -pos[i + 2] + minY;
  97883. if (!matrix[x]) {
  97884. matrix[x] = [];
  97885. }
  97886. if (!matrix[x][z]) {
  97887. matrix[x][z] = y;
  97888. }
  97889. matrix[x][z] = Math.max(y, matrix[x][z]);
  97890. }
  97891. for (var x = 0; x <= arraySize; ++x) {
  97892. if (!matrix[x]) {
  97893. var loc = 1;
  97894. while (!matrix[(x + loc) % arraySize]) {
  97895. loc++;
  97896. }
  97897. matrix[x] = matrix[(x + loc) % arraySize].slice();
  97898. //console.log("missing x", x);
  97899. }
  97900. for (var z = 0; z <= arraySize; ++z) {
  97901. if (!matrix[x][z]) {
  97902. var loc = 1;
  97903. var newValue;
  97904. while (newValue === undefined) {
  97905. newValue = matrix[x][(z + loc++) % arraySize];
  97906. }
  97907. matrix[x][z] = newValue;
  97908. }
  97909. }
  97910. }
  97911. var shape = new this.BJSCANNON.Heightfield(matrix, {
  97912. elementSize: elementSize
  97913. });
  97914. //For future reference, needed for body transformation
  97915. shape.minY = minY;
  97916. return shape;
  97917. };
  97918. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  97919. var object = impostor.object;
  97920. //make sure it is updated...
  97921. object.computeWorldMatrix && object.computeWorldMatrix(true);
  97922. // The delta between the mesh position and the mesh bounding box center
  97923. var bInfo = object.getBoundingInfo();
  97924. if (!bInfo) {
  97925. return;
  97926. }
  97927. var center = impostor.getObjectCenter();
  97928. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  97929. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  97930. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  97931. this._tmpPosition.copyFrom(center);
  97932. var quaternion = object.rotationQuaternion;
  97933. if (!quaternion) {
  97934. return;
  97935. }
  97936. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  97937. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  97938. //-90 DEG in X, precalculated
  97939. quaternion = quaternion.multiply(this._minus90X);
  97940. //Invert! (Precalculated, 90 deg in X)
  97941. //No need to clone. this will never change.
  97942. impostor.setDeltaRotation(this._plus90X);
  97943. }
  97944. //If it is a heightfield, if should be centered.
  97945. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  97946. var mesh = object;
  97947. var boundingInfo = mesh.getBoundingInfo();
  97948. //calculate the correct body position:
  97949. var rotationQuaternion = mesh.rotationQuaternion;
  97950. mesh.rotationQuaternion = this._tmpUnityRotation;
  97951. mesh.computeWorldMatrix(true);
  97952. //get original center with no rotation
  97953. var c = center.clone();
  97954. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  97955. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  97956. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  97957. mesh.setPreTransformMatrix(p);
  97958. mesh.computeWorldMatrix(true);
  97959. //calculate the translation
  97960. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  97961. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  97962. //add it inverted to the delta
  97963. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  97964. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  97965. //rotation is back
  97966. mesh.rotationQuaternion = rotationQuaternion;
  97967. mesh.setPreTransformMatrix(oldPivot);
  97968. mesh.computeWorldMatrix(true);
  97969. }
  97970. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  97971. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  97972. //this._tmpPosition.copyFrom(object.position);
  97973. }
  97974. impostor.setDeltaPosition(this._tmpDeltaPosition);
  97975. //Now update the impostor object
  97976. impostor.physicsBody.position.copy(this._tmpPosition);
  97977. impostor.physicsBody.quaternion.copy(quaternion);
  97978. };
  97979. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  97980. impostor.object.position.copyFrom(impostor.physicsBody.position);
  97981. if (impostor.object.rotationQuaternion) {
  97982. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  97983. }
  97984. };
  97985. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  97986. impostor.physicsBody.position.copy(newPosition);
  97987. impostor.physicsBody.quaternion.copy(newRotation);
  97988. };
  97989. CannonJSPlugin.prototype.isSupported = function () {
  97990. return this.BJSCANNON !== undefined;
  97991. };
  97992. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  97993. impostor.physicsBody.velocity.copy(velocity);
  97994. };
  97995. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  97996. impostor.physicsBody.angularVelocity.copy(velocity);
  97997. };
  97998. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  97999. var v = impostor.physicsBody.velocity;
  98000. if (!v) {
  98001. return null;
  98002. }
  98003. return new BABYLON.Vector3(v.x, v.y, v.z);
  98004. };
  98005. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  98006. var v = impostor.physicsBody.angularVelocity;
  98007. if (!v) {
  98008. return null;
  98009. }
  98010. return new BABYLON.Vector3(v.x, v.y, v.z);
  98011. };
  98012. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  98013. impostor.physicsBody.mass = mass;
  98014. impostor.physicsBody.updateMassProperties();
  98015. };
  98016. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  98017. return impostor.physicsBody.mass;
  98018. };
  98019. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  98020. return impostor.physicsBody.material.friction;
  98021. };
  98022. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  98023. impostor.physicsBody.material.friction = friction;
  98024. };
  98025. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  98026. return impostor.physicsBody.material.restitution;
  98027. };
  98028. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  98029. impostor.physicsBody.material.restitution = restitution;
  98030. };
  98031. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  98032. impostor.physicsBody.sleep();
  98033. };
  98034. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  98035. impostor.physicsBody.wakeUp();
  98036. };
  98037. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  98038. joint.physicsJoint.distance = maxDistance;
  98039. };
  98040. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  98041. // if (!motorIndex) {
  98042. // joint.physicsJoint.enableMotor();
  98043. // }
  98044. // }
  98045. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  98046. // if (!motorIndex) {
  98047. // joint.physicsJoint.disableMotor();
  98048. // }
  98049. // }
  98050. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  98051. if (!motorIndex) {
  98052. joint.physicsJoint.enableMotor();
  98053. joint.physicsJoint.setMotorSpeed(speed);
  98054. if (maxForce) {
  98055. this.setLimit(joint, maxForce);
  98056. }
  98057. }
  98058. };
  98059. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  98060. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  98061. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  98062. };
  98063. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  98064. var body = impostor.physicsBody;
  98065. mesh.position.x = body.position.x;
  98066. mesh.position.y = body.position.y;
  98067. mesh.position.z = body.position.z;
  98068. if (mesh.rotationQuaternion) {
  98069. mesh.rotationQuaternion.x = body.quaternion.x;
  98070. mesh.rotationQuaternion.y = body.quaternion.y;
  98071. mesh.rotationQuaternion.z = body.quaternion.z;
  98072. mesh.rotationQuaternion.w = body.quaternion.w;
  98073. }
  98074. };
  98075. CannonJSPlugin.prototype.getRadius = function (impostor) {
  98076. var shape = impostor.physicsBody.shapes[0];
  98077. return shape.boundingSphereRadius;
  98078. };
  98079. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  98080. var shape = impostor.physicsBody.shapes[0];
  98081. result.x = shape.halfExtents.x * 2;
  98082. result.y = shape.halfExtents.y * 2;
  98083. result.z = shape.halfExtents.z * 2;
  98084. };
  98085. CannonJSPlugin.prototype.dispose = function () {
  98086. };
  98087. CannonJSPlugin.prototype._extendNamespace = function () {
  98088. //this will force cannon to execute at least one step when using interpolation
  98089. var step_tmp1 = new this.BJSCANNON.Vec3();
  98090. var Engine = this.BJSCANNON;
  98091. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  98092. maxSubSteps = maxSubSteps || 10;
  98093. timeSinceLastCalled = timeSinceLastCalled || 0;
  98094. if (timeSinceLastCalled === 0) {
  98095. this.internalStep(dt);
  98096. this.time += dt;
  98097. }
  98098. else {
  98099. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  98100. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  98101. var t0 = performance.now();
  98102. for (var i = 0; i !== internalSteps; i++) {
  98103. this.internalStep(dt);
  98104. if (performance.now() - t0 > dt * 1000) {
  98105. break;
  98106. }
  98107. }
  98108. this.time += timeSinceLastCalled;
  98109. var h = this.time % dt;
  98110. var h_div_dt = h / dt;
  98111. var interpvelo = step_tmp1;
  98112. var bodies = this.bodies;
  98113. for (var j = 0; j !== bodies.length; j++) {
  98114. var b = bodies[j];
  98115. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  98116. b.position.vsub(b.previousPosition, interpvelo);
  98117. interpvelo.scale(h_div_dt, interpvelo);
  98118. b.position.vadd(interpvelo, b.interpolatedPosition);
  98119. }
  98120. else {
  98121. b.interpolatedPosition.copy(b.position);
  98122. b.interpolatedQuaternion.copy(b.quaternion);
  98123. }
  98124. }
  98125. }
  98126. };
  98127. };
  98128. return CannonJSPlugin;
  98129. }());
  98130. BABYLON.CannonJSPlugin = CannonJSPlugin;
  98131. })(BABYLON || (BABYLON = {}));
  98132. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  98133. var BABYLON;
  98134. (function (BABYLON) {
  98135. /** @hidden */
  98136. var OimoJSPlugin = /** @class */ (function () {
  98137. function OimoJSPlugin(iterations) {
  98138. this.name = "OimoJSPlugin";
  98139. this._tmpImpostorsArray = [];
  98140. this._tmpPositionVector = BABYLON.Vector3.Zero();
  98141. this.BJSOIMO = OIMO;
  98142. this.world = new this.BJSOIMO.World({
  98143. iterations: iterations
  98144. });
  98145. this.world.clear();
  98146. }
  98147. OimoJSPlugin.prototype.setGravity = function (gravity) {
  98148. this.world.gravity.copy(gravity);
  98149. };
  98150. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  98151. this.world.timeStep = timeStep;
  98152. };
  98153. OimoJSPlugin.prototype.getTimeStep = function () {
  98154. return this.world.timeStep;
  98155. };
  98156. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  98157. var _this = this;
  98158. impostors.forEach(function (impostor) {
  98159. impostor.beforeStep();
  98160. });
  98161. this.world.step();
  98162. impostors.forEach(function (impostor) {
  98163. impostor.afterStep();
  98164. //update the ordered impostors array
  98165. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  98166. });
  98167. //check for collisions
  98168. var contact = this.world.contacts;
  98169. while (contact !== null) {
  98170. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  98171. contact = contact.next;
  98172. continue;
  98173. }
  98174. //is this body colliding with any other? get the impostor
  98175. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  98176. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  98177. if (!mainImpostor || !collidingImpostor) {
  98178. contact = contact.next;
  98179. continue;
  98180. }
  98181. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  98182. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  98183. contact = contact.next;
  98184. }
  98185. };
  98186. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  98187. var mass = impostor.physicsBody.mass;
  98188. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  98189. };
  98190. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  98191. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  98192. this.applyImpulse(impostor, force, contactPoint);
  98193. };
  98194. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  98195. var _this = this;
  98196. //parent-child relationship. Does this impostor has a parent impostor?
  98197. if (impostor.parent) {
  98198. if (impostor.physicsBody) {
  98199. this.removePhysicsBody(impostor);
  98200. //TODO is that needed?
  98201. impostor.forceUpdate();
  98202. }
  98203. return;
  98204. }
  98205. if (impostor.isBodyInitRequired()) {
  98206. var bodyConfig = {
  98207. name: impostor.uniqueId,
  98208. //Oimo must have mass, also for static objects.
  98209. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  98210. size: [],
  98211. type: [],
  98212. pos: [],
  98213. posShape: [],
  98214. rot: [],
  98215. rotShape: [],
  98216. move: impostor.getParam("mass") !== 0,
  98217. density: impostor.getParam("mass"),
  98218. friction: impostor.getParam("friction"),
  98219. restitution: impostor.getParam("restitution"),
  98220. //Supporting older versions of Oimo
  98221. world: this.world
  98222. };
  98223. var impostors = [impostor];
  98224. var addToArray = function (parent) {
  98225. if (!parent.getChildMeshes) {
  98226. return;
  98227. }
  98228. parent.getChildMeshes().forEach(function (m) {
  98229. if (m.physicsImpostor) {
  98230. impostors.push(m.physicsImpostor);
  98231. //m.physicsImpostor._init();
  98232. }
  98233. });
  98234. };
  98235. addToArray(impostor.object);
  98236. var checkWithEpsilon_1 = function (value) {
  98237. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  98238. };
  98239. var globalQuaternion_1 = new BABYLON.Quaternion();
  98240. impostors.forEach(function (i) {
  98241. if (!i.object.rotationQuaternion) {
  98242. return;
  98243. }
  98244. //get the correct bounding box
  98245. var oldQuaternion = i.object.rotationQuaternion;
  98246. globalQuaternion_1 = oldQuaternion.clone();
  98247. var rot = oldQuaternion.toEulerAngles();
  98248. var extendSize = i.getObjectExtendSize();
  98249. var radToDeg = 57.295779513082320876;
  98250. if (i === impostor) {
  98251. var center = impostor.getObjectCenter();
  98252. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  98253. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  98254. //Can also use Array.prototype.push.apply
  98255. bodyConfig.pos.push(center.x);
  98256. bodyConfig.pos.push(center.y);
  98257. bodyConfig.pos.push(center.z);
  98258. bodyConfig.posShape.push(0, 0, 0);
  98259. //tmp solution
  98260. bodyConfig.rot.push(0);
  98261. bodyConfig.rot.push(0);
  98262. bodyConfig.rot.push(0);
  98263. bodyConfig.rotShape.push(0, 0, 0);
  98264. }
  98265. else {
  98266. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  98267. bodyConfig.posShape.push(localPosition.x);
  98268. bodyConfig.posShape.push(localPosition.y);
  98269. bodyConfig.posShape.push(localPosition.z);
  98270. bodyConfig.pos.push(0, 0, 0);
  98271. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  98272. bodyConfig.rot.push(0);
  98273. bodyConfig.rot.push(0);
  98274. bodyConfig.rot.push(0);
  98275. bodyConfig.rotShape.push(rot.x * radToDeg);
  98276. bodyConfig.rotShape.push(rot.y * radToDeg);
  98277. bodyConfig.rotShape.push(rot.z * radToDeg);
  98278. }
  98279. // register mesh
  98280. switch (i.type) {
  98281. case BABYLON.PhysicsImpostor.ParticleImpostor:
  98282. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  98283. case BABYLON.PhysicsImpostor.SphereImpostor:
  98284. var radiusX = extendSize.x;
  98285. var radiusY = extendSize.y;
  98286. var radiusZ = extendSize.z;
  98287. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  98288. bodyConfig.type.push('sphere');
  98289. //due to the way oimo works with compounds, add 3 times
  98290. bodyConfig.size.push(size);
  98291. bodyConfig.size.push(size);
  98292. bodyConfig.size.push(size);
  98293. break;
  98294. case BABYLON.PhysicsImpostor.CylinderImpostor:
  98295. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  98296. var sizeY = checkWithEpsilon_1(extendSize.y);
  98297. bodyConfig.type.push('cylinder');
  98298. bodyConfig.size.push(sizeX);
  98299. bodyConfig.size.push(sizeY);
  98300. //due to the way oimo works with compounds, add one more value.
  98301. bodyConfig.size.push(sizeY);
  98302. break;
  98303. case BABYLON.PhysicsImpostor.PlaneImpostor:
  98304. case BABYLON.PhysicsImpostor.BoxImpostor:
  98305. default:
  98306. var sizeX = checkWithEpsilon_1(extendSize.x);
  98307. var sizeY = checkWithEpsilon_1(extendSize.y);
  98308. var sizeZ = checkWithEpsilon_1(extendSize.z);
  98309. bodyConfig.type.push('box');
  98310. //if (i === impostor) {
  98311. bodyConfig.size.push(sizeX);
  98312. bodyConfig.size.push(sizeY);
  98313. bodyConfig.size.push(sizeZ);
  98314. //} else {
  98315. // bodyConfig.size.push(0,0,0);
  98316. //}
  98317. break;
  98318. }
  98319. //actually not needed, but hey...
  98320. i.object.rotationQuaternion = oldQuaternion;
  98321. });
  98322. impostor.physicsBody = this.world.add(bodyConfig);
  98323. // set the quaternion, ignoring the previously defined (euler) rotation
  98324. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  98325. // update with delta 0, so the body will reveive the new rotation.
  98326. impostor.physicsBody.updatePosition(0);
  98327. }
  98328. else {
  98329. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  98330. }
  98331. impostor.setDeltaPosition(this._tmpPositionVector);
  98332. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  98333. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  98334. };
  98335. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  98336. //impostor.physicsBody.dispose();
  98337. //Same as : (older oimo versions)
  98338. this.world.removeRigidBody(impostor.physicsBody);
  98339. };
  98340. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  98341. var mainBody = impostorJoint.mainImpostor.physicsBody;
  98342. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  98343. if (!mainBody || !connectedBody) {
  98344. return;
  98345. }
  98346. var jointData = impostorJoint.joint.jointData;
  98347. var options = jointData.nativeParams || {};
  98348. var type;
  98349. var nativeJointData = {
  98350. body1: mainBody,
  98351. body2: connectedBody,
  98352. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  98353. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  98354. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  98355. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  98356. min: options.min,
  98357. max: options.max,
  98358. collision: options.collision || jointData.collision,
  98359. spring: options.spring,
  98360. //supporting older version of Oimo
  98361. world: this.world
  98362. };
  98363. switch (impostorJoint.joint.type) {
  98364. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  98365. type = "jointBall";
  98366. break;
  98367. case BABYLON.PhysicsJoint.SpringJoint:
  98368. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  98369. var springData = jointData;
  98370. nativeJointData.min = springData.length || nativeJointData.min;
  98371. //Max should also be set, just make sure it is at least min
  98372. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  98373. case BABYLON.PhysicsJoint.DistanceJoint:
  98374. type = "jointDistance";
  98375. nativeJointData.max = jointData.maxDistance;
  98376. break;
  98377. case BABYLON.PhysicsJoint.PrismaticJoint:
  98378. type = "jointPrisme";
  98379. break;
  98380. case BABYLON.PhysicsJoint.SliderJoint:
  98381. type = "jointSlide";
  98382. break;
  98383. case BABYLON.PhysicsJoint.WheelJoint:
  98384. type = "jointWheel";
  98385. break;
  98386. case BABYLON.PhysicsJoint.HingeJoint:
  98387. default:
  98388. type = "jointHinge";
  98389. break;
  98390. }
  98391. nativeJointData.type = type;
  98392. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  98393. };
  98394. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  98395. //Bug in Oimo prevents us from disposing a joint in the playground
  98396. //joint.joint.physicsJoint.dispose();
  98397. //So we will bruteforce it!
  98398. try {
  98399. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  98400. }
  98401. catch (e) {
  98402. BABYLON.Tools.Warn(e);
  98403. }
  98404. };
  98405. OimoJSPlugin.prototype.isSupported = function () {
  98406. return this.BJSOIMO !== undefined;
  98407. };
  98408. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  98409. if (!impostor.physicsBody.sleeping) {
  98410. //TODO check that
  98411. /*if (impostor.physicsBody.shapes.next) {
  98412. var parentShape = this._getLastShape(impostor.physicsBody);
  98413. impostor.object.position.copyFrom(parentShape.position);
  98414. console.log(parentShape.position);
  98415. } else {*/
  98416. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  98417. //}
  98418. if (impostor.object.rotationQuaternion) {
  98419. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  98420. }
  98421. }
  98422. };
  98423. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  98424. var body = impostor.physicsBody;
  98425. body.position.copy(newPosition);
  98426. body.orientation.copy(newRotation);
  98427. body.syncShapes();
  98428. body.awake();
  98429. };
  98430. /*private _getLastShape(body: any): any {
  98431. var lastShape = body.shapes;
  98432. while (lastShape.next) {
  98433. lastShape = lastShape.next;
  98434. }
  98435. return lastShape;
  98436. }*/
  98437. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  98438. impostor.physicsBody.linearVelocity.copy(velocity);
  98439. };
  98440. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  98441. impostor.physicsBody.angularVelocity.copy(velocity);
  98442. };
  98443. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  98444. var v = impostor.physicsBody.linearVelocity;
  98445. if (!v) {
  98446. return null;
  98447. }
  98448. return new BABYLON.Vector3(v.x, v.y, v.z);
  98449. };
  98450. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  98451. var v = impostor.physicsBody.angularVelocity;
  98452. if (!v) {
  98453. return null;
  98454. }
  98455. return new BABYLON.Vector3(v.x, v.y, v.z);
  98456. };
  98457. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  98458. var staticBody = mass === 0;
  98459. //this will actually set the body's density and not its mass.
  98460. //But this is how oimo treats the mass variable.
  98461. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  98462. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  98463. };
  98464. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  98465. return impostor.physicsBody.shapes.density;
  98466. };
  98467. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  98468. return impostor.physicsBody.shapes.friction;
  98469. };
  98470. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  98471. impostor.physicsBody.shapes.friction = friction;
  98472. };
  98473. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  98474. return impostor.physicsBody.shapes.restitution;
  98475. };
  98476. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  98477. impostor.physicsBody.shapes.restitution = restitution;
  98478. };
  98479. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  98480. impostor.physicsBody.sleep();
  98481. };
  98482. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  98483. impostor.physicsBody.awake();
  98484. };
  98485. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  98486. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  98487. if (minDistance !== void 0) {
  98488. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  98489. }
  98490. };
  98491. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  98492. //TODO separate rotational and transational motors.
  98493. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  98494. if (motor) {
  98495. motor.setMotor(speed, maxForce);
  98496. }
  98497. };
  98498. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  98499. //TODO separate rotational and transational motors.
  98500. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  98501. if (motor) {
  98502. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  98503. }
  98504. };
  98505. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  98506. var body = impostor.physicsBody;
  98507. mesh.position.x = body.position.x;
  98508. mesh.position.y = body.position.y;
  98509. mesh.position.z = body.position.z;
  98510. if (mesh.rotationQuaternion) {
  98511. mesh.rotationQuaternion.x = body.orientation.x;
  98512. mesh.rotationQuaternion.y = body.orientation.y;
  98513. mesh.rotationQuaternion.z = body.orientation.z;
  98514. mesh.rotationQuaternion.w = body.orientation.s;
  98515. }
  98516. };
  98517. OimoJSPlugin.prototype.getRadius = function (impostor) {
  98518. return impostor.physicsBody.shapes.radius;
  98519. };
  98520. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  98521. var shape = impostor.physicsBody.shapes;
  98522. result.x = shape.halfWidth * 2;
  98523. result.y = shape.halfHeight * 2;
  98524. result.z = shape.halfDepth * 2;
  98525. };
  98526. OimoJSPlugin.prototype.dispose = function () {
  98527. this.world.clear();
  98528. };
  98529. return OimoJSPlugin;
  98530. }());
  98531. BABYLON.OimoJSPlugin = OimoJSPlugin;
  98532. })(BABYLON || (BABYLON = {}));
  98533. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  98534. var BABYLON;
  98535. (function (BABYLON) {
  98536. /**
  98537. * Gets the current physics engine
  98538. * @returns a IPhysicsEngine or null if none attached
  98539. */
  98540. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  98541. return this._physicsEngine;
  98542. };
  98543. /**
  98544. * Enables physics to the current scene
  98545. * @param gravity defines the scene's gravity for the physics engine
  98546. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  98547. * @return a boolean indicating if the physics engine was initialized
  98548. */
  98549. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  98550. if (gravity === void 0) { gravity = null; }
  98551. if (this._physicsEngine) {
  98552. return true;
  98553. }
  98554. // Register the component to the scene
  98555. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  98556. if (!component) {
  98557. component = new PhysicsEngineSceneComponent(this);
  98558. this._addComponent(component);
  98559. }
  98560. try {
  98561. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  98562. return true;
  98563. }
  98564. catch (e) {
  98565. BABYLON.Tools.Error(e.message);
  98566. return false;
  98567. }
  98568. };
  98569. /**
  98570. * Disables and disposes the physics engine associated with the scene
  98571. */
  98572. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  98573. if (!this._physicsEngine) {
  98574. return;
  98575. }
  98576. this._physicsEngine.dispose();
  98577. this._physicsEngine = null;
  98578. };
  98579. /**
  98580. * Gets a boolean indicating if there is an active physics engine
  98581. * @returns a boolean indicating if there is an active physics engine
  98582. */
  98583. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  98584. return this._physicsEngine !== undefined;
  98585. };
  98586. /**
  98587. * Deletes a physics compound impostor
  98588. * @param compound defines the compound to delete
  98589. */
  98590. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  98591. var mesh = compound.parts[0].mesh;
  98592. if (mesh.physicsImpostor) {
  98593. mesh.physicsImpostor.dispose( /*true*/);
  98594. mesh.physicsImpostor = null;
  98595. }
  98596. };
  98597. /** @hidden */
  98598. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  98599. if (this._physicsEngine) {
  98600. this.onBeforePhysicsObservable.notifyObservers(this);
  98601. this._physicsEngine._step(step / 1000);
  98602. this.onAfterPhysicsObservable.notifyObservers(this);
  98603. }
  98604. };
  98605. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  98606. get: function () {
  98607. return this._physicsImpostor;
  98608. },
  98609. set: function (value) {
  98610. var _this = this;
  98611. if (this._physicsImpostor === value) {
  98612. return;
  98613. }
  98614. if (this._disposePhysicsObserver) {
  98615. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  98616. }
  98617. this._physicsImpostor = value;
  98618. if (value) {
  98619. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  98620. // Physics
  98621. if (_this.physicsImpostor) {
  98622. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  98623. _this.physicsImpostor = null;
  98624. }
  98625. });
  98626. }
  98627. },
  98628. enumerable: true,
  98629. configurable: true
  98630. });
  98631. /**
  98632. * Gets the current physics impostor
  98633. * @see http://doc.babylonjs.com/features/physics_engine
  98634. * @returns a physics impostor or null
  98635. */
  98636. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  98637. return this.physicsImpostor;
  98638. };
  98639. /**
  98640. * Apply a physic impulse to the mesh
  98641. * @param force defines the force to apply
  98642. * @param contactPoint defines where to apply the force
  98643. * @returns the current mesh
  98644. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  98645. */
  98646. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  98647. if (!this.physicsImpostor) {
  98648. return this;
  98649. }
  98650. this.physicsImpostor.applyImpulse(force, contactPoint);
  98651. return this;
  98652. };
  98653. /**
  98654. * Creates a physic joint between two meshes
  98655. * @param otherMesh defines the other mesh to use
  98656. * @param pivot1 defines the pivot to use on this mesh
  98657. * @param pivot2 defines the pivot to use on the other mesh
  98658. * @param options defines additional options (can be plugin dependent)
  98659. * @returns the current mesh
  98660. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  98661. */
  98662. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  98663. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  98664. return this;
  98665. }
  98666. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  98667. mainPivot: pivot1,
  98668. connectedPivot: pivot2,
  98669. nativeParams: options
  98670. });
  98671. return this;
  98672. };
  98673. /**
  98674. * Defines the physics engine scene component responsible to manage a physics engine
  98675. */
  98676. var PhysicsEngineSceneComponent = /** @class */ (function () {
  98677. /**
  98678. * Creates a new instance of the component for the given scene
  98679. * @param scene Defines the scene to register the component in
  98680. */
  98681. function PhysicsEngineSceneComponent(scene) {
  98682. var _this = this;
  98683. /**
  98684. * The component name helpful to identify the component in the list of scene components.
  98685. */
  98686. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  98687. this.scene = scene;
  98688. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  98689. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  98690. // Replace the function used to get the deterministic frame time
  98691. this.scene.getDeterministicFrameTime = function () {
  98692. if (_this.scene._physicsEngine) {
  98693. return _this.scene._physicsEngine.getTimeStep() * 1000;
  98694. }
  98695. return 1000.0 / 60.0;
  98696. };
  98697. }
  98698. /**
  98699. * Registers the component in a given scene
  98700. */
  98701. PhysicsEngineSceneComponent.prototype.register = function () {
  98702. };
  98703. /**
  98704. * Rebuilds the elements related to this component in case of
  98705. * context lost for instance.
  98706. */
  98707. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  98708. // Nothing to do for this component
  98709. };
  98710. /**
  98711. * Disposes the component and the associated ressources
  98712. */
  98713. PhysicsEngineSceneComponent.prototype.dispose = function () {
  98714. this.scene.onBeforePhysicsObservable.clear();
  98715. this.scene.onAfterPhysicsObservable.clear();
  98716. if (this.scene._physicsEngine) {
  98717. this.scene.disablePhysicsEngine();
  98718. }
  98719. };
  98720. return PhysicsEngineSceneComponent;
  98721. }());
  98722. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  98723. })(BABYLON || (BABYLON = {}));
  98724. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  98725. var BABYLON;
  98726. (function (BABYLON) {
  98727. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  98728. // All values and structures referenced from:
  98729. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  98730. var DDS_MAGIC = 0x20534444;
  98731. var
  98732. //DDSD_CAPS = 0x1,
  98733. //DDSD_HEIGHT = 0x2,
  98734. //DDSD_WIDTH = 0x4,
  98735. //DDSD_PITCH = 0x8,
  98736. //DDSD_PIXELFORMAT = 0x1000,
  98737. DDSD_MIPMAPCOUNT = 0x20000;
  98738. //DDSD_LINEARSIZE = 0x80000,
  98739. //DDSD_DEPTH = 0x800000;
  98740. // var DDSCAPS_COMPLEX = 0x8,
  98741. // DDSCAPS_MIPMAP = 0x400000,
  98742. // DDSCAPS_TEXTURE = 0x1000;
  98743. var DDSCAPS2_CUBEMAP = 0x200;
  98744. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  98745. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  98746. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  98747. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  98748. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  98749. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  98750. // DDSCAPS2_VOLUME = 0x200000;
  98751. var
  98752. //DDPF_ALPHAPIXELS = 0x1,
  98753. //DDPF_ALPHA = 0x2,
  98754. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  98755. //DDPF_YUV = 0x200,
  98756. DDPF_LUMINANCE = 0x20000;
  98757. function FourCCToInt32(value) {
  98758. return value.charCodeAt(0) +
  98759. (value.charCodeAt(1) << 8) +
  98760. (value.charCodeAt(2) << 16) +
  98761. (value.charCodeAt(3) << 24);
  98762. }
  98763. function Int32ToFourCC(value) {
  98764. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  98765. }
  98766. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  98767. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  98768. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  98769. var FOURCC_DX10 = FourCCToInt32("DX10");
  98770. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  98771. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  98772. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  98773. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  98774. var headerLengthInt = 31; // The header length in 32 bit ints
  98775. // Offsets into the header array
  98776. var off_magic = 0;
  98777. var off_size = 1;
  98778. var off_flags = 2;
  98779. var off_height = 3;
  98780. var off_width = 4;
  98781. var off_mipmapCount = 7;
  98782. var off_pfFlags = 20;
  98783. var off_pfFourCC = 21;
  98784. var off_RGBbpp = 22;
  98785. var off_RMask = 23;
  98786. var off_GMask = 24;
  98787. var off_BMask = 25;
  98788. var off_AMask = 26;
  98789. // var off_caps1 = 27;
  98790. var off_caps2 = 28;
  98791. // var off_caps3 = 29;
  98792. // var off_caps4 = 30;
  98793. var off_dxgiFormat = 32;
  98794. /**
  98795. * Class used to provide DDS decompression tools
  98796. */
  98797. var DDSTools = /** @class */ (function () {
  98798. function DDSTools() {
  98799. }
  98800. /**
  98801. * Gets DDS information from an array buffer
  98802. * @param arrayBuffer defines the array buffer to read data from
  98803. * @returns the DDS information
  98804. */
  98805. DDSTools.GetDDSInfo = function (arrayBuffer) {
  98806. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  98807. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  98808. var mipmapCount = 1;
  98809. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  98810. mipmapCount = Math.max(1, header[off_mipmapCount]);
  98811. }
  98812. var fourCC = header[off_pfFourCC];
  98813. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  98814. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98815. switch (fourCC) {
  98816. case FOURCC_D3DFMT_R16G16B16A16F:
  98817. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98818. break;
  98819. case FOURCC_D3DFMT_R32G32B32A32F:
  98820. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98821. break;
  98822. case FOURCC_DX10:
  98823. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  98824. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98825. break;
  98826. }
  98827. }
  98828. return {
  98829. width: header[off_width],
  98830. height: header[off_height],
  98831. mipmapCount: mipmapCount,
  98832. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  98833. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  98834. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  98835. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  98836. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  98837. dxgiFormat: dxgiFormat,
  98838. textureType: textureType
  98839. };
  98840. };
  98841. DDSTools._ToHalfFloat = function (value) {
  98842. if (!DDSTools._FloatView) {
  98843. DDSTools._FloatView = new Float32Array(1);
  98844. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  98845. }
  98846. DDSTools._FloatView[0] = value;
  98847. var x = DDSTools._Int32View[0];
  98848. var bits = (x >> 16) & 0x8000; /* Get the sign */
  98849. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  98850. var e = (x >> 23) & 0xff; /* Using int is faster here */
  98851. /* If zero, or denormal, or exponent underflows too much for a denormal
  98852. * half, return signed zero. */
  98853. if (e < 103) {
  98854. return bits;
  98855. }
  98856. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  98857. if (e > 142) {
  98858. bits |= 0x7c00;
  98859. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  98860. * not Inf, so make sure we set one mantissa bit too. */
  98861. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  98862. return bits;
  98863. }
  98864. /* If exponent underflows but not too much, return a denormal */
  98865. if (e < 113) {
  98866. m |= 0x0800;
  98867. /* Extra rounding may overflow and set mantissa to 0 and exponent
  98868. * to 1, which is OK. */
  98869. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  98870. return bits;
  98871. }
  98872. bits |= ((e - 112) << 10) | (m >> 1);
  98873. bits += m & 1;
  98874. return bits;
  98875. };
  98876. DDSTools._FromHalfFloat = function (value) {
  98877. var s = (value & 0x8000) >> 15;
  98878. var e = (value & 0x7C00) >> 10;
  98879. var f = value & 0x03FF;
  98880. if (e === 0) {
  98881. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  98882. }
  98883. else if (e == 0x1F) {
  98884. return f ? NaN : ((s ? -1 : 1) * Infinity);
  98885. }
  98886. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  98887. };
  98888. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98889. var destArray = new Float32Array(dataLength);
  98890. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  98891. var index = 0;
  98892. for (var y = 0; y < height; y++) {
  98893. for (var x = 0; x < width; x++) {
  98894. var srcPos = (x + y * width) * 4;
  98895. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  98896. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  98897. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  98898. if (DDSTools.StoreLODInAlphaChannel) {
  98899. destArray[index + 3] = lod;
  98900. }
  98901. else {
  98902. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  98903. }
  98904. index += 4;
  98905. }
  98906. }
  98907. return destArray;
  98908. };
  98909. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98910. if (DDSTools.StoreLODInAlphaChannel) {
  98911. var destArray = new Uint16Array(dataLength);
  98912. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  98913. var index = 0;
  98914. for (var y = 0; y < height; y++) {
  98915. for (var x = 0; x < width; x++) {
  98916. var srcPos = (x + y * width) * 4;
  98917. destArray[index] = srcData[srcPos];
  98918. destArray[index + 1] = srcData[srcPos + 1];
  98919. destArray[index + 2] = srcData[srcPos + 2];
  98920. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  98921. index += 4;
  98922. }
  98923. }
  98924. return destArray;
  98925. }
  98926. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  98927. };
  98928. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98929. if (DDSTools.StoreLODInAlphaChannel) {
  98930. var destArray = new Float32Array(dataLength);
  98931. var srcData = new Float32Array(arrayBuffer, dataOffset);
  98932. var index = 0;
  98933. for (var y = 0; y < height; y++) {
  98934. for (var x = 0; x < width; x++) {
  98935. var srcPos = (x + y * width) * 4;
  98936. destArray[index] = srcData[srcPos];
  98937. destArray[index + 1] = srcData[srcPos + 1];
  98938. destArray[index + 2] = srcData[srcPos + 2];
  98939. destArray[index + 3] = lod;
  98940. index += 4;
  98941. }
  98942. }
  98943. return destArray;
  98944. }
  98945. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  98946. };
  98947. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98948. var destArray = new Uint8Array(dataLength);
  98949. var srcData = new Float32Array(arrayBuffer, dataOffset);
  98950. var index = 0;
  98951. for (var y = 0; y < height; y++) {
  98952. for (var x = 0; x < width; x++) {
  98953. var srcPos = (x + y * width) * 4;
  98954. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  98955. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  98956. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  98957. if (DDSTools.StoreLODInAlphaChannel) {
  98958. destArray[index + 3] = lod;
  98959. }
  98960. else {
  98961. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  98962. }
  98963. index += 4;
  98964. }
  98965. }
  98966. return destArray;
  98967. };
  98968. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98969. var destArray = new Uint8Array(dataLength);
  98970. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  98971. var index = 0;
  98972. for (var y = 0; y < height; y++) {
  98973. for (var x = 0; x < width; x++) {
  98974. var srcPos = (x + y * width) * 4;
  98975. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  98976. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  98977. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  98978. if (DDSTools.StoreLODInAlphaChannel) {
  98979. destArray[index + 3] = lod;
  98980. }
  98981. else {
  98982. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  98983. }
  98984. index += 4;
  98985. }
  98986. }
  98987. return destArray;
  98988. };
  98989. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  98990. var byteArray = new Uint8Array(dataLength);
  98991. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  98992. var index = 0;
  98993. for (var y = 0; y < height; y++) {
  98994. for (var x = 0; x < width; x++) {
  98995. var srcPos = (x + y * width) * 4;
  98996. byteArray[index] = srcData[srcPos + rOffset];
  98997. byteArray[index + 1] = srcData[srcPos + gOffset];
  98998. byteArray[index + 2] = srcData[srcPos + bOffset];
  98999. byteArray[index + 3] = srcData[srcPos + aOffset];
  99000. index += 4;
  99001. }
  99002. }
  99003. return byteArray;
  99004. };
  99005. DDSTools._ExtractLongWordOrder = function (value) {
  99006. if (value === 0 || value === 255 || value === -16777216) {
  99007. return 0;
  99008. }
  99009. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  99010. };
  99011. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  99012. var byteArray = new Uint8Array(dataLength);
  99013. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99014. var index = 0;
  99015. for (var y = 0; y < height; y++) {
  99016. for (var x = 0; x < width; x++) {
  99017. var srcPos = (x + y * width) * 3;
  99018. byteArray[index] = srcData[srcPos + rOffset];
  99019. byteArray[index + 1] = srcData[srcPos + gOffset];
  99020. byteArray[index + 2] = srcData[srcPos + bOffset];
  99021. index += 3;
  99022. }
  99023. }
  99024. return byteArray;
  99025. };
  99026. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  99027. var byteArray = new Uint8Array(dataLength);
  99028. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99029. var index = 0;
  99030. for (var y = 0; y < height; y++) {
  99031. for (var x = 0; x < width; x++) {
  99032. var srcPos = (x + y * width);
  99033. byteArray[index] = srcData[srcPos];
  99034. index++;
  99035. }
  99036. }
  99037. return byteArray;
  99038. };
  99039. /**
  99040. * Uploads DDS Levels to a Babylon Texture
  99041. * @hidden
  99042. */
  99043. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  99044. if (lodIndex === void 0) { lodIndex = -1; }
  99045. var sphericalPolynomialFaces = null;
  99046. if (info.sphericalPolynomial) {
  99047. sphericalPolynomialFaces = new Array();
  99048. }
  99049. var ext = engine.getCaps().s3tc;
  99050. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  99051. var fourCC, width, height, dataLength = 0, dataOffset;
  99052. var byteArray, mipmapCount, mip;
  99053. var internalCompressedFormat = 0;
  99054. var blockBytes = 1;
  99055. if (header[off_magic] !== DDS_MAGIC) {
  99056. BABYLON.Tools.Error("Invalid magic number in DDS header");
  99057. return;
  99058. }
  99059. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  99060. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  99061. return;
  99062. }
  99063. if (info.isCompressed && !ext) {
  99064. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  99065. return;
  99066. }
  99067. var bpp = header[off_RGBbpp];
  99068. dataOffset = header[off_size] + 4;
  99069. var computeFormats = false;
  99070. if (info.isFourCC) {
  99071. fourCC = header[off_pfFourCC];
  99072. switch (fourCC) {
  99073. case FOURCC_DXT1:
  99074. blockBytes = 8;
  99075. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  99076. break;
  99077. case FOURCC_DXT3:
  99078. blockBytes = 16;
  99079. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  99080. break;
  99081. case FOURCC_DXT5:
  99082. blockBytes = 16;
  99083. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  99084. break;
  99085. case FOURCC_D3DFMT_R16G16B16A16F:
  99086. computeFormats = true;
  99087. break;
  99088. case FOURCC_D3DFMT_R32G32B32A32F:
  99089. computeFormats = true;
  99090. break;
  99091. case FOURCC_DX10:
  99092. // There is an additionnal header so dataOffset need to be changed
  99093. dataOffset += 5 * 4; // 5 uints
  99094. var supported = false;
  99095. switch (info.dxgiFormat) {
  99096. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  99097. computeFormats = true;
  99098. supported = true;
  99099. break;
  99100. case DXGI_FORMAT_B8G8R8X8_UNORM:
  99101. info.isRGB = true;
  99102. info.isFourCC = false;
  99103. bpp = 32;
  99104. supported = true;
  99105. break;
  99106. }
  99107. if (supported) {
  99108. break;
  99109. }
  99110. default:
  99111. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  99112. return;
  99113. }
  99114. }
  99115. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  99116. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  99117. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  99118. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  99119. if (computeFormats) {
  99120. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  99121. }
  99122. mipmapCount = 1;
  99123. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  99124. mipmapCount = Math.max(1, header[off_mipmapCount]);
  99125. }
  99126. for (var face = 0; face < faces; face++) {
  99127. width = header[off_width];
  99128. height = header[off_height];
  99129. for (mip = 0; mip < mipmapCount; ++mip) {
  99130. if (lodIndex === -1 || lodIndex === mip) {
  99131. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  99132. var i = (lodIndex === -1) ? mip : 0;
  99133. if (!info.isCompressed && info.isFourCC) {
  99134. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  99135. dataLength = width * height * 4;
  99136. var floatArray = null;
  99137. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  99138. if (bpp === 128) {
  99139. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99140. if (sphericalPolynomialFaces && i == 0) {
  99141. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99142. }
  99143. }
  99144. else if (bpp === 64) {
  99145. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99146. if (sphericalPolynomialFaces && i == 0) {
  99147. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99148. }
  99149. }
  99150. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99151. }
  99152. else {
  99153. if (bpp === 128) {
  99154. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99155. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99156. if (sphericalPolynomialFaces && i == 0) {
  99157. sphericalPolynomialFaces.push(floatArray);
  99158. }
  99159. }
  99160. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  99161. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99162. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99163. if (sphericalPolynomialFaces && i == 0) {
  99164. sphericalPolynomialFaces.push(floatArray);
  99165. }
  99166. }
  99167. else { // 64
  99168. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99169. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99170. if (sphericalPolynomialFaces && i == 0) {
  99171. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99172. }
  99173. }
  99174. }
  99175. if (floatArray) {
  99176. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  99177. }
  99178. }
  99179. else if (info.isRGB) {
  99180. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99181. if (bpp === 24) {
  99182. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  99183. dataLength = width * height * 3;
  99184. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  99185. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99186. }
  99187. else { // 32
  99188. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  99189. dataLength = width * height * 4;
  99190. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  99191. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99192. }
  99193. }
  99194. else if (info.isLuminance) {
  99195. var unpackAlignment = engine._getUnpackAlignement();
  99196. var unpaddedRowSize = width;
  99197. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  99198. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  99199. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  99200. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  99201. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99202. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99203. }
  99204. else {
  99205. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  99206. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  99207. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99208. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  99209. }
  99210. }
  99211. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  99212. width *= 0.5;
  99213. height *= 0.5;
  99214. width = Math.max(1.0, width);
  99215. height = Math.max(1.0, height);
  99216. }
  99217. if (currentFace !== undefined) {
  99218. // Loading a single face
  99219. break;
  99220. }
  99221. }
  99222. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  99223. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  99224. size: header[off_width],
  99225. right: sphericalPolynomialFaces[0],
  99226. left: sphericalPolynomialFaces[1],
  99227. up: sphericalPolynomialFaces[2],
  99228. down: sphericalPolynomialFaces[3],
  99229. front: sphericalPolynomialFaces[4],
  99230. back: sphericalPolynomialFaces[5],
  99231. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  99232. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  99233. gammaSpace: false,
  99234. });
  99235. }
  99236. else {
  99237. info.sphericalPolynomial = undefined;
  99238. }
  99239. };
  99240. /**
  99241. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  99242. */
  99243. DDSTools.StoreLODInAlphaChannel = false;
  99244. return DDSTools;
  99245. }());
  99246. BABYLON.DDSTools = DDSTools;
  99247. })(BABYLON || (BABYLON = {}));
  99248. //# sourceMappingURL=babylon.dds.js.map
  99249. var BABYLON;
  99250. (function (BABYLON) {
  99251. /**
  99252. * Implementation of the DDS Texture Loader.
  99253. */
  99254. var DDSTextureLoader = /** @class */ (function () {
  99255. function DDSTextureLoader() {
  99256. /**
  99257. * Defines wether the loader supports cascade loading the different faces.
  99258. */
  99259. this.supportCascades = true;
  99260. }
  99261. /**
  99262. * This returns if the loader support the current file information.
  99263. * @param extension defines the file extension of the file being loaded
  99264. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99265. * @param fallback defines the fallback internal texture if any
  99266. * @param isBase64 defines whether the texture is encoded as a base64
  99267. * @param isBuffer defines whether the texture data are stored as a buffer
  99268. * @returns true if the loader can load the specified file
  99269. */
  99270. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99271. return extension.indexOf(".dds") === 0;
  99272. };
  99273. /**
  99274. * Transform the url before loading if required.
  99275. * @param rootUrl the url of the texture
  99276. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99277. * @returns the transformed texture
  99278. */
  99279. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99280. return rootUrl;
  99281. };
  99282. /**
  99283. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99284. * @param rootUrl the url of the texture
  99285. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99286. * @returns the fallback texture
  99287. */
  99288. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99289. return null;
  99290. };
  99291. /**
  99292. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99293. * @param data contains the texture data
  99294. * @param texture defines the BabylonJS internal texture
  99295. * @param createPolynomials will be true if polynomials have been requested
  99296. * @param onLoad defines the callback to trigger once the texture is ready
  99297. * @param onError defines the callback to trigger in case of error
  99298. */
  99299. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  99300. var engine = texture.getEngine();
  99301. var info;
  99302. var loadMipmap = false;
  99303. if (Array.isArray(imgs)) {
  99304. for (var index = 0; index < imgs.length; index++) {
  99305. var data_1 = imgs[index];
  99306. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  99307. texture.width = info.width;
  99308. texture.height = info.height;
  99309. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  99310. engine._unpackFlipY(info.isCompressed);
  99311. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  99312. if (!info.isFourCC && info.mipmapCount === 1) {
  99313. engine.generateMipMapsForCubemap(texture);
  99314. }
  99315. }
  99316. }
  99317. else {
  99318. var data = imgs;
  99319. info = BABYLON.DDSTools.GetDDSInfo(data);
  99320. texture.width = info.width;
  99321. texture.height = info.height;
  99322. if (createPolynomials) {
  99323. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  99324. }
  99325. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  99326. engine._unpackFlipY(info.isCompressed);
  99327. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  99328. if (!info.isFourCC && info.mipmapCount === 1) {
  99329. engine.generateMipMapsForCubemap(texture);
  99330. }
  99331. }
  99332. engine._setCubeMapTextureParams(loadMipmap);
  99333. texture.isReady = true;
  99334. if (onLoad) {
  99335. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  99336. }
  99337. };
  99338. /**
  99339. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99340. * @param data contains the texture data
  99341. * @param texture defines the BabylonJS internal texture
  99342. * @param callback defines the method to call once ready to upload
  99343. */
  99344. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  99345. var info = BABYLON.DDSTools.GetDDSInfo(data);
  99346. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  99347. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  99348. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  99349. });
  99350. };
  99351. return DDSTextureLoader;
  99352. }());
  99353. // Register the loader.
  99354. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  99355. })(BABYLON || (BABYLON = {}));
  99356. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  99357. var BABYLON;
  99358. (function (BABYLON) {
  99359. /**
  99360. * Based on jsTGALoader - Javascript loader for TGA file
  99361. * By Vincent Thibault
  99362. * @see http://blog.robrowser.com/javascript-tga-loader.html
  99363. */
  99364. var TGATools = /** @class */ (function () {
  99365. function TGATools() {
  99366. }
  99367. /**
  99368. * Gets the header of a TGA file
  99369. * @param data defines the TGA data
  99370. * @returns the header
  99371. */
  99372. TGATools.GetTGAHeader = function (data) {
  99373. var offset = 0;
  99374. var header = {
  99375. id_length: data[offset++],
  99376. colormap_type: data[offset++],
  99377. image_type: data[offset++],
  99378. colormap_index: data[offset++] | data[offset++] << 8,
  99379. colormap_length: data[offset++] | data[offset++] << 8,
  99380. colormap_size: data[offset++],
  99381. origin: [
  99382. data[offset++] | data[offset++] << 8,
  99383. data[offset++] | data[offset++] << 8
  99384. ],
  99385. width: data[offset++] | data[offset++] << 8,
  99386. height: data[offset++] | data[offset++] << 8,
  99387. pixel_size: data[offset++],
  99388. flags: data[offset++]
  99389. };
  99390. return header;
  99391. };
  99392. /**
  99393. * Uploads TGA content to a Babylon Texture
  99394. * @hidden
  99395. */
  99396. TGATools.UploadContent = function (texture, data) {
  99397. // Not enough data to contain header ?
  99398. if (data.length < 19) {
  99399. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  99400. return;
  99401. }
  99402. // Read Header
  99403. var offset = 18;
  99404. var header = TGATools.GetTGAHeader(data);
  99405. // Assume it's a valid Targa file.
  99406. if (header.id_length + offset > data.length) {
  99407. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  99408. return;
  99409. }
  99410. // Skip not needed data
  99411. offset += header.id_length;
  99412. var use_rle = false;
  99413. var use_pal = false;
  99414. var use_grey = false;
  99415. // Get some informations.
  99416. switch (header.image_type) {
  99417. case TGATools._TYPE_RLE_INDEXED:
  99418. use_rle = true;
  99419. case TGATools._TYPE_INDEXED:
  99420. use_pal = true;
  99421. break;
  99422. case TGATools._TYPE_RLE_RGB:
  99423. use_rle = true;
  99424. case TGATools._TYPE_RGB:
  99425. // use_rgb = true;
  99426. break;
  99427. case TGATools._TYPE_RLE_GREY:
  99428. use_rle = true;
  99429. case TGATools._TYPE_GREY:
  99430. use_grey = true;
  99431. break;
  99432. }
  99433. var pixel_data;
  99434. // var numAlphaBits = header.flags & 0xf;
  99435. var pixel_size = header.pixel_size >> 3;
  99436. var pixel_total = header.width * header.height * pixel_size;
  99437. // Read palettes
  99438. var palettes;
  99439. if (use_pal) {
  99440. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  99441. }
  99442. // Read LRE
  99443. if (use_rle) {
  99444. pixel_data = new Uint8Array(pixel_total);
  99445. var c, count, i;
  99446. var localOffset = 0;
  99447. var pixels = new Uint8Array(pixel_size);
  99448. while (offset < pixel_total && localOffset < pixel_total) {
  99449. c = data[offset++];
  99450. count = (c & 0x7f) + 1;
  99451. // RLE pixels
  99452. if (c & 0x80) {
  99453. // Bind pixel tmp array
  99454. for (i = 0; i < pixel_size; ++i) {
  99455. pixels[i] = data[offset++];
  99456. }
  99457. // Copy pixel array
  99458. for (i = 0; i < count; ++i) {
  99459. pixel_data.set(pixels, localOffset + i * pixel_size);
  99460. }
  99461. localOffset += pixel_size * count;
  99462. }
  99463. // Raw pixels
  99464. else {
  99465. count *= pixel_size;
  99466. for (i = 0; i < count; ++i) {
  99467. pixel_data[localOffset + i] = data[offset++];
  99468. }
  99469. localOffset += count;
  99470. }
  99471. }
  99472. }
  99473. // RAW Pixels
  99474. else {
  99475. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  99476. }
  99477. // Load to texture
  99478. var x_start, y_start, x_step, y_step, y_end, x_end;
  99479. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  99480. default:
  99481. case TGATools._ORIGIN_UL:
  99482. x_start = 0;
  99483. x_step = 1;
  99484. x_end = header.width;
  99485. y_start = 0;
  99486. y_step = 1;
  99487. y_end = header.height;
  99488. break;
  99489. case TGATools._ORIGIN_BL:
  99490. x_start = 0;
  99491. x_step = 1;
  99492. x_end = header.width;
  99493. y_start = header.height - 1;
  99494. y_step = -1;
  99495. y_end = -1;
  99496. break;
  99497. case TGATools._ORIGIN_UR:
  99498. x_start = header.width - 1;
  99499. x_step = -1;
  99500. x_end = -1;
  99501. y_start = 0;
  99502. y_step = 1;
  99503. y_end = header.height;
  99504. break;
  99505. case TGATools._ORIGIN_BR:
  99506. x_start = header.width - 1;
  99507. x_step = -1;
  99508. x_end = -1;
  99509. y_start = header.height - 1;
  99510. y_step = -1;
  99511. y_end = -1;
  99512. break;
  99513. }
  99514. // Load the specify method
  99515. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  99516. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  99517. var engine = texture.getEngine();
  99518. engine._uploadDataToTextureDirectly(texture, imageData);
  99519. };
  99520. /** @hidden */
  99521. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99522. var image = pixel_data, colormap = palettes;
  99523. var width = header.width, height = header.height;
  99524. var color, i = 0, x, y;
  99525. var imageData = new Uint8Array(width * height * 4);
  99526. for (y = y_start; y !== y_end; y += y_step) {
  99527. for (x = x_start; x !== x_end; x += x_step, i++) {
  99528. color = image[i];
  99529. imageData[(x + width * y) * 4 + 3] = 255;
  99530. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  99531. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  99532. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  99533. }
  99534. }
  99535. return imageData;
  99536. };
  99537. /** @hidden */
  99538. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99539. var image = pixel_data;
  99540. var width = header.width, height = header.height;
  99541. var color, i = 0, x, y;
  99542. var imageData = new Uint8Array(width * height * 4);
  99543. for (y = y_start; y !== y_end; y += y_step) {
  99544. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  99545. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  99546. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  99547. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  99548. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  99549. imageData[(x + width * y) * 4 + 0] = r;
  99550. imageData[(x + width * y) * 4 + 1] = g;
  99551. imageData[(x + width * y) * 4 + 2] = b;
  99552. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  99553. }
  99554. }
  99555. return imageData;
  99556. };
  99557. /** @hidden */
  99558. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99559. var image = pixel_data;
  99560. var width = header.width, height = header.height;
  99561. var i = 0, x, y;
  99562. var imageData = new Uint8Array(width * height * 4);
  99563. for (y = y_start; y !== y_end; y += y_step) {
  99564. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  99565. imageData[(x + width * y) * 4 + 3] = 255;
  99566. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99567. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  99568. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  99569. }
  99570. }
  99571. return imageData;
  99572. };
  99573. /** @hidden */
  99574. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99575. var image = pixel_data;
  99576. var width = header.width, height = header.height;
  99577. var 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 += 4) {
  99581. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99582. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  99583. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  99584. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  99585. }
  99586. }
  99587. return imageData;
  99588. };
  99589. /** @hidden */
  99590. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99591. var image = pixel_data;
  99592. var width = header.width, height = header.height;
  99593. var color, i = 0, x, y;
  99594. var imageData = new Uint8Array(width * height * 4);
  99595. for (y = y_start; y !== y_end; y += y_step) {
  99596. for (x = x_start; x !== x_end; x += x_step, i++) {
  99597. color = image[i];
  99598. imageData[(x + width * y) * 4 + 0] = color;
  99599. imageData[(x + width * y) * 4 + 1] = color;
  99600. imageData[(x + width * y) * 4 + 2] = color;
  99601. imageData[(x + width * y) * 4 + 3] = 255;
  99602. }
  99603. }
  99604. return imageData;
  99605. };
  99606. /** @hidden */
  99607. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99608. var image = pixel_data;
  99609. var width = header.width, height = header.height;
  99610. var i = 0, x, y;
  99611. var imageData = new Uint8Array(width * height * 4);
  99612. for (y = y_start; y !== y_end; y += y_step) {
  99613. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  99614. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  99615. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  99616. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99617. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  99618. }
  99619. }
  99620. return imageData;
  99621. };
  99622. //private static _TYPE_NO_DATA = 0;
  99623. TGATools._TYPE_INDEXED = 1;
  99624. TGATools._TYPE_RGB = 2;
  99625. TGATools._TYPE_GREY = 3;
  99626. TGATools._TYPE_RLE_INDEXED = 9;
  99627. TGATools._TYPE_RLE_RGB = 10;
  99628. TGATools._TYPE_RLE_GREY = 11;
  99629. TGATools._ORIGIN_MASK = 0x30;
  99630. TGATools._ORIGIN_SHIFT = 0x04;
  99631. TGATools._ORIGIN_BL = 0x00;
  99632. TGATools._ORIGIN_BR = 0x01;
  99633. TGATools._ORIGIN_UL = 0x02;
  99634. TGATools._ORIGIN_UR = 0x03;
  99635. return TGATools;
  99636. }());
  99637. BABYLON.TGATools = TGATools;
  99638. })(BABYLON || (BABYLON = {}));
  99639. //# sourceMappingURL=babylon.tga.js.map
  99640. var BABYLON;
  99641. (function (BABYLON) {
  99642. /**
  99643. * Implementation of the TGA Texture Loader.
  99644. */
  99645. var TGATextureLoader = /** @class */ (function () {
  99646. function TGATextureLoader() {
  99647. /**
  99648. * Defines wether the loader supports cascade loading the different faces.
  99649. */
  99650. this.supportCascades = false;
  99651. }
  99652. /**
  99653. * This returns if the loader support the current file information.
  99654. * @param extension defines the file extension of the file being loaded
  99655. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99656. * @param fallback defines the fallback internal texture if any
  99657. * @param isBase64 defines whether the texture is encoded as a base64
  99658. * @param isBuffer defines whether the texture data are stored as a buffer
  99659. * @returns true if the loader can load the specified file
  99660. */
  99661. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99662. return extension.indexOf(".tga") === 0;
  99663. };
  99664. /**
  99665. * Transform the url before loading if required.
  99666. * @param rootUrl the url of the texture
  99667. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99668. * @returns the transformed texture
  99669. */
  99670. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99671. return rootUrl;
  99672. };
  99673. /**
  99674. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99675. * @param rootUrl the url of the texture
  99676. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99677. * @returns the fallback texture
  99678. */
  99679. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99680. return null;
  99681. };
  99682. /**
  99683. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99684. * @param data contains the texture data
  99685. * @param texture defines the BabylonJS internal texture
  99686. * @param createPolynomials will be true if polynomials have been requested
  99687. * @param onLoad defines the callback to trigger once the texture is ready
  99688. * @param onError defines the callback to trigger in case of error
  99689. */
  99690. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  99691. throw ".env not supported in Cube.";
  99692. };
  99693. /**
  99694. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99695. * @param data contains the texture data
  99696. * @param texture defines the BabylonJS internal texture
  99697. * @param callback defines the method to call once ready to upload
  99698. */
  99699. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  99700. var uintData = new Uint8Array(data);
  99701. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  99702. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  99703. BABYLON.TGATools.UploadContent(texture, uintData);
  99704. });
  99705. };
  99706. return TGATextureLoader;
  99707. }());
  99708. // Register the loader.
  99709. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  99710. })(BABYLON || (BABYLON = {}));
  99711. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  99712. var BABYLON;
  99713. (function (BABYLON) {
  99714. /**
  99715. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  99716. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  99717. */
  99718. var KhronosTextureContainer = /** @class */ (function () {
  99719. /**
  99720. * Creates a new KhronosTextureContainer
  99721. * @param arrayBuffer contents of the KTX container file
  99722. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  99723. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  99724. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  99725. */
  99726. function KhronosTextureContainer(
  99727. /** contents of the KTX container file */
  99728. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  99729. this.arrayBuffer = arrayBuffer;
  99730. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  99731. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  99732. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  99733. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  99734. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  99735. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  99736. BABYLON.Tools.Error("texture missing KTX identifier");
  99737. return;
  99738. }
  99739. // load the reset of the header in native 32 bit int
  99740. var header = new Int32Array(this.arrayBuffer, 12, 13);
  99741. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  99742. var oppositeEndianess = header[0] === 0x01020304;
  99743. // read all the header elements in order they exist in the file, without modification (sans endainness)
  99744. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  99745. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  99746. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  99747. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  99748. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  99749. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  99750. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  99751. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  99752. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  99753. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  99754. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  99755. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  99756. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  99757. if (this.glType !== 0) {
  99758. BABYLON.Tools.Error("only compressed formats currently supported");
  99759. return;
  99760. }
  99761. else {
  99762. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  99763. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  99764. }
  99765. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  99766. BABYLON.Tools.Error("only 2D textures currently supported");
  99767. return;
  99768. }
  99769. if (this.numberOfArrayElements !== 0) {
  99770. BABYLON.Tools.Error("texture arrays not currently supported");
  99771. return;
  99772. }
  99773. if (this.numberOfFaces !== facesExpected) {
  99774. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  99775. return;
  99776. }
  99777. // we now have a completely validated file, so could use existence of loadType as success
  99778. // would need to make this more elaborate & adjust checks above to support more than one load type
  99779. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  99780. }
  99781. //
  99782. /**
  99783. * Revert the endianness of a value.
  99784. * Not as fast hardware based, but will probably never need to use
  99785. * @param val defines the value to convert
  99786. * @returns the new value
  99787. */
  99788. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  99789. return ((val & 0xFF) << 24)
  99790. | ((val & 0xFF00) << 8)
  99791. | ((val >> 8) & 0xFF00)
  99792. | ((val >> 24) & 0xFF);
  99793. };
  99794. /**
  99795. * Uploads KTX content to a Babylon Texture.
  99796. * It is assumed that the texture has already been created & is currently bound
  99797. * @hidden
  99798. */
  99799. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  99800. switch (this.loadType) {
  99801. case KhronosTextureContainer.COMPRESSED_2D:
  99802. this._upload2DCompressedLevels(texture, loadMipmaps);
  99803. break;
  99804. case KhronosTextureContainer.TEX_2D:
  99805. case KhronosTextureContainer.COMPRESSED_3D:
  99806. case KhronosTextureContainer.TEX_3D:
  99807. }
  99808. };
  99809. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  99810. // initialize width & height for level 1
  99811. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  99812. var width = this.pixelWidth;
  99813. var height = this.pixelHeight;
  99814. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  99815. for (var level = 0; level < mipmapCount; level++) {
  99816. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  99817. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  99818. for (var face = 0; face < this.numberOfFaces; face++) {
  99819. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  99820. var engine = texture.getEngine();
  99821. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  99822. dataOffset += imageSize; // add size of the image for the next face/mipmap
  99823. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  99824. }
  99825. width = Math.max(1.0, width * 0.5);
  99826. height = Math.max(1.0, height * 0.5);
  99827. }
  99828. };
  99829. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  99830. // load types
  99831. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  99832. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  99833. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  99834. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  99835. return KhronosTextureContainer;
  99836. }());
  99837. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  99838. })(BABYLON || (BABYLON = {}));
  99839. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  99840. var BABYLON;
  99841. (function (BABYLON) {
  99842. /**
  99843. * Implementation of the KTX Texture Loader.
  99844. */
  99845. var KTXTextureLoader = /** @class */ (function () {
  99846. function KTXTextureLoader() {
  99847. /**
  99848. * Defines wether the loader supports cascade loading the different faces.
  99849. */
  99850. this.supportCascades = false;
  99851. }
  99852. /**
  99853. * This returns if the loader support the current file information.
  99854. * @param extension defines the file extension of the file being loaded
  99855. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99856. * @param fallback defines the fallback internal texture if any
  99857. * @param isBase64 defines whether the texture is encoded as a base64
  99858. * @param isBuffer defines whether the texture data are stored as a buffer
  99859. * @returns true if the loader can load the specified file
  99860. */
  99861. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99862. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  99863. return true;
  99864. }
  99865. return false;
  99866. };
  99867. /**
  99868. * Transform the url before loading if required.
  99869. * @param rootUrl the url of the texture
  99870. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99871. * @returns the transformed texture
  99872. */
  99873. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99874. var lastDot = rootUrl.lastIndexOf('.');
  99875. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  99876. };
  99877. /**
  99878. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99879. * @param rootUrl the url of the texture
  99880. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99881. * @returns the fallback texture
  99882. */
  99883. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99884. // remove the format appended to the rootUrl in the original createCubeTexture call.
  99885. var exp = new RegExp("" + textureFormatInUse + "$");
  99886. return rootUrl.replace(exp, "");
  99887. };
  99888. /**
  99889. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99890. * @param data contains the texture data
  99891. * @param texture defines the BabylonJS internal texture
  99892. * @param createPolynomials will be true if polynomials have been requested
  99893. * @param onLoad defines the callback to trigger once the texture is ready
  99894. * @param onError defines the callback to trigger in case of error
  99895. */
  99896. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  99897. if (Array.isArray(data)) {
  99898. return;
  99899. }
  99900. var engine = texture.getEngine();
  99901. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  99902. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  99903. engine._unpackFlipY(true);
  99904. ktx.uploadLevels(texture, texture.generateMipMaps);
  99905. texture.width = ktx.pixelWidth;
  99906. texture.height = ktx.pixelHeight;
  99907. engine._setCubeMapTextureParams(loadMipmap);
  99908. texture.isReady = true;
  99909. };
  99910. /**
  99911. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99912. * @param data contains the texture data
  99913. * @param texture defines the BabylonJS internal texture
  99914. * @param callback defines the method to call once ready to upload
  99915. */
  99916. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  99917. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  99918. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  99919. ktx.uploadLevels(texture, texture.generateMipMaps);
  99920. });
  99921. };
  99922. return KTXTextureLoader;
  99923. }());
  99924. // Register the loader.
  99925. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  99926. })(BABYLON || (BABYLON = {}));
  99927. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  99928. var BABYLON;
  99929. (function (BABYLON) {
  99930. /**
  99931. * Sets of helpers addressing the serialization and deserialization of environment texture
  99932. * stored in a BabylonJS env file.
  99933. * Those files are usually stored as .env files.
  99934. */
  99935. var EnvironmentTextureTools = /** @class */ (function () {
  99936. function EnvironmentTextureTools() {
  99937. }
  99938. /**
  99939. * Gets the environment info from an env file.
  99940. * @param data The array buffer containing the .env bytes.
  99941. * @returns the environment file info (the json header) if successfully parsed.
  99942. */
  99943. EnvironmentTextureTools.GetEnvInfo = function (data) {
  99944. var dataView = new DataView(data);
  99945. var pos = 0;
  99946. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  99947. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  99948. BABYLON.Tools.Error('Not a babylon environment map');
  99949. return null;
  99950. }
  99951. }
  99952. // Read json manifest - collect characters up to null terminator
  99953. var manifestString = '';
  99954. var charCode = 0x00;
  99955. while ((charCode = dataView.getUint8(pos++))) {
  99956. manifestString += String.fromCharCode(charCode);
  99957. }
  99958. var manifest = JSON.parse(manifestString);
  99959. if (manifest.specular) {
  99960. // Extend the header with the position of the payload.
  99961. manifest.specular.specularDataPosition = pos;
  99962. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  99963. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  99964. }
  99965. return manifest;
  99966. };
  99967. /**
  99968. * Creates an environment texture from a loaded cube texture.
  99969. * @param texture defines the cube texture to convert in env file
  99970. * @return a promise containing the environment data if succesfull.
  99971. */
  99972. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  99973. var _this = this;
  99974. var internalTexture = texture.getInternalTexture();
  99975. if (!internalTexture) {
  99976. return Promise.reject("The cube texture is invalid.");
  99977. }
  99978. if (!texture._prefiltered) {
  99979. return Promise.reject("The cube texture is invalid (not prefiltered).");
  99980. }
  99981. var engine = internalTexture.getEngine();
  99982. if (engine && engine.premultipliedAlpha) {
  99983. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  99984. }
  99985. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  99986. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  99987. }
  99988. var canvas = engine.getRenderingCanvas();
  99989. if (!canvas) {
  99990. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  99991. }
  99992. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99993. if (!engine.getCaps().textureFloatRender) {
  99994. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99995. if (!engine.getCaps().textureHalfFloatRender) {
  99996. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  99997. }
  99998. }
  99999. var cubeWidth = internalTexture.width;
  100000. var hostingScene = new BABYLON.Scene(engine);
  100001. var specularTextures = {};
  100002. var promises = [];
  100003. // Read and collect all mipmaps data from the cube.
  100004. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  100005. mipmapsCount = Math.round(mipmapsCount);
  100006. var _loop_1 = function (i) {
  100007. var faceWidth = Math.pow(2, mipmapsCount - i);
  100008. var _loop_2 = function (face) {
  100009. var data = texture.readPixels(face, i);
  100010. // Creates a temp texture with the face data.
  100011. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  100012. // And rgbdEncode them.
  100013. var promise = new Promise(function (resolve, reject) {
  100014. 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);
  100015. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  100016. rgbdPostProcess.onApply = function (effect) {
  100017. effect._bindTexture("textureSampler", tempTexture);
  100018. };
  100019. // As the process needs to happen on the main canvas, keep track of the current size
  100020. var currentW = engine.getRenderWidth();
  100021. var currentH = engine.getRenderHeight();
  100022. // Set the desired size for the texture
  100023. engine.setSize(faceWidth, faceWidth);
  100024. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  100025. // Reading datas from WebGL
  100026. BABYLON.Tools.ToBlob(canvas, function (blob) {
  100027. var fileReader = new FileReader();
  100028. fileReader.onload = function (event) {
  100029. var arrayBuffer = event.target.result;
  100030. specularTextures[i * 6 + face] = arrayBuffer;
  100031. resolve();
  100032. };
  100033. fileReader.readAsArrayBuffer(blob);
  100034. });
  100035. // Reapply the previous canvas size
  100036. engine.setSize(currentW, currentH);
  100037. });
  100038. });
  100039. promises.push(promise);
  100040. };
  100041. // All faces of the cube.
  100042. for (var face = 0; face < 6; face++) {
  100043. _loop_2(face);
  100044. }
  100045. };
  100046. for (var i = 0; i <= mipmapsCount; i++) {
  100047. _loop_1(i);
  100048. }
  100049. // Once all the textures haves been collected as RGBD stored in PNGs
  100050. return Promise.all(promises).then(function () {
  100051. // We can delete the hosting scene keeping track of all the creation objects
  100052. hostingScene.dispose();
  100053. // Creates the json header for the env texture
  100054. var info = {
  100055. version: 1,
  100056. width: cubeWidth,
  100057. irradiance: _this._CreateEnvTextureIrradiance(texture),
  100058. specular: {
  100059. mipmaps: [],
  100060. lodGenerationScale: texture.lodGenerationScale
  100061. }
  100062. };
  100063. // Sets the specular image data information
  100064. var position = 0;
  100065. for (var i = 0; i <= mipmapsCount; i++) {
  100066. for (var face = 0; face < 6; face++) {
  100067. var byteLength = specularTextures[i * 6 + face].byteLength;
  100068. info.specular.mipmaps.push({
  100069. length: byteLength,
  100070. position: position
  100071. });
  100072. position += byteLength;
  100073. }
  100074. }
  100075. // Encode the JSON as an array buffer
  100076. var infoString = JSON.stringify(info);
  100077. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  100078. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  100079. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  100080. infoView[i] = infoString.charCodeAt(i);
  100081. }
  100082. // Ends up with a null terminator for easier parsing
  100083. infoView[infoString.length] = 0x00;
  100084. // Computes the final required size and creates the storage
  100085. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  100086. var finalBuffer = new ArrayBuffer(totalSize);
  100087. var finalBufferView = new Uint8Array(finalBuffer);
  100088. var dataView = new DataView(finalBuffer);
  100089. // Copy the magic bytes identifying the file in
  100090. var pos = 0;
  100091. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  100092. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  100093. }
  100094. // Add the json info
  100095. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  100096. pos += infoBuffer.byteLength;
  100097. // Finally inserts the texture data
  100098. for (var i = 0; i <= mipmapsCount; i++) {
  100099. for (var face = 0; face < 6; face++) {
  100100. var dataBuffer = specularTextures[i * 6 + face];
  100101. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  100102. pos += dataBuffer.byteLength;
  100103. }
  100104. }
  100105. // Voila
  100106. return finalBuffer;
  100107. });
  100108. };
  100109. /**
  100110. * Creates a JSON representation of the spherical data.
  100111. * @param texture defines the texture containing the polynomials
  100112. * @return the JSON representation of the spherical info
  100113. */
  100114. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  100115. var polynmials = texture.sphericalPolynomial;
  100116. if (polynmials == null) {
  100117. return null;
  100118. }
  100119. return {
  100120. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  100121. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  100122. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  100123. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  100124. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  100125. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  100126. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  100127. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  100128. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  100129. };
  100130. };
  100131. /**
  100132. * Uploads the texture info contained in the env file to the GPU.
  100133. * @param texture defines the internal texture to upload to
  100134. * @param arrayBuffer defines the buffer cotaining the data to load
  100135. * @param info defines the texture info retrieved through the GetEnvInfo method
  100136. * @returns a promise
  100137. */
  100138. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  100139. if (info.version !== 1) {
  100140. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  100141. }
  100142. var specularInfo = info.specular;
  100143. if (!specularInfo) {
  100144. // Nothing else parsed so far
  100145. return Promise.resolve();
  100146. }
  100147. // Double checks the enclosed info
  100148. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  100149. mipmapsCount = Math.round(mipmapsCount) + 1;
  100150. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  100151. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  100152. }
  100153. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  100154. var imageData = new Array(mipmapsCount);
  100155. for (var i = 0; i < mipmapsCount; i++) {
  100156. imageData[i] = new Array(6);
  100157. for (var face = 0; face < 6; face++) {
  100158. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  100159. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  100160. }
  100161. }
  100162. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  100163. };
  100164. /**
  100165. * Uploads the levels of image data to the GPU.
  100166. * @param texture defines the internal texture to upload to
  100167. * @param imageData defines the array buffer views of image data [mipmap][face]
  100168. * @returns a promise
  100169. */
  100170. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  100171. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  100172. throw new Error("Texture size must be a power of two");
  100173. }
  100174. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  100175. // Gets everything ready.
  100176. var engine = texture.getEngine();
  100177. var expandTexture = false;
  100178. var generateNonLODTextures = false;
  100179. var rgbdPostProcess = null;
  100180. var cubeRtt = null;
  100181. var lodTextures = null;
  100182. var caps = engine.getCaps();
  100183. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  100184. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100185. texture.generateMipMaps = true;
  100186. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  100187. // Add extra process if texture lod is not supported
  100188. if (!caps.textureLOD) {
  100189. expandTexture = false;
  100190. generateNonLODTextures = true;
  100191. lodTextures = {};
  100192. }
  100193. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  100194. else if (engine.webGLVersion < 2) {
  100195. expandTexture = false;
  100196. }
  100197. // If half float available we can uncompress the texture
  100198. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  100199. expandTexture = true;
  100200. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100201. }
  100202. // If full float available we can uncompress the texture
  100203. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  100204. expandTexture = true;
  100205. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  100206. }
  100207. // Expand the texture if possible
  100208. if (expandTexture) {
  100209. // Simply run through the decode PP
  100210. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  100211. texture._isRGBD = false;
  100212. texture.invertY = false;
  100213. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  100214. generateDepthBuffer: false,
  100215. generateMipMaps: true,
  100216. generateStencilBuffer: false,
  100217. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  100218. type: texture.type,
  100219. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  100220. });
  100221. }
  100222. else {
  100223. texture._isRGBD = true;
  100224. texture.invertY = true;
  100225. // In case of missing support, applies the same patch than DDS files.
  100226. if (generateNonLODTextures) {
  100227. var mipSlices = 3;
  100228. var scale = texture._lodGenerationScale;
  100229. var offset = texture._lodGenerationOffset;
  100230. for (var i = 0; i < mipSlices; i++) {
  100231. //compute LOD from even spacing in smoothness (matching shader calculation)
  100232. var smoothness = i / (mipSlices - 1);
  100233. var roughness = 1 - smoothness;
  100234. var minLODIndex = offset; // roughness = 0
  100235. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  100236. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  100237. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  100238. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  100239. glTextureFromLod.isCube = true;
  100240. glTextureFromLod.invertY = true;
  100241. glTextureFromLod.generateMipMaps = false;
  100242. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  100243. // Wrap in a base texture for easy binding.
  100244. var lodTexture = new BABYLON.BaseTexture(null);
  100245. lodTexture.isCube = true;
  100246. lodTexture._texture = glTextureFromLod;
  100247. lodTextures[mipmapIndex] = lodTexture;
  100248. switch (i) {
  100249. case 0:
  100250. texture._lodTextureLow = lodTexture;
  100251. break;
  100252. case 1:
  100253. texture._lodTextureMid = lodTexture;
  100254. break;
  100255. case 2:
  100256. texture._lodTextureHigh = lodTexture;
  100257. break;
  100258. }
  100259. }
  100260. }
  100261. }
  100262. var promises = [];
  100263. var _loop_3 = function (i) {
  100264. var _loop_4 = function (face) {
  100265. // Constructs an image element from image data
  100266. var bytes = imageData[i][face];
  100267. var blob = new Blob([bytes], { type: 'image/png' });
  100268. var url = URL.createObjectURL(blob);
  100269. var image = new Image();
  100270. image.src = url;
  100271. // Enqueue promise to upload to the texture.
  100272. var promise = new Promise(function (resolve, reject) {
  100273. image.onload = function () {
  100274. if (expandTexture) {
  100275. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  100276. reject(message);
  100277. }, image);
  100278. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  100279. // Uncompress the data to a RTT
  100280. rgbdPostProcess.onApply = function (effect) {
  100281. effect._bindTexture("textureSampler", tempTexture_1);
  100282. effect.setFloat2("scale", 1, 1);
  100283. };
  100284. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  100285. // Cleanup
  100286. engine.restoreDefaultFramebuffer();
  100287. tempTexture_1.dispose();
  100288. window.URL.revokeObjectURL(url);
  100289. resolve();
  100290. });
  100291. }
  100292. else {
  100293. engine._uploadImageToTexture(texture, image, face, i);
  100294. // Upload the face to the non lod texture support
  100295. if (generateNonLODTextures) {
  100296. var lodTexture = lodTextures[i];
  100297. if (lodTexture) {
  100298. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  100299. }
  100300. }
  100301. resolve();
  100302. }
  100303. };
  100304. image.onerror = function (error) {
  100305. reject(error);
  100306. };
  100307. });
  100308. promises.push(promise);
  100309. };
  100310. // All faces
  100311. for (var face = 0; face < 6; face++) {
  100312. _loop_4(face);
  100313. }
  100314. };
  100315. // All mipmaps up to provided number of images
  100316. for (var i = 0; i < imageData.length; i++) {
  100317. _loop_3(i);
  100318. }
  100319. // Fill remaining mipmaps with black textures.
  100320. if (imageData.length < mipmapsCount) {
  100321. var data = void 0;
  100322. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  100323. var dataLength = size * size * 4;
  100324. switch (texture.type) {
  100325. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  100326. data = new Uint8Array(dataLength);
  100327. break;
  100328. }
  100329. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  100330. data = new Uint16Array(dataLength);
  100331. break;
  100332. }
  100333. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  100334. data = new Float32Array(dataLength);
  100335. break;
  100336. }
  100337. }
  100338. for (var i = imageData.length; i < mipmapsCount; i++) {
  100339. for (var face = 0; face < 6; face++) {
  100340. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  100341. }
  100342. }
  100343. }
  100344. // Once all done, finishes the cleanup and return
  100345. return Promise.all(promises).then(function () {
  100346. // Release temp RTT.
  100347. if (cubeRtt) {
  100348. engine._releaseFramebufferObjects(cubeRtt);
  100349. cubeRtt._swapAndDie(texture);
  100350. }
  100351. // Release temp Post Process.
  100352. if (rgbdPostProcess) {
  100353. rgbdPostProcess.dispose();
  100354. }
  100355. // Flag internal texture as ready in case they are in use.
  100356. if (generateNonLODTextures) {
  100357. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  100358. texture._lodTextureHigh._texture.isReady = true;
  100359. }
  100360. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  100361. texture._lodTextureMid._texture.isReady = true;
  100362. }
  100363. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  100364. texture._lodTextureLow._texture.isReady = true;
  100365. }
  100366. }
  100367. });
  100368. };
  100369. /**
  100370. * Uploads spherical polynomials information to the texture.
  100371. * @param texture defines the texture we are trying to upload the information to
  100372. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  100373. */
  100374. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  100375. if (info.version !== 1) {
  100376. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  100377. }
  100378. var irradianceInfo = info.irradiance;
  100379. if (!irradianceInfo) {
  100380. return;
  100381. }
  100382. var sp = new BABYLON.SphericalPolynomial();
  100383. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  100384. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  100385. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  100386. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  100387. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  100388. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  100389. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  100390. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  100391. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  100392. texture._sphericalPolynomial = sp;
  100393. };
  100394. /**
  100395. * Magic number identifying the env file.
  100396. */
  100397. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  100398. return EnvironmentTextureTools;
  100399. }());
  100400. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  100401. })(BABYLON || (BABYLON = {}));
  100402. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  100403. var BABYLON;
  100404. (function (BABYLON) {
  100405. /**
  100406. * Implementation of the ENV Texture Loader.
  100407. */
  100408. var ENVTextureLoader = /** @class */ (function () {
  100409. function ENVTextureLoader() {
  100410. /**
  100411. * Defines wether the loader supports cascade loading the different faces.
  100412. */
  100413. this.supportCascades = false;
  100414. }
  100415. /**
  100416. * This returns if the loader support the current file information.
  100417. * @param extension defines the file extension of the file being loaded
  100418. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100419. * @param fallback defines the fallback internal texture if any
  100420. * @param isBase64 defines whether the texture is encoded as a base64
  100421. * @param isBuffer defines whether the texture data are stored as a buffer
  100422. * @returns true if the loader can load the specified file
  100423. */
  100424. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  100425. return extension.indexOf(".env") === 0;
  100426. };
  100427. /**
  100428. * Transform the url before loading if required.
  100429. * @param rootUrl the url of the texture
  100430. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100431. * @returns the transformed texture
  100432. */
  100433. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  100434. return rootUrl;
  100435. };
  100436. /**
  100437. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  100438. * @param rootUrl the url of the texture
  100439. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100440. * @returns the fallback texture
  100441. */
  100442. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  100443. return null;
  100444. };
  100445. /**
  100446. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  100447. * @param data contains the texture data
  100448. * @param texture defines the BabylonJS internal texture
  100449. * @param createPolynomials will be true if polynomials have been requested
  100450. * @param onLoad defines the callback to trigger once the texture is ready
  100451. * @param onError defines the callback to trigger in case of error
  100452. */
  100453. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  100454. if (Array.isArray(data)) {
  100455. return;
  100456. }
  100457. data = data;
  100458. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  100459. if (info) {
  100460. texture.width = info.width;
  100461. texture.height = info.width;
  100462. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  100463. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  100464. texture.isReady = true;
  100465. if (onLoad) {
  100466. onLoad();
  100467. }
  100468. });
  100469. }
  100470. else if (onError) {
  100471. onError("Can not parse the environment file", null);
  100472. }
  100473. };
  100474. /**
  100475. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  100476. * @param data contains the texture data
  100477. * @param texture defines the BabylonJS internal texture
  100478. * @param callback defines the method to call once ready to upload
  100479. */
  100480. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  100481. throw ".env not supported in 2d.";
  100482. };
  100483. return ENVTextureLoader;
  100484. }());
  100485. // Register the loader.
  100486. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  100487. })(BABYLON || (BABYLON = {}));
  100488. //# sourceMappingURL=babylon.envTextureLoader.js.map
  100489. var BABYLON;
  100490. (function (BABYLON) {
  100491. /**
  100492. * Renders a layer on top of an existing scene
  100493. */
  100494. var UtilityLayerRenderer = /** @class */ (function () {
  100495. /**
  100496. * Instantiates a UtilityLayerRenderer
  100497. * @param originalScene the original scene that will be rendered on top of
  100498. */
  100499. function UtilityLayerRenderer(
  100500. /** the original scene that will be rendered on top of */
  100501. originalScene) {
  100502. var _this = this;
  100503. this.originalScene = originalScene;
  100504. this._pointerCaptures = {};
  100505. this._lastPointerEvents = {};
  100506. /**
  100507. * If the utility layer should automatically be rendered on top of existing scene
  100508. */
  100509. this.shouldRender = true;
  100510. /**
  100511. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  100512. */
  100513. this.onlyCheckPointerDownEvents = true;
  100514. /**
  100515. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  100516. */
  100517. this.processAllEvents = false;
  100518. /**
  100519. * Observable raised when the pointer move from the utility layer scene to the main scene
  100520. */
  100521. this.onPointerOutObservable = new BABYLON.Observable();
  100522. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  100523. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  100524. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  100525. this.utilityLayerScene._allowPostProcessClearColor = false;
  100526. originalScene.getEngine().scenes.pop();
  100527. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  100528. this.utilityLayerScene.detachControl();
  100529. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  100530. if (!_this.processAllEvents) {
  100531. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  100532. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  100533. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  100534. return;
  100535. }
  100536. }
  100537. var pointerEvent = (prePointerInfo.event);
  100538. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  100539. _this._pointerCaptures[pointerEvent.pointerId] = false;
  100540. return;
  100541. }
  100542. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  100543. if (!prePointerInfo.ray && utilityScenePick) {
  100544. prePointerInfo.ray = utilityScenePick.ray;
  100545. }
  100546. // always fire the prepointer oversvable
  100547. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  100548. // allow every non pointer down event to flow to the utility layer
  100549. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  100550. if (!prePointerInfo.skipOnPointerObservable) {
  100551. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  100552. }
  100553. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  100554. _this._pointerCaptures[pointerEvent.pointerId] = false;
  100555. }
  100556. return;
  100557. }
  100558. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  100559. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  100560. if (utilityScenePick && utilityScenePick.hit) {
  100561. if (!prePointerInfo.skipOnPointerObservable) {
  100562. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  100563. }
  100564. prePointerInfo.skipOnPointerObservable = true;
  100565. }
  100566. }
  100567. else {
  100568. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  100569. var pointerEvent_1 = (prePointerInfo.event);
  100570. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  100571. if (originalScenePick && utilityScenePick) {
  100572. // No pick in utility scene
  100573. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  100574. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  100575. // We touched an utility mesh present in the main scene
  100576. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  100577. prePointerInfo.skipOnPointerObservable = true;
  100578. }
  100579. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100580. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  100581. }
  100582. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  100583. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  100584. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  100585. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  100586. }
  100587. }
  100588. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  100589. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  100590. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  100591. // If a previous utility layer set this, do not unset this
  100592. if (!prePointerInfo.skipOnPointerObservable) {
  100593. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  100594. }
  100595. }
  100596. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  100597. // We have a pick in both scenes but main is closer than utility
  100598. // We touched an utility mesh present in the main scene
  100599. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  100600. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  100601. prePointerInfo.skipOnPointerObservable = true;
  100602. }
  100603. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  100604. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  100605. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  100606. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  100607. }
  100608. }
  100609. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  100610. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  100611. }
  100612. }
  100613. }
  100614. });
  100615. // Render directly on top of existing scene without clearing
  100616. this.utilityLayerScene.autoClear = false;
  100617. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  100618. if (_this.shouldRender) {
  100619. _this.render();
  100620. }
  100621. });
  100622. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  100623. _this.dispose();
  100624. });
  100625. this._updateCamera();
  100626. }
  100627. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  100628. /**
  100629. * 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)
  100630. */
  100631. get: function () {
  100632. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  100633. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  100634. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  100635. UtilityLayerRenderer._DefaultUtilityLayer = null;
  100636. });
  100637. }
  100638. return UtilityLayerRenderer._DefaultUtilityLayer;
  100639. },
  100640. enumerable: true,
  100641. configurable: true
  100642. });
  100643. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  100644. /**
  100645. * 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)
  100646. */
  100647. get: function () {
  100648. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  100649. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  100650. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  100651. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  100652. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  100653. });
  100654. }
  100655. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  100656. },
  100657. enumerable: true,
  100658. configurable: true
  100659. });
  100660. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  100661. if (!prePointerInfo.skipOnPointerObservable) {
  100662. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  100663. this._lastPointerEvents[pointerEvent.pointerId] = true;
  100664. }
  100665. };
  100666. /**
  100667. * Renders the utility layers scene on top of the original scene
  100668. */
  100669. UtilityLayerRenderer.prototype.render = function () {
  100670. this._updateCamera();
  100671. if (this.utilityLayerScene.activeCamera) {
  100672. // Set the camera's scene to utility layers scene
  100673. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  100674. var camera = this.utilityLayerScene.activeCamera;
  100675. camera._scene = this.utilityLayerScene;
  100676. if (camera.leftCamera) {
  100677. camera.leftCamera._scene = this.utilityLayerScene;
  100678. }
  100679. if (camera.rightCamera) {
  100680. camera.rightCamera._scene = this.utilityLayerScene;
  100681. }
  100682. this.utilityLayerScene.render(false);
  100683. // Reset camera's scene back to original
  100684. camera._scene = oldScene;
  100685. if (camera.leftCamera) {
  100686. camera.leftCamera._scene = oldScene;
  100687. }
  100688. if (camera.rightCamera) {
  100689. camera.rightCamera._scene = oldScene;
  100690. }
  100691. }
  100692. };
  100693. /**
  100694. * Disposes of the renderer
  100695. */
  100696. UtilityLayerRenderer.prototype.dispose = function () {
  100697. this.onPointerOutObservable.clear();
  100698. if (this._afterRenderObserver) {
  100699. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  100700. }
  100701. if (this._sceneDisposeObserver) {
  100702. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  100703. }
  100704. if (this._originalPointerObserver) {
  100705. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  100706. }
  100707. this.utilityLayerScene.dispose();
  100708. };
  100709. UtilityLayerRenderer.prototype._updateCamera = function () {
  100710. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  100711. };
  100712. UtilityLayerRenderer._DefaultUtilityLayer = null;
  100713. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  100714. return UtilityLayerRenderer;
  100715. }());
  100716. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  100717. })(BABYLON || (BABYLON = {}));
  100718. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  100719. //# sourceMappingURL=babylon.behavior.js.map
  100720. var BABYLON;
  100721. (function (BABYLON) {
  100722. /**
  100723. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  100724. */
  100725. var PointerDragBehavior = /** @class */ (function () {
  100726. /**
  100727. * Creates a pointer drag behavior that can be attached to a mesh
  100728. * @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)
  100729. */
  100730. function PointerDragBehavior(options) {
  100731. /**
  100732. * 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)
  100733. */
  100734. this.maxDragAngle = 0;
  100735. /**
  100736. * @hidden
  100737. */
  100738. this._useAlternatePickedPointAboveMaxDragAngle = false;
  100739. /**
  100740. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  100741. */
  100742. this.currentDraggingPointerID = -1;
  100743. /**
  100744. * If the behavior is currently in a dragging state
  100745. */
  100746. this.dragging = false;
  100747. /**
  100748. * 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)
  100749. */
  100750. this.dragDeltaRatio = 0.2;
  100751. /**
  100752. * If the drag plane orientation should be updated during the dragging (Default: true)
  100753. */
  100754. this.updateDragPlane = true;
  100755. // Debug mode will display drag planes to help visualize behavior
  100756. this._debugMode = false;
  100757. this._moving = false;
  100758. /**
  100759. * Fires each time the attached mesh is dragged with the pointer
  100760. * * delta between last drag position and current drag position in world space
  100761. * * dragDistance along the drag axis
  100762. * * dragPlaneNormal normal of the current drag plane used during the drag
  100763. * * dragPlanePoint in world space where the drag intersects the drag plane
  100764. */
  100765. this.onDragObservable = new BABYLON.Observable();
  100766. /**
  100767. * Fires each time a drag begins (eg. mouse down on mesh)
  100768. */
  100769. this.onDragStartObservable = new BABYLON.Observable();
  100770. /**
  100771. * Fires each time a drag ends (eg. mouse release after drag)
  100772. */
  100773. this.onDragEndObservable = new BABYLON.Observable();
  100774. /**
  100775. * If the attached mesh should be moved when dragged
  100776. */
  100777. this.moveAttached = true;
  100778. /**
  100779. * If the drag behavior will react to drag events (Default: true)
  100780. */
  100781. this.enabled = true;
  100782. /**
  100783. * If camera controls should be detached during the drag
  100784. */
  100785. this.detachCameraControls = true;
  100786. /**
  100787. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  100788. */
  100789. this.useObjectOrienationForDragging = true;
  100790. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  100791. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  100792. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  100793. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  100794. this._attachedElement = null;
  100795. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  100796. this._lastPointerRay = {};
  100797. this._dragDelta = new BABYLON.Vector3();
  100798. // Variables to avoid instantiation in the below method
  100799. this._pointA = new BABYLON.Vector3(0, 0, 0);
  100800. this._pointB = new BABYLON.Vector3(0, 0, 0);
  100801. this._pointC = new BABYLON.Vector3(0, 0, 0);
  100802. this._lineA = new BABYLON.Vector3(0, 0, 0);
  100803. this._lineB = new BABYLON.Vector3(0, 0, 0);
  100804. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  100805. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  100806. this._options = options ? options : {};
  100807. var optionCount = 0;
  100808. if (this._options.dragAxis) {
  100809. optionCount++;
  100810. }
  100811. if (this._options.dragPlaneNormal) {
  100812. optionCount++;
  100813. }
  100814. if (optionCount > 1) {
  100815. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  100816. }
  100817. }
  100818. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  100819. /**
  100820. * The name of the behavior
  100821. */
  100822. get: function () {
  100823. return "PointerDrag";
  100824. },
  100825. enumerable: true,
  100826. configurable: true
  100827. });
  100828. /**
  100829. * Initializes the behavior
  100830. */
  100831. PointerDragBehavior.prototype.init = function () { };
  100832. /**
  100833. * Attaches the drag behavior the passed in mesh
  100834. * @param ownerNode The mesh that will be dragged around once attached
  100835. */
  100836. PointerDragBehavior.prototype.attach = function (ownerNode) {
  100837. var _this = this;
  100838. this._scene = ownerNode.getScene();
  100839. this._attachedNode = ownerNode;
  100840. // Initialize drag plane to not interfere with existing scene
  100841. if (!PointerDragBehavior._planeScene) {
  100842. if (this._debugMode) {
  100843. PointerDragBehavior._planeScene = this._scene;
  100844. }
  100845. else {
  100846. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  100847. PointerDragBehavior._planeScene.detachControl();
  100848. this._scene.getEngine().scenes.pop();
  100849. this._scene.onDisposeObservable.addOnce(function () {
  100850. PointerDragBehavior._planeScene.dispose();
  100851. PointerDragBehavior._planeScene = null;
  100852. });
  100853. }
  100854. }
  100855. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  100856. // State of the drag
  100857. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  100858. var pickPredicate = function (m) {
  100859. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  100860. };
  100861. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  100862. if (!_this.enabled) {
  100863. return;
  100864. }
  100865. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  100866. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  100867. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  100868. }
  100869. }
  100870. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  100871. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  100872. _this.releaseDrag();
  100873. }
  100874. }
  100875. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  100876. var pointerId = pointerInfo.event.pointerId;
  100877. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  100878. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  100879. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  100880. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  100881. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  100882. }
  100883. _this.currentDraggingPointerID = pointerId;
  100884. }
  100885. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  100886. if (!_this._lastPointerRay[pointerId]) {
  100887. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  100888. }
  100889. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  100890. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  100891. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  100892. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  100893. _this._moveDrag(pointerInfo.pickInfo.ray);
  100894. }
  100895. }
  100896. }
  100897. });
  100898. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  100899. if (_this._moving && _this.moveAttached) {
  100900. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  100901. // Slowly move mesh to avoid jitter
  100902. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  100903. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  100904. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  100905. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  100906. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  100907. }
  100908. });
  100909. };
  100910. /**
  100911. * Force relase the drag action by code.
  100912. */
  100913. PointerDragBehavior.prototype.releaseDrag = function () {
  100914. this.dragging = false;
  100915. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  100916. this.currentDraggingPointerID = -1;
  100917. this._moving = false;
  100918. // Reattach camera controls
  100919. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  100920. this._scene.activeCamera.attachControl(this._attachedElement, true);
  100921. }
  100922. };
  100923. /**
  100924. * Simulates the start of a pointer drag event on the behavior
  100925. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  100926. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  100927. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  100928. */
  100929. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  100930. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  100931. this._startDrag(pointerId, fromRay, startPickedPoint);
  100932. var lastRay = this._lastPointerRay[pointerId];
  100933. if (pointerId === PointerDragBehavior._AnyMouseID) {
  100934. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  100935. }
  100936. if (lastRay) {
  100937. // if there was a last pointer ray drag the object there
  100938. this._moveDrag(lastRay);
  100939. }
  100940. };
  100941. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  100942. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  100943. return;
  100944. }
  100945. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  100946. // Create start ray from the camera to the object
  100947. if (fromRay) {
  100948. this._startDragRay.direction.copyFrom(fromRay.direction);
  100949. this._startDragRay.origin.copyFrom(fromRay.origin);
  100950. }
  100951. else {
  100952. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  100953. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  100954. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  100955. }
  100956. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  100957. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  100958. if (pickedPoint) {
  100959. this.dragging = true;
  100960. this.currentDraggingPointerID = pointerId;
  100961. this.lastDragPosition.copyFrom(pickedPoint);
  100962. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  100963. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  100964. // Detatch camera controls
  100965. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  100966. if (this._scene.activeCamera.inputs.attachedElement) {
  100967. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  100968. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  100969. }
  100970. else {
  100971. this._attachedElement = null;
  100972. }
  100973. }
  100974. }
  100975. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  100976. };
  100977. PointerDragBehavior.prototype._moveDrag = function (ray) {
  100978. this._moving = true;
  100979. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  100980. if (pickedPoint) {
  100981. if (this.updateDragPlane) {
  100982. this._updateDragPlanePosition(ray, pickedPoint);
  100983. }
  100984. var dragLength = 0;
  100985. // depending on the drag mode option drag accordingly
  100986. if (this._options.dragAxis) {
  100987. // Convert local drag axis to world
  100988. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  100989. // Project delta drag from the drag plane onto the drag axis
  100990. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  100991. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  100992. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  100993. }
  100994. else {
  100995. dragLength = this._dragDelta.length();
  100996. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  100997. }
  100998. this._targetPosition.addInPlace(this._dragDelta);
  100999. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  101000. this.lastDragPosition.copyFrom(pickedPoint);
  101001. }
  101002. };
  101003. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  101004. var _this = this;
  101005. if (!ray) {
  101006. return null;
  101007. }
  101008. // Calculate angle between plane normal and ray
  101009. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  101010. // Correct if ray is casted from oposite side
  101011. if (angle > Math.PI / 2) {
  101012. angle = Math.PI - angle;
  101013. }
  101014. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  101015. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  101016. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  101017. // Invert ray direction along the towards object axis
  101018. this._tmpVector.copyFrom(ray.direction);
  101019. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  101020. this._alternatePickedPoint.normalize();
  101021. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  101022. this._tmpVector.addInPlace(this._alternatePickedPoint);
  101023. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  101024. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  101025. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  101026. this._alternatePickedPoint.addInPlace(this._tmpVector);
  101027. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  101028. return this._alternatePickedPoint;
  101029. }
  101030. else {
  101031. return null;
  101032. }
  101033. }
  101034. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  101035. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  101036. return pickResult.pickedPoint;
  101037. }
  101038. else {
  101039. return null;
  101040. }
  101041. };
  101042. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  101043. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  101044. this._pointA.copyFrom(dragPlanePosition);
  101045. if (this._options.dragAxis) {
  101046. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  101047. // Calculate plane normal in direction of camera but perpendicular to drag axis
  101048. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  101049. ray.origin.subtractToRef(this._pointA, this._pointC);
  101050. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  101051. // Get perpendicular line from direction to camera and drag axis
  101052. this._pointB.subtractToRef(this._pointA, this._lineA);
  101053. this._pointC.subtractToRef(this._pointA, this._lineB);
  101054. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  101055. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  101056. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  101057. this._lookAt.normalize();
  101058. this._dragPlane.position.copyFrom(this._pointA);
  101059. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  101060. this._dragPlane.lookAt(this._lookAt);
  101061. }
  101062. else if (this._options.dragPlaneNormal) {
  101063. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  101064. this._dragPlane.position.copyFrom(this._pointA);
  101065. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  101066. this._dragPlane.lookAt(this._lookAt);
  101067. }
  101068. else {
  101069. this._dragPlane.position.copyFrom(this._pointA);
  101070. this._dragPlane.lookAt(ray.origin);
  101071. }
  101072. this._dragPlane.computeWorldMatrix(true);
  101073. };
  101074. /**
  101075. * Detaches the behavior from the mesh
  101076. */
  101077. PointerDragBehavior.prototype.detach = function () {
  101078. if (this._pointerObserver) {
  101079. this._scene.onPointerObservable.remove(this._pointerObserver);
  101080. }
  101081. if (this._beforeRenderObserver) {
  101082. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  101083. }
  101084. };
  101085. PointerDragBehavior._AnyMouseID = -2;
  101086. return PointerDragBehavior;
  101087. }());
  101088. BABYLON.PointerDragBehavior = PointerDragBehavior;
  101089. })(BABYLON || (BABYLON = {}));
  101090. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  101091. var BABYLON;
  101092. (function (BABYLON) {
  101093. /**
  101094. * A behavior that when attached to a mesh will allow the mesh to be scaled
  101095. */
  101096. var MultiPointerScaleBehavior = /** @class */ (function () {
  101097. /**
  101098. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  101099. */
  101100. function MultiPointerScaleBehavior() {
  101101. this._startDistance = 0;
  101102. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  101103. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  101104. this._sceneRenderObserver = null;
  101105. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  101106. this._dragBehaviorA.moveAttached = false;
  101107. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  101108. this._dragBehaviorB.moveAttached = false;
  101109. }
  101110. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  101111. /**
  101112. * The name of the behavior
  101113. */
  101114. get: function () {
  101115. return "MultiPointerScale";
  101116. },
  101117. enumerable: true,
  101118. configurable: true
  101119. });
  101120. /**
  101121. * Initializes the behavior
  101122. */
  101123. MultiPointerScaleBehavior.prototype.init = function () { };
  101124. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  101125. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  101126. };
  101127. /**
  101128. * Attaches the scale behavior the passed in mesh
  101129. * @param ownerNode The mesh that will be scaled around once attached
  101130. */
  101131. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  101132. var _this = this;
  101133. this._ownerNode = ownerNode;
  101134. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  101135. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  101136. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101137. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  101138. _this._dragBehaviorA.releaseDrag();
  101139. }
  101140. else {
  101141. _this._initialScale.copyFrom(ownerNode.scaling);
  101142. _this._startDistance = _this._getCurrentDistance();
  101143. }
  101144. }
  101145. });
  101146. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  101147. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101148. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  101149. _this._dragBehaviorB.releaseDrag();
  101150. }
  101151. else {
  101152. _this._initialScale.copyFrom(ownerNode.scaling);
  101153. _this._startDistance = _this._getCurrentDistance();
  101154. }
  101155. }
  101156. });
  101157. // Once both drag behaviors are active scale based on the distance between the two pointers
  101158. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  101159. behavior.onDragObservable.add(function () {
  101160. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101161. var ratio = _this._getCurrentDistance() / _this._startDistance;
  101162. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  101163. }
  101164. });
  101165. });
  101166. ownerNode.addBehavior(this._dragBehaviorA);
  101167. ownerNode.addBehavior(this._dragBehaviorB);
  101168. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  101169. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  101170. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101171. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  101172. if (change.length() > 0.01) {
  101173. ownerNode.scaling.addInPlace(change);
  101174. }
  101175. }
  101176. });
  101177. };
  101178. /**
  101179. * Detaches the behavior from the mesh
  101180. */
  101181. MultiPointerScaleBehavior.prototype.detach = function () {
  101182. var _this = this;
  101183. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  101184. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  101185. behavior.onDragStartObservable.clear();
  101186. behavior.onDragObservable.clear();
  101187. _this._ownerNode.removeBehavior(behavior);
  101188. });
  101189. };
  101190. return MultiPointerScaleBehavior;
  101191. }());
  101192. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  101193. })(BABYLON || (BABYLON = {}));
  101194. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  101195. var BABYLON;
  101196. (function (BABYLON) {
  101197. /**
  101198. * 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
  101199. */
  101200. var SixDofDragBehavior = /** @class */ (function () {
  101201. /**
  101202. * 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
  101203. */
  101204. function SixDofDragBehavior() {
  101205. this._sceneRenderObserver = null;
  101206. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  101207. this._moving = false;
  101208. this._startingOrientation = new BABYLON.Quaternion();
  101209. /**
  101210. * 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)
  101211. */
  101212. this.zDragFactor = 3;
  101213. /**
  101214. * If the behavior is currently in a dragging state
  101215. */
  101216. this.dragging = false;
  101217. /**
  101218. * 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)
  101219. */
  101220. this.dragDeltaRatio = 0.2;
  101221. /**
  101222. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  101223. */
  101224. this.currentDraggingPointerID = -1;
  101225. /**
  101226. * If camera controls should be detached during the drag
  101227. */
  101228. this.detachCameraControls = true;
  101229. /**
  101230. * Fires each time a drag starts
  101231. */
  101232. this.onDragStartObservable = new BABYLON.Observable();
  101233. /**
  101234. * Fires each time a drag ends (eg. mouse release after drag)
  101235. */
  101236. this.onDragEndObservable = new BABYLON.Observable();
  101237. }
  101238. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  101239. /**
  101240. * The name of the behavior
  101241. */
  101242. get: function () {
  101243. return "SixDofDrag";
  101244. },
  101245. enumerable: true,
  101246. configurable: true
  101247. });
  101248. /**
  101249. * Initializes the behavior
  101250. */
  101251. SixDofDragBehavior.prototype.init = function () { };
  101252. /**
  101253. * Attaches the scale behavior the passed in mesh
  101254. * @param ownerNode The mesh that will be scaled around once attached
  101255. */
  101256. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  101257. var _this = this;
  101258. this._ownerNode = ownerNode;
  101259. this._scene = this._ownerNode.getScene();
  101260. if (!SixDofDragBehavior._virtualScene) {
  101261. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  101262. SixDofDragBehavior._virtualScene.detachControl();
  101263. this._scene.getEngine().scenes.pop();
  101264. }
  101265. var pickedMesh = null;
  101266. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  101267. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  101268. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  101269. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  101270. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  101271. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  101272. var pickPredicate = function (m) {
  101273. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  101274. };
  101275. var attachedElement = null;
  101276. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  101277. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101278. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  101279. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  101280. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  101281. }
  101282. pickedMesh = _this._ownerNode;
  101283. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  101284. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  101285. // Set position and orientation of the controller
  101286. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  101287. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  101288. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  101289. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101290. pickedMesh.computeWorldMatrix();
  101291. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  101292. if (!pickedMesh.rotationQuaternion) {
  101293. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  101294. }
  101295. var oldParent = pickedMesh.parent;
  101296. pickedMesh.setParent(null);
  101297. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  101298. pickedMesh.setParent(oldParent);
  101299. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  101300. // Update state
  101301. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  101302. _this.dragging = true;
  101303. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  101304. // Detatch camera controls
  101305. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  101306. if (_this._scene.activeCamera.inputs.attachedElement) {
  101307. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  101308. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  101309. }
  101310. else {
  101311. attachedElement = null;
  101312. }
  101313. }
  101314. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  101315. _this.onDragStartObservable.notifyObservers({});
  101316. }
  101317. }
  101318. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  101319. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  101320. _this.dragging = false;
  101321. _this._moving = false;
  101322. _this.currentDraggingPointerID = -1;
  101323. pickedMesh = null;
  101324. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101325. // Reattach camera controls
  101326. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  101327. _this._scene.activeCamera.attachControl(attachedElement, true);
  101328. }
  101329. _this.onDragEndObservable.notifyObservers({});
  101330. }
  101331. }
  101332. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  101333. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  101334. var zDragFactor = _this.zDragFactor;
  101335. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  101336. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  101337. zDragFactor = 0;
  101338. }
  101339. // Calculate controller drag distance in controller space
  101340. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  101341. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  101342. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  101343. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  101344. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  101345. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  101346. if (_this._virtualDragMesh.position.z < 0) {
  101347. _this._virtualDragMesh.position.z = 0;
  101348. }
  101349. // Update the controller position
  101350. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  101351. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  101352. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101353. // Move the virtualObjectsPosition into the picked mesh's space if needed
  101354. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  101355. if (pickedMesh.parent) {
  101356. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  101357. }
  101358. if (!_this._moving) {
  101359. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  101360. }
  101361. _this._moving = true;
  101362. }
  101363. }
  101364. });
  101365. var tmpQuaternion = new BABYLON.Quaternion();
  101366. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  101367. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  101368. if (_this.dragging && _this._moving && pickedMesh) {
  101369. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  101370. // Slowly move mesh to avoid jitter
  101371. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  101372. // Get change in rotation
  101373. tmpQuaternion.copyFrom(_this._startingOrientation);
  101374. tmpQuaternion.x = -tmpQuaternion.x;
  101375. tmpQuaternion.y = -tmpQuaternion.y;
  101376. tmpQuaternion.z = -tmpQuaternion.z;
  101377. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  101378. // Convert change in rotation to only y axis rotation
  101379. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  101380. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  101381. // Slowly move mesh to avoid jitter
  101382. var oldParent = pickedMesh.parent;
  101383. pickedMesh.setParent(null);
  101384. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  101385. pickedMesh.setParent(oldParent);
  101386. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  101387. }
  101388. });
  101389. };
  101390. /**
  101391. * Detaches the behavior from the mesh
  101392. */
  101393. SixDofDragBehavior.prototype.detach = function () {
  101394. if (this._scene) {
  101395. this._scene.onPointerObservable.remove(this._pointerObserver);
  101396. }
  101397. if (this._ownerNode) {
  101398. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  101399. }
  101400. if (this._virtualOriginMesh) {
  101401. this._virtualOriginMesh.dispose();
  101402. }
  101403. if (this._virtualDragMesh) {
  101404. this._virtualDragMesh.dispose();
  101405. }
  101406. this.onDragEndObservable.clear();
  101407. this.onDragStartObservable.clear();
  101408. };
  101409. return SixDofDragBehavior;
  101410. }());
  101411. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  101412. })(BABYLON || (BABYLON = {}));
  101413. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  101414. var BABYLON;
  101415. (function (BABYLON) {
  101416. /**
  101417. * @hidden
  101418. */
  101419. var FaceDirectionInfo = /** @class */ (function () {
  101420. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  101421. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  101422. if (diff === void 0) { diff = 0; }
  101423. if (ignore === void 0) { ignore = false; }
  101424. this.direction = direction;
  101425. this.rotatedDirection = rotatedDirection;
  101426. this.diff = diff;
  101427. this.ignore = ignore;
  101428. }
  101429. return FaceDirectionInfo;
  101430. }());
  101431. /**
  101432. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  101433. */
  101434. var AttachToBoxBehavior = /** @class */ (function () {
  101435. /**
  101436. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  101437. * @param ui The transform node that should be attched to the mesh
  101438. */
  101439. function AttachToBoxBehavior(ui) {
  101440. this.ui = ui;
  101441. /**
  101442. * The name of the behavior
  101443. */
  101444. this.name = "AttachToBoxBehavior";
  101445. /**
  101446. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  101447. */
  101448. this.distanceAwayFromFace = 0.15;
  101449. /**
  101450. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  101451. */
  101452. this.distanceAwayFromBottomOfFace = 0.15;
  101453. 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))];
  101454. this._tmpMatrix = new BABYLON.Matrix();
  101455. this._tmpVector = new BABYLON.Vector3();
  101456. this._zeroVector = BABYLON.Vector3.Zero();
  101457. this._lookAtTmpMatrix = new BABYLON.Matrix();
  101458. /* Does nothing */
  101459. }
  101460. /**
  101461. * Initializes the behavior
  101462. */
  101463. AttachToBoxBehavior.prototype.init = function () {
  101464. /* Does nothing */
  101465. };
  101466. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  101467. var _this = this;
  101468. // Go over each face and calculate the angle between the face's normal and targetDirection
  101469. this._faceVectors.forEach(function (v) {
  101470. if (!_this._target.rotationQuaternion) {
  101471. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  101472. }
  101473. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  101474. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  101475. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  101476. });
  101477. // Return the face information of the one with the normal closeset to target direction
  101478. return this._faceVectors.reduce(function (min, p) {
  101479. if (min.ignore) {
  101480. return p;
  101481. }
  101482. else if (p.ignore) {
  101483. return min;
  101484. }
  101485. else {
  101486. return min.diff < p.diff ? min : p;
  101487. }
  101488. }, this._faceVectors[0]);
  101489. };
  101490. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  101491. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  101492. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  101493. this._lookAtTmpMatrix.invert();
  101494. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  101495. };
  101496. /**
  101497. * Attaches the AttachToBoxBehavior to the passed in mesh
  101498. * @param target The mesh that the specified node will be attached to
  101499. */
  101500. AttachToBoxBehavior.prototype.attach = function (target) {
  101501. var _this = this;
  101502. this._target = target;
  101503. this._scene = this._target.getScene();
  101504. // Every frame, update the app bars position
  101505. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  101506. if (!_this._scene.activeCamera) {
  101507. return;
  101508. }
  101509. // Find the face closest to the cameras position
  101510. var cameraPos = _this._scene.activeCamera.position;
  101511. if (_this._scene.activeCamera.devicePosition) {
  101512. cameraPos = _this._scene.activeCamera.devicePosition;
  101513. }
  101514. var facing = _this._closestFace(cameraPos.subtract(target.position));
  101515. if (_this._scene.activeCamera.leftCamera) {
  101516. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  101517. }
  101518. else {
  101519. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  101520. }
  101521. // Get camera up direction
  101522. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  101523. // Ignore faces to not select a parrelel face for the up vector of the UI
  101524. _this._faceVectors.forEach(function (v) {
  101525. if (facing.direction.x && v.direction.x) {
  101526. v.ignore = true;
  101527. }
  101528. if (facing.direction.y && v.direction.y) {
  101529. v.ignore = true;
  101530. }
  101531. if (facing.direction.z && v.direction.z) {
  101532. v.ignore = true;
  101533. }
  101534. });
  101535. var facingUp = _this._closestFace(_this._tmpVector);
  101536. // Unignore faces
  101537. _this._faceVectors.forEach(function (v) {
  101538. v.ignore = false;
  101539. });
  101540. // Position the app bar on that face
  101541. _this.ui.position.copyFrom(target.position);
  101542. if (facing.direction.x) {
  101543. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101544. _this.ui.position.addInPlace(_this._tmpVector);
  101545. }
  101546. if (facing.direction.y) {
  101547. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101548. _this.ui.position.addInPlace(_this._tmpVector);
  101549. }
  101550. if (facing.direction.z) {
  101551. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101552. _this.ui.position.addInPlace(_this._tmpVector);
  101553. }
  101554. // Rotate to be oriented properly to the camera
  101555. if (!_this.ui.rotationQuaternion) {
  101556. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  101557. }
  101558. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  101559. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  101560. // Place ui the correct distance from the bottom of the mesh
  101561. if (facingUp.direction.x) {
  101562. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  101563. }
  101564. if (facingUp.direction.y) {
  101565. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  101566. }
  101567. if (facingUp.direction.z) {
  101568. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  101569. }
  101570. _this.ui.position.addInPlace(_this._tmpVector);
  101571. });
  101572. };
  101573. /**
  101574. * Detaches the behavior from the mesh
  101575. */
  101576. AttachToBoxBehavior.prototype.detach = function () {
  101577. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  101578. };
  101579. return AttachToBoxBehavior;
  101580. }());
  101581. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  101582. })(BABYLON || (BABYLON = {}));
  101583. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  101584. var BABYLON;
  101585. (function (BABYLON) {
  101586. /**
  101587. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  101588. */
  101589. var FadeInOutBehavior = /** @class */ (function () {
  101590. /**
  101591. * Instatiates the FadeInOutBehavior
  101592. */
  101593. function FadeInOutBehavior() {
  101594. var _this = this;
  101595. /**
  101596. * Time in milliseconds to delay before fading in (Default: 0)
  101597. */
  101598. this.delay = 0;
  101599. /**
  101600. * Time in milliseconds for the mesh to fade in (Default: 300)
  101601. */
  101602. this.fadeInTime = 300;
  101603. this._millisecondsPerFrame = 1000 / 60;
  101604. this._hovered = false;
  101605. this._hoverValue = 0;
  101606. this._ownerNode = null;
  101607. this._update = function () {
  101608. if (_this._ownerNode) {
  101609. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  101610. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  101611. if (_this._ownerNode.visibility > 1) {
  101612. _this._setAllVisibility(_this._ownerNode, 1);
  101613. _this._hoverValue = _this.fadeInTime + _this.delay;
  101614. return;
  101615. }
  101616. else if (_this._ownerNode.visibility < 0) {
  101617. _this._setAllVisibility(_this._ownerNode, 0);
  101618. if (_this._hoverValue < 0) {
  101619. _this._hoverValue = 0;
  101620. return;
  101621. }
  101622. }
  101623. setTimeout(_this._update, _this._millisecondsPerFrame);
  101624. }
  101625. };
  101626. }
  101627. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  101628. /**
  101629. * The name of the behavior
  101630. */
  101631. get: function () {
  101632. return "FadeInOut";
  101633. },
  101634. enumerable: true,
  101635. configurable: true
  101636. });
  101637. /**
  101638. * Initializes the behavior
  101639. */
  101640. FadeInOutBehavior.prototype.init = function () {
  101641. };
  101642. /**
  101643. * Attaches the fade behavior on the passed in mesh
  101644. * @param ownerNode The mesh that will be faded in/out once attached
  101645. */
  101646. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  101647. this._ownerNode = ownerNode;
  101648. this._setAllVisibility(this._ownerNode, 0);
  101649. };
  101650. /**
  101651. * Detaches the behavior from the mesh
  101652. */
  101653. FadeInOutBehavior.prototype.detach = function () {
  101654. this._ownerNode = null;
  101655. };
  101656. /**
  101657. * Triggers the mesh to begin fading in or out
  101658. * @param value if the object should fade in or out (true to fade in)
  101659. */
  101660. FadeInOutBehavior.prototype.fadeIn = function (value) {
  101661. this._hovered = value;
  101662. this._update();
  101663. };
  101664. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  101665. var _this = this;
  101666. mesh.visibility = value;
  101667. mesh.getChildMeshes().forEach(function (c) {
  101668. _this._setAllVisibility(c, value);
  101669. });
  101670. };
  101671. return FadeInOutBehavior;
  101672. }());
  101673. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  101674. })(BABYLON || (BABYLON = {}));
  101675. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  101676. var BABYLON;
  101677. (function (BABYLON) {
  101678. /**
  101679. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  101680. */
  101681. var Gizmo = /** @class */ (function () {
  101682. /**
  101683. * Creates a gizmo
  101684. * @param gizmoLayer The utility layer the gizmo will be added to
  101685. */
  101686. function Gizmo(
  101687. /** The utility layer the gizmo will be added to */
  101688. gizmoLayer) {
  101689. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101690. var _this = this;
  101691. this.gizmoLayer = gizmoLayer;
  101692. /**
  101693. * Ratio for the scale of the gizmo (Default: 1)
  101694. */
  101695. this.scaleRatio = 1;
  101696. this._tmpMatrix = new BABYLON.Matrix();
  101697. /**
  101698. * If a custom mesh has been set (Default: false)
  101699. */
  101700. this._customMeshSet = false;
  101701. /**
  101702. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  101703. */
  101704. this.updateGizmoRotationToMatchAttachedMesh = true;
  101705. /**
  101706. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  101707. */
  101708. this.updateGizmoPositionToMatchAttachedMesh = true;
  101709. /**
  101710. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  101711. */
  101712. this._updateScale = true;
  101713. this._interactionsEnabled = true;
  101714. this._tempVector = new BABYLON.Vector3();
  101715. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  101716. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  101717. _this._update();
  101718. });
  101719. this.attachedMesh = null;
  101720. }
  101721. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  101722. /**
  101723. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  101724. * * When set, interactions will be enabled
  101725. */
  101726. get: function () {
  101727. return this._attachedMesh;
  101728. },
  101729. set: function (value) {
  101730. this._attachedMesh = value;
  101731. this._rootMesh.setEnabled(value ? true : false);
  101732. this._attachedMeshChanged(value);
  101733. },
  101734. enumerable: true,
  101735. configurable: true
  101736. });
  101737. /**
  101738. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  101739. * @param mesh The mesh to replace the default mesh of the gizmo
  101740. */
  101741. Gizmo.prototype.setCustomMesh = function (mesh) {
  101742. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  101743. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  101744. }
  101745. this._rootMesh.getChildMeshes().forEach(function (c) {
  101746. c.dispose();
  101747. });
  101748. mesh.parent = this._rootMesh;
  101749. this._customMeshSet = true;
  101750. };
  101751. Gizmo.prototype._attachedMeshChanged = function (value) {
  101752. };
  101753. /**
  101754. * @hidden
  101755. * Updates the gizmo to match the attached mesh's position/rotation
  101756. */
  101757. Gizmo.prototype._update = function () {
  101758. if (this.attachedMesh) {
  101759. if (this.updateGizmoRotationToMatchAttachedMesh) {
  101760. if (!this._rootMesh.rotationQuaternion) {
  101761. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  101762. }
  101763. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  101764. this._tempVector.copyFrom(this.attachedMesh.scaling);
  101765. if (this.attachedMesh.scaling.x < 0) {
  101766. this.attachedMesh.scaling.x *= -1;
  101767. }
  101768. if (this.attachedMesh.scaling.y < 0) {
  101769. this.attachedMesh.scaling.y *= -1;
  101770. }
  101771. if (this.attachedMesh.scaling.z < 0) {
  101772. this.attachedMesh.scaling.z *= -1;
  101773. }
  101774. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  101775. this.attachedMesh.scaling.copyFrom(this._tempVector);
  101776. this.attachedMesh.computeWorldMatrix();
  101777. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  101778. }
  101779. else if (this._rootMesh.rotationQuaternion) {
  101780. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  101781. }
  101782. if (this.updateGizmoPositionToMatchAttachedMesh) {
  101783. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  101784. }
  101785. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  101786. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  101787. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  101788. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  101789. }
  101790. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  101791. var dist = this._tempVector.length() * this.scaleRatio;
  101792. this._rootMesh.scaling.set(dist, dist, dist);
  101793. }
  101794. }
  101795. };
  101796. /**
  101797. * Disposes of the gizmo
  101798. */
  101799. Gizmo.prototype.dispose = function () {
  101800. this._rootMesh.dispose();
  101801. if (this._beforeRenderObserver) {
  101802. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  101803. }
  101804. };
  101805. return Gizmo;
  101806. }());
  101807. BABYLON.Gizmo = Gizmo;
  101808. })(BABYLON || (BABYLON = {}));
  101809. //# sourceMappingURL=babylon.gizmo.js.map
  101810. var BABYLON;
  101811. (function (BABYLON) {
  101812. /**
  101813. * Single axis drag gizmo
  101814. */
  101815. var AxisDragGizmo = /** @class */ (function (_super) {
  101816. __extends(AxisDragGizmo, _super);
  101817. /**
  101818. * Creates an AxisDragGizmo
  101819. * @param gizmoLayer The utility layer the gizmo will be added to
  101820. * @param dragAxis The axis which the gizmo will be able to drag on
  101821. * @param color The color of the gizmo
  101822. */
  101823. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  101824. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  101825. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101826. var _this = _super.call(this, gizmoLayer) || this;
  101827. _this._pointerObserver = null;
  101828. /**
  101829. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101830. */
  101831. _this.snapDistance = 0;
  101832. /**
  101833. * Event that fires each time the gizmo snaps to a new location.
  101834. * * snapDistance is the the change in distance
  101835. */
  101836. _this.onSnapObservable = new BABYLON.Observable();
  101837. // Create Material
  101838. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101839. coloredMaterial.disableLighting = true;
  101840. coloredMaterial.emissiveColor = color;
  101841. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101842. hoverMaterial.disableLighting = true;
  101843. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  101844. // Build mesh on root node
  101845. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101846. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  101847. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  101848. arrowTail.color = coloredMaterial.emissiveColor;
  101849. arrow.addChild(arrowMesh);
  101850. arrow.addChild(arrowTail);
  101851. // Position arrow pointing in its drag axis
  101852. arrowMesh.scaling.scaleInPlace(0.05);
  101853. arrowMesh.material = coloredMaterial;
  101854. arrowMesh.rotation.x = Math.PI / 2;
  101855. arrowMesh.position.z += 0.3;
  101856. arrowTail.scaling.scaleInPlace(0.26);
  101857. arrowTail.rotation.x = Math.PI / 2;
  101858. arrowTail.material = coloredMaterial;
  101859. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  101860. arrow.scaling.scaleInPlace(1 / 3);
  101861. _this._rootMesh.addChild(arrow);
  101862. var currentSnapDragDistance = 0;
  101863. var tmpVector = new BABYLON.Vector3();
  101864. var tmpSnapEvent = { snapDistance: 0 };
  101865. // Add drag behavior to handle events when the gizmo is dragged
  101866. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  101867. _this.dragBehavior.moveAttached = false;
  101868. _this._rootMesh.addBehavior(_this.dragBehavior);
  101869. var localDelta = new BABYLON.Vector3();
  101870. var tmpMatrix = new BABYLON.Matrix();
  101871. _this.dragBehavior.onDragObservable.add(function (event) {
  101872. if (_this.attachedMesh) {
  101873. // Convert delta to local translation if it has a parent
  101874. if (_this.attachedMesh.parent) {
  101875. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  101876. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  101877. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  101878. }
  101879. else {
  101880. localDelta.copyFrom(event.delta);
  101881. }
  101882. // Snapping logic
  101883. if (_this.snapDistance == 0) {
  101884. _this.attachedMesh.position.addInPlace(localDelta);
  101885. }
  101886. else {
  101887. currentSnapDragDistance += event.dragDistance;
  101888. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  101889. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  101890. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  101891. localDelta.normalizeToRef(tmpVector);
  101892. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  101893. _this.attachedMesh.position.addInPlace(tmpVector);
  101894. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  101895. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  101896. }
  101897. }
  101898. }
  101899. });
  101900. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  101901. if (_this._customMeshSet) {
  101902. return;
  101903. }
  101904. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  101905. var material = isHovered ? hoverMaterial : coloredMaterial;
  101906. _this._rootMesh.getChildMeshes().forEach(function (m) {
  101907. m.material = material;
  101908. if (m.color) {
  101909. m.color = material.emissiveColor;
  101910. }
  101911. });
  101912. });
  101913. return _this;
  101914. }
  101915. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  101916. if (this.dragBehavior) {
  101917. this.dragBehavior.enabled = value ? true : false;
  101918. }
  101919. };
  101920. /**
  101921. * Disposes of the gizmo
  101922. */
  101923. AxisDragGizmo.prototype.dispose = function () {
  101924. this.onSnapObservable.clear();
  101925. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101926. this.dragBehavior.detach();
  101927. _super.prototype.dispose.call(this);
  101928. };
  101929. return AxisDragGizmo;
  101930. }(BABYLON.Gizmo));
  101931. BABYLON.AxisDragGizmo = AxisDragGizmo;
  101932. })(BABYLON || (BABYLON = {}));
  101933. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  101934. var BABYLON;
  101935. (function (BABYLON) {
  101936. /**
  101937. * Single axis scale gizmo
  101938. */
  101939. var AxisScaleGizmo = /** @class */ (function (_super) {
  101940. __extends(AxisScaleGizmo, _super);
  101941. /**
  101942. * Creates an AxisScaleGizmo
  101943. * @param gizmoLayer The utility layer the gizmo will be added to
  101944. * @param dragAxis The axis which the gizmo will be able to scale on
  101945. * @param color The color of the gizmo
  101946. */
  101947. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  101948. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  101949. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101950. var _this = _super.call(this, gizmoLayer) || this;
  101951. _this._pointerObserver = null;
  101952. /**
  101953. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101954. */
  101955. _this.snapDistance = 0;
  101956. /**
  101957. * Event that fires each time the gizmo snaps to a new location.
  101958. * * snapDistance is the the change in distance
  101959. */
  101960. _this.onSnapObservable = new BABYLON.Observable();
  101961. /**
  101962. * If the scaling operation should be done on all axis (default: false)
  101963. */
  101964. _this.uniformScaling = false;
  101965. // Create Material
  101966. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101967. _this._coloredMaterial.disableLighting = true;
  101968. _this._coloredMaterial.emissiveColor = color;
  101969. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101970. hoverMaterial.disableLighting = true;
  101971. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  101972. // Build mesh on root node
  101973. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101974. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  101975. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  101976. arrowTail.color = _this._coloredMaterial.emissiveColor;
  101977. arrow.addChild(arrowMesh);
  101978. arrow.addChild(arrowTail);
  101979. // Position arrow pointing in its drag axis
  101980. arrowMesh.scaling.scaleInPlace(0.1);
  101981. arrowMesh.material = _this._coloredMaterial;
  101982. arrowMesh.rotation.x = Math.PI / 2;
  101983. arrowMesh.position.z += 0.3;
  101984. arrowTail.scaling.scaleInPlace(0.26);
  101985. arrowTail.rotation.x = Math.PI / 2;
  101986. arrowTail.material = _this._coloredMaterial;
  101987. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  101988. _this._rootMesh.addChild(arrow);
  101989. arrow.scaling.scaleInPlace(1 / 3);
  101990. // Add drag behavior to handle events when the gizmo is dragged
  101991. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  101992. _this.dragBehavior.moveAttached = false;
  101993. _this._rootMesh.addBehavior(_this.dragBehavior);
  101994. var currentSnapDragDistance = 0;
  101995. var tmpVector = new BABYLON.Vector3();
  101996. var tmpSnapEvent = { snapDistance: 0 };
  101997. _this.dragBehavior.onDragObservable.add(function (event) {
  101998. if (_this.attachedMesh) {
  101999. // Snapping logic
  102000. var snapped = false;
  102001. var dragSteps = 0;
  102002. if (_this.uniformScaling) {
  102003. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  102004. if (tmpVector.y < 0) {
  102005. tmpVector.scaleInPlace(-1);
  102006. }
  102007. }
  102008. else {
  102009. tmpVector.copyFrom(dragAxis);
  102010. }
  102011. if (_this.snapDistance == 0) {
  102012. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  102013. }
  102014. else {
  102015. currentSnapDragDistance += event.dragDistance;
  102016. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  102017. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  102018. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  102019. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  102020. snapped = true;
  102021. }
  102022. else {
  102023. tmpVector.scaleInPlace(0);
  102024. }
  102025. }
  102026. _this.attachedMesh.scaling.addInPlace(tmpVector);
  102027. if (snapped) {
  102028. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  102029. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  102030. }
  102031. }
  102032. });
  102033. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102034. if (_this._customMeshSet) {
  102035. return;
  102036. }
  102037. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  102038. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  102039. _this._rootMesh.getChildMeshes().forEach(function (m) {
  102040. m.material = material;
  102041. if (m.color) {
  102042. m.color = material.emissiveColor;
  102043. }
  102044. });
  102045. });
  102046. return _this;
  102047. }
  102048. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  102049. if (this.dragBehavior) {
  102050. this.dragBehavior.enabled = value ? true : false;
  102051. }
  102052. };
  102053. /**
  102054. * Disposes of the gizmo
  102055. */
  102056. AxisScaleGizmo.prototype.dispose = function () {
  102057. this.onSnapObservable.clear();
  102058. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  102059. this.dragBehavior.detach();
  102060. _super.prototype.dispose.call(this);
  102061. };
  102062. /**
  102063. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  102064. * @param mesh The mesh to replace the default mesh of the gizmo
  102065. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  102066. */
  102067. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  102068. var _this = this;
  102069. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  102070. _super.prototype.setCustomMesh.call(this, mesh);
  102071. if (useGizmoMaterial) {
  102072. this._rootMesh.getChildMeshes().forEach(function (m) {
  102073. m.material = _this._coloredMaterial;
  102074. if (m.color) {
  102075. m.color = _this._coloredMaterial.emissiveColor;
  102076. }
  102077. });
  102078. this._customMeshSet = false;
  102079. }
  102080. };
  102081. return AxisScaleGizmo;
  102082. }(BABYLON.Gizmo));
  102083. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  102084. })(BABYLON || (BABYLON = {}));
  102085. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  102086. var BABYLON;
  102087. (function (BABYLON) {
  102088. /**
  102089. * Single plane rotation gizmo
  102090. */
  102091. var PlaneRotationGizmo = /** @class */ (function (_super) {
  102092. __extends(PlaneRotationGizmo, _super);
  102093. /**
  102094. * Creates a PlaneRotationGizmo
  102095. * @param gizmoLayer The utility layer the gizmo will be added to
  102096. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  102097. * @param color The color of the gizmo
  102098. * @param tessellation Amount of tessellation to be used when creating rotation circles
  102099. */
  102100. function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) {
  102101. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102102. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102103. if (tessellation === void 0) { tessellation = 32; }
  102104. var _this = _super.call(this, gizmoLayer) || this;
  102105. _this._pointerObserver = null;
  102106. /**
  102107. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  102108. */
  102109. _this.snapDistance = 0;
  102110. /**
  102111. * Event that fires each time the gizmo snaps to a new location.
  102112. * * snapDistance is the the change in distance
  102113. */
  102114. _this.onSnapObservable = new BABYLON.Observable();
  102115. // Create Material
  102116. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102117. coloredMaterial.disableLighting = true;
  102118. coloredMaterial.emissiveColor = color;
  102119. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102120. hoverMaterial.disableLighting = true;
  102121. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102122. // Build mesh on root node
  102123. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102124. // Create circle out of lines
  102125. var radius = 0.8;
  102126. var points = new Array();
  102127. for (var i = 0; i < tessellation; i++) {
  102128. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  102129. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  102130. }
  102131. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  102132. rotationMesh.color = coloredMaterial.emissiveColor;
  102133. // Position arrow pointing in its drag axis
  102134. rotationMesh.scaling.scaleInPlace(0.26);
  102135. rotationMesh.material = coloredMaterial;
  102136. rotationMesh.rotation.x = Math.PI / 2;
  102137. parentMesh.addChild(rotationMesh);
  102138. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  102139. _this._rootMesh.addChild(parentMesh);
  102140. parentMesh.scaling.scaleInPlace(1 / 3);
  102141. // Add drag behavior to handle events when the gizmo is dragged
  102142. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  102143. _this.dragBehavior.moveAttached = false;
  102144. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  102145. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  102146. _this._rootMesh.addBehavior(_this.dragBehavior);
  102147. var lastDragPosition = new BABYLON.Vector3();
  102148. _this.dragBehavior.onDragStartObservable.add(function (e) {
  102149. if (_this.attachedMesh) {
  102150. lastDragPosition.copyFrom(e.dragPlanePoint);
  102151. }
  102152. });
  102153. var rotationMatrix = new BABYLON.Matrix();
  102154. var planeNormalTowardsCamera = new BABYLON.Vector3();
  102155. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  102156. var tmpSnapEvent = { snapDistance: 0 };
  102157. var currentSnapDragDistance = 0;
  102158. var tmpMatrix = new BABYLON.Matrix();
  102159. var tmpVector = new BABYLON.Vector3();
  102160. var amountToRotate = new BABYLON.Quaternion();
  102161. _this.dragBehavior.onDragObservable.add(function (event) {
  102162. if (_this.attachedMesh) {
  102163. if (!_this.attachedMesh.rotationQuaternion) {
  102164. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  102165. }
  102166. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  102167. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  102168. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  102169. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  102170. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  102171. var angle = Math.atan2(cross.length(), dot);
  102172. planeNormalTowardsCamera.copyFrom(planeNormal);
  102173. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  102174. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  102175. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  102176. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  102177. }
  102178. // Flip up vector depending on which side the camera is on
  102179. if (gizmoLayer.utilityLayerScene.activeCamera) {
  102180. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  102181. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  102182. planeNormalTowardsCamera.scaleInPlace(-1);
  102183. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  102184. }
  102185. }
  102186. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  102187. if (halfCircleSide) {
  102188. angle = -angle;
  102189. }
  102190. // Snapping logic
  102191. var snapped = false;
  102192. if (_this.snapDistance != 0) {
  102193. currentSnapDragDistance += angle;
  102194. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  102195. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  102196. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  102197. angle = _this.snapDistance * dragSteps;
  102198. snapped = true;
  102199. }
  102200. else {
  102201. angle = 0;
  102202. }
  102203. }
  102204. // If the mesh has a parent, convert needed world rotation to local rotation
  102205. tmpMatrix.reset();
  102206. if (_this.attachedMesh.parent) {
  102207. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  102208. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  102209. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  102210. }
  102211. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  102212. var quaternionCoefficient = Math.sin(angle / 2);
  102213. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  102214. // 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
  102215. if (tmpMatrix.determinant() > 0) {
  102216. amountToRotate.toEulerAnglesToRef(tmpVector);
  102217. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  102218. }
  102219. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  102220. // Rotate selected mesh quaternion over fixed axis
  102221. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  102222. }
  102223. else {
  102224. // Rotate selected mesh quaternion over rotated axis
  102225. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  102226. }
  102227. lastDragPosition.copyFrom(event.dragPlanePoint);
  102228. if (snapped) {
  102229. tmpSnapEvent.snapDistance = angle;
  102230. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  102231. }
  102232. }
  102233. });
  102234. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102235. if (_this._customMeshSet) {
  102236. return;
  102237. }
  102238. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  102239. var material = isHovered ? hoverMaterial : coloredMaterial;
  102240. _this._rootMesh.getChildMeshes().forEach(function (m) {
  102241. m.material = material;
  102242. if (m.color) {
  102243. m.color = material.emissiveColor;
  102244. }
  102245. });
  102246. });
  102247. return _this;
  102248. }
  102249. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  102250. if (this.dragBehavior) {
  102251. this.dragBehavior.enabled = value ? true : false;
  102252. }
  102253. };
  102254. /**
  102255. * Disposes of the gizmo
  102256. */
  102257. PlaneRotationGizmo.prototype.dispose = function () {
  102258. this.onSnapObservable.clear();
  102259. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  102260. this.dragBehavior.detach();
  102261. _super.prototype.dispose.call(this);
  102262. };
  102263. return PlaneRotationGizmo;
  102264. }(BABYLON.Gizmo));
  102265. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  102266. })(BABYLON || (BABYLON = {}));
  102267. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  102268. var BABYLON;
  102269. (function (BABYLON) {
  102270. /**
  102271. * Gizmo that enables dragging a mesh along 3 axis
  102272. */
  102273. var PositionGizmo = /** @class */ (function (_super) {
  102274. __extends(PositionGizmo, _super);
  102275. /**
  102276. * Creates a PositionGizmo
  102277. * @param gizmoLayer The utility layer the gizmo will be added to
  102278. */
  102279. function PositionGizmo(gizmoLayer) {
  102280. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102281. var _this = _super.call(this, gizmoLayer) || this;
  102282. /** Fires an event when any of it's sub gizmos are dragged */
  102283. _this.onDragStartObservable = new BABYLON.Observable();
  102284. /** Fires an event when any of it's sub gizmos are released from dragging */
  102285. _this.onDragEndObservable = new BABYLON.Observable();
  102286. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  102287. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  102288. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  102289. // Relay drag events
  102290. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  102291. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102292. _this.onDragStartObservable.notifyObservers({});
  102293. });
  102294. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102295. _this.onDragEndObservable.notifyObservers({});
  102296. });
  102297. });
  102298. _this.attachedMesh = null;
  102299. return _this;
  102300. }
  102301. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  102302. set: function (mesh) {
  102303. if (this.xGizmo) {
  102304. this.xGizmo.attachedMesh = mesh;
  102305. this.yGizmo.attachedMesh = mesh;
  102306. this.zGizmo.attachedMesh = mesh;
  102307. }
  102308. },
  102309. enumerable: true,
  102310. configurable: true
  102311. });
  102312. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102313. get: function () {
  102314. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102315. },
  102316. set: function (value) {
  102317. if (this.xGizmo) {
  102318. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102319. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102320. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102321. }
  102322. },
  102323. enumerable: true,
  102324. configurable: true
  102325. });
  102326. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  102327. get: function () {
  102328. return this.xGizmo.snapDistance;
  102329. },
  102330. /**
  102331. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102332. */
  102333. set: function (value) {
  102334. if (this.xGizmo) {
  102335. this.xGizmo.snapDistance = value;
  102336. this.yGizmo.snapDistance = value;
  102337. this.zGizmo.snapDistance = value;
  102338. }
  102339. },
  102340. enumerable: true,
  102341. configurable: true
  102342. });
  102343. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  102344. get: function () {
  102345. return this.xGizmo.scaleRatio;
  102346. },
  102347. /**
  102348. * Ratio for the scale of the gizmo (Default: 1)
  102349. */
  102350. set: function (value) {
  102351. if (this.xGizmo) {
  102352. this.xGizmo.scaleRatio = value;
  102353. this.yGizmo.scaleRatio = value;
  102354. this.zGizmo.scaleRatio = value;
  102355. }
  102356. },
  102357. enumerable: true,
  102358. configurable: true
  102359. });
  102360. /**
  102361. * Disposes of the gizmo
  102362. */
  102363. PositionGizmo.prototype.dispose = function () {
  102364. this.xGizmo.dispose();
  102365. this.yGizmo.dispose();
  102366. this.zGizmo.dispose();
  102367. this.onDragStartObservable.clear();
  102368. this.onDragEndObservable.clear();
  102369. };
  102370. /**
  102371. * CustomMeshes are not supported by this gizmo
  102372. * @param mesh The mesh to replace the default mesh of the gizmo
  102373. */
  102374. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  102375. 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)");
  102376. };
  102377. return PositionGizmo;
  102378. }(BABYLON.Gizmo));
  102379. BABYLON.PositionGizmo = PositionGizmo;
  102380. })(BABYLON || (BABYLON = {}));
  102381. //# sourceMappingURL=babylon.positionGizmo.js.map
  102382. var BABYLON;
  102383. (function (BABYLON) {
  102384. /**
  102385. * Gizmo that enables rotating a mesh along 3 axis
  102386. */
  102387. var RotationGizmo = /** @class */ (function (_super) {
  102388. __extends(RotationGizmo, _super);
  102389. /**
  102390. * Creates a RotationGizmo
  102391. * @param gizmoLayer The utility layer the gizmo will be added to
  102392. * @param tessellation Amount of tessellation to be used when creating rotation circles
  102393. */
  102394. function RotationGizmo(gizmoLayer, tessellation) {
  102395. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102396. if (tessellation === void 0) { tessellation = 32; }
  102397. var _this = _super.call(this, gizmoLayer) || this;
  102398. /** Fires an event when any of it's sub gizmos are dragged */
  102399. _this.onDragStartObservable = new BABYLON.Observable();
  102400. /** Fires an event when any of it's sub gizmos are released from dragging */
  102401. _this.onDragEndObservable = new BABYLON.Observable();
  102402. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer, tessellation);
  102403. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer, tessellation);
  102404. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer, tessellation);
  102405. // Relay drag events
  102406. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  102407. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102408. _this.onDragStartObservable.notifyObservers({});
  102409. });
  102410. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102411. _this.onDragEndObservable.notifyObservers({});
  102412. });
  102413. });
  102414. _this.attachedMesh = null;
  102415. return _this;
  102416. }
  102417. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  102418. set: function (mesh) {
  102419. if (this.xGizmo) {
  102420. this.xGizmo.attachedMesh = mesh;
  102421. this.yGizmo.attachedMesh = mesh;
  102422. this.zGizmo.attachedMesh = mesh;
  102423. }
  102424. },
  102425. enumerable: true,
  102426. configurable: true
  102427. });
  102428. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102429. get: function () {
  102430. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102431. },
  102432. set: function (value) {
  102433. if (this.xGizmo) {
  102434. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102435. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102436. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102437. }
  102438. },
  102439. enumerable: true,
  102440. configurable: true
  102441. });
  102442. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  102443. get: function () {
  102444. return this.xGizmo.snapDistance;
  102445. },
  102446. /**
  102447. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102448. */
  102449. set: function (value) {
  102450. if (this.xGizmo) {
  102451. this.xGizmo.snapDistance = value;
  102452. this.yGizmo.snapDistance = value;
  102453. this.zGizmo.snapDistance = value;
  102454. }
  102455. },
  102456. enumerable: true,
  102457. configurable: true
  102458. });
  102459. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  102460. get: function () {
  102461. return this.xGizmo.scaleRatio;
  102462. },
  102463. /**
  102464. * Ratio for the scale of the gizmo (Default: 1)
  102465. */
  102466. set: function (value) {
  102467. if (this.xGizmo) {
  102468. this.xGizmo.scaleRatio = value;
  102469. this.yGizmo.scaleRatio = value;
  102470. this.zGizmo.scaleRatio = value;
  102471. }
  102472. },
  102473. enumerable: true,
  102474. configurable: true
  102475. });
  102476. /**
  102477. * Disposes of the gizmo
  102478. */
  102479. RotationGizmo.prototype.dispose = function () {
  102480. this.xGizmo.dispose();
  102481. this.yGizmo.dispose();
  102482. this.zGizmo.dispose();
  102483. this.onDragStartObservable.clear();
  102484. this.onDragEndObservable.clear();
  102485. };
  102486. /**
  102487. * CustomMeshes are not supported by this gizmo
  102488. * @param mesh The mesh to replace the default mesh of the gizmo
  102489. */
  102490. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  102491. 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)");
  102492. };
  102493. return RotationGizmo;
  102494. }(BABYLON.Gizmo));
  102495. BABYLON.RotationGizmo = RotationGizmo;
  102496. })(BABYLON || (BABYLON = {}));
  102497. //# sourceMappingURL=babylon.rotationGizmo.js.map
  102498. var BABYLON;
  102499. (function (BABYLON) {
  102500. /**
  102501. * Gizmo that enables scaling a mesh along 3 axis
  102502. */
  102503. var ScaleGizmo = /** @class */ (function (_super) {
  102504. __extends(ScaleGizmo, _super);
  102505. /**
  102506. * Creates a ScaleGizmo
  102507. * @param gizmoLayer The utility layer the gizmo will be added to
  102508. */
  102509. function ScaleGizmo(gizmoLayer) {
  102510. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102511. var _this = _super.call(this, gizmoLayer) || this;
  102512. /** Fires an event when any of it's sub gizmos are dragged */
  102513. _this.onDragStartObservable = new BABYLON.Observable();
  102514. /** Fires an event when any of it's sub gizmos are released from dragging */
  102515. _this.onDragEndObservable = new BABYLON.Observable();
  102516. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  102517. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  102518. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  102519. // Create uniform scale gizmo
  102520. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  102521. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  102522. _this.uniformScaleGizmo.uniformScaling = true;
  102523. var uniformScalingMesh = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  102524. uniformScalingMesh.scaling.scaleInPlace(0.02);
  102525. uniformScalingMesh.visibility = 0;
  102526. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  102527. octahedron.scaling.scaleInPlace(0.007);
  102528. uniformScalingMesh.addChild(octahedron);
  102529. _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true);
  102530. // Relay drag events
  102531. [_this.xGizmo, _this.yGizmo, _this.zGizmo, _this.uniformScaleGizmo].forEach(function (gizmo) {
  102532. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102533. _this.onDragStartObservable.notifyObservers({});
  102534. });
  102535. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102536. _this.onDragEndObservable.notifyObservers({});
  102537. });
  102538. });
  102539. _this.attachedMesh = null;
  102540. return _this;
  102541. }
  102542. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  102543. set: function (mesh) {
  102544. if (this.xGizmo) {
  102545. this.xGizmo.attachedMesh = mesh;
  102546. this.yGizmo.attachedMesh = mesh;
  102547. this.zGizmo.attachedMesh = mesh;
  102548. this.uniformScaleGizmo.attachedMesh = mesh;
  102549. }
  102550. },
  102551. enumerable: true,
  102552. configurable: true
  102553. });
  102554. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102555. get: function () {
  102556. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102557. },
  102558. set: function (value) {
  102559. if (!value) {
  102560. BABYLON.Tools.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
  102561. }
  102562. if (this.xGizmo) {
  102563. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102564. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102565. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102566. }
  102567. },
  102568. enumerable: true,
  102569. configurable: true
  102570. });
  102571. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  102572. get: function () {
  102573. return this.xGizmo.snapDistance;
  102574. },
  102575. /**
  102576. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102577. */
  102578. set: function (value) {
  102579. if (this.xGizmo) {
  102580. this.xGizmo.snapDistance = value;
  102581. this.yGizmo.snapDistance = value;
  102582. this.zGizmo.snapDistance = value;
  102583. this.uniformScaleGizmo.snapDistance = value;
  102584. }
  102585. },
  102586. enumerable: true,
  102587. configurable: true
  102588. });
  102589. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  102590. get: function () {
  102591. return this.xGizmo.scaleRatio;
  102592. },
  102593. /**
  102594. * Ratio for the scale of the gizmo (Default: 1)
  102595. */
  102596. set: function (value) {
  102597. if (this.xGizmo) {
  102598. this.xGizmo.scaleRatio = value;
  102599. this.yGizmo.scaleRatio = value;
  102600. this.zGizmo.scaleRatio = value;
  102601. this.uniformScaleGizmo.scaleRatio = value;
  102602. }
  102603. },
  102604. enumerable: true,
  102605. configurable: true
  102606. });
  102607. /**
  102608. * Disposes of the gizmo
  102609. */
  102610. ScaleGizmo.prototype.dispose = function () {
  102611. this.xGizmo.dispose();
  102612. this.yGizmo.dispose();
  102613. this.zGizmo.dispose();
  102614. this.uniformScaleGizmo.dispose();
  102615. this.onDragStartObservable.clear();
  102616. this.onDragEndObservable.clear();
  102617. };
  102618. return ScaleGizmo;
  102619. }(BABYLON.Gizmo));
  102620. BABYLON.ScaleGizmo = ScaleGizmo;
  102621. })(BABYLON || (BABYLON = {}));
  102622. //# sourceMappingURL=babylon.scaleGizmo.js.map
  102623. var BABYLON;
  102624. (function (BABYLON) {
  102625. /**
  102626. * Bounding box gizmo
  102627. */
  102628. var BoundingBoxGizmo = /** @class */ (function (_super) {
  102629. __extends(BoundingBoxGizmo, _super);
  102630. /**
  102631. * Creates an BoundingBoxGizmo
  102632. * @param gizmoLayer The utility layer the gizmo will be added to
  102633. * @param color The color of the gizmo
  102634. */
  102635. function BoundingBoxGizmo(color, gizmoLayer) {
  102636. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102637. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  102638. var _this = _super.call(this, gizmoLayer) || this;
  102639. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  102640. _this._renderObserver = null;
  102641. _this._pointerObserver = null;
  102642. _this._scaleDragSpeed = 0.2;
  102643. _this._tmpQuaternion = new BABYLON.Quaternion();
  102644. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  102645. _this._tmpRotationMatrix = new BABYLON.Matrix();
  102646. /**
  102647. * 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)
  102648. */
  102649. _this.ignoreChildren = false;
  102650. /**
  102651. * 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)
  102652. */
  102653. _this.includeChildPredicate = null;
  102654. /**
  102655. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  102656. */
  102657. _this.rotationSphereSize = 0.1;
  102658. /**
  102659. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  102660. */
  102661. _this.scaleBoxSize = 0.1;
  102662. /**
  102663. * 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)
  102664. */
  102665. _this.fixedDragMeshScreenSize = false;
  102666. /**
  102667. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  102668. */
  102669. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  102670. /**
  102671. * Fired when a rotation sphere or scale box is dragged
  102672. */
  102673. _this.onDragStartObservable = new BABYLON.Observable();
  102674. /**
  102675. * Fired when a scale box is dragged
  102676. */
  102677. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  102678. /**
  102679. * Fired when a scale box drag is ended
  102680. */
  102681. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  102682. /**
  102683. * Fired when a rotation sphere is dragged
  102684. */
  102685. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  102686. /**
  102687. * Fired when a rotation sphere drag is ended
  102688. */
  102689. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  102690. /**
  102691. * 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)
  102692. */
  102693. _this.scalePivot = null;
  102694. _this._existingMeshScale = new BABYLON.Vector3();
  102695. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  102696. _this._updateScale = false;
  102697. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  102698. // Create Materials
  102699. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102700. coloredMaterial.disableLighting = true;
  102701. coloredMaterial.emissiveColor = color;
  102702. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102703. hoverColoredMaterial.disableLighting = true;
  102704. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102705. // Build bounding box out of lines
  102706. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102707. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  102708. var lines = [];
  102709. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  102710. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  102711. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  102712. 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));
  102713. 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));
  102714. 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));
  102715. 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));
  102716. 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));
  102717. 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));
  102718. 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));
  102719. 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));
  102720. 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));
  102721. lines.forEach(function (l) {
  102722. l.color = color;
  102723. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  102724. l.isPickable = false;
  102725. _this._lineBoundingBox.addChild(l);
  102726. });
  102727. _this._rootMesh.addChild(_this._lineBoundingBox);
  102728. // Create rotation spheres
  102729. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102730. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  102731. var _loop_1 = function (i_1) {
  102732. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  102733. sphere.rotationQuaternion = new BABYLON.Quaternion();
  102734. sphere.material = coloredMaterial;
  102735. // Drag behavior
  102736. _dragBehavior = new BABYLON.PointerDragBehavior({});
  102737. _dragBehavior.moveAttached = false;
  102738. _dragBehavior.updateDragPlane = false;
  102739. sphere.addBehavior(_dragBehavior);
  102740. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  102741. var totalTurnAmountOfDrag = 0;
  102742. _dragBehavior.onDragStartObservable.add(function (event) {
  102743. startingTurnDirection.copyFrom(sphere.forward);
  102744. totalTurnAmountOfDrag = 0;
  102745. });
  102746. _dragBehavior.onDragObservable.add(function (event) {
  102747. _this.onRotationSphereDragObservable.notifyObservers({});
  102748. if (_this.attachedMesh) {
  102749. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  102750. var worldDragDirection = startingTurnDirection;
  102751. // Project the world right on to the drag plane
  102752. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  102753. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  102754. // project drag delta on to the resulting drag axis and rotate based on that
  102755. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  102756. // Make rotation relative to size of mesh.
  102757. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  102758. // Rotate based on axis
  102759. if (!_this.attachedMesh.rotationQuaternion) {
  102760. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  102761. }
  102762. if (!_this._anchorMesh.rotationQuaternion) {
  102763. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  102764. }
  102765. // Do not allow the object to turn more than a full circle
  102766. totalTurnAmountOfDrag += projectDist;
  102767. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  102768. if (i_1 >= 8) {
  102769. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  102770. }
  102771. else if (i_1 >= 4) {
  102772. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  102773. }
  102774. else {
  102775. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  102776. }
  102777. // Rotate around center of bounding box
  102778. _this._anchorMesh.addChild(_this.attachedMesh);
  102779. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  102780. _this._anchorMesh.removeChild(_this.attachedMesh);
  102781. }
  102782. _this.updateBoundingBox();
  102783. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  102784. }
  102785. });
  102786. // Selection/deselection
  102787. _dragBehavior.onDragStartObservable.add(function () {
  102788. _this.onDragStartObservable.notifyObservers({});
  102789. _this._selectNode(sphere);
  102790. });
  102791. _dragBehavior.onDragEndObservable.add(function () {
  102792. _this.onRotationSphereDragEndObservable.notifyObservers({});
  102793. _this._selectNode(null);
  102794. });
  102795. this_1._rotateSpheresParent.addChild(sphere);
  102796. };
  102797. var this_1 = this, _dragBehavior;
  102798. for (var i_1 = 0; i_1 < 12; i_1++) {
  102799. _loop_1(i_1);
  102800. }
  102801. _this._rootMesh.addChild(_this._rotateSpheresParent);
  102802. // Create scale cubes
  102803. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102804. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  102805. for (var i = 0; i < 2; i++) {
  102806. for (var j = 0; j < 2; j++) {
  102807. var _loop_2 = function () {
  102808. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  102809. box.material = coloredMaterial;
  102810. // Dragging logic
  102811. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  102812. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  102813. _dragBehavior.moveAttached = false;
  102814. box.addBehavior(_dragBehavior);
  102815. _dragBehavior.onDragObservable.add(function (event) {
  102816. _this.onScaleBoxDragObservable.notifyObservers({});
  102817. if (_this.attachedMesh) {
  102818. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  102819. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  102820. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  102821. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  102822. _this.updateBoundingBox();
  102823. if (_this.scalePivot) {
  102824. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  102825. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  102826. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  102827. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  102828. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  102829. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  102830. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  102831. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  102832. }
  102833. else {
  102834. // Scale from the position of the opposite corner
  102835. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  102836. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  102837. }
  102838. _this._anchorMesh.addChild(_this.attachedMesh);
  102839. _this._anchorMesh.scaling.addInPlace(deltaScale);
  102840. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  102841. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  102842. }
  102843. _this._anchorMesh.removeChild(_this.attachedMesh);
  102844. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  102845. }
  102846. });
  102847. // Selection/deselection
  102848. _dragBehavior.onDragStartObservable.add(function () {
  102849. _this.onDragStartObservable.notifyObservers({});
  102850. _this._selectNode(box);
  102851. });
  102852. _dragBehavior.onDragEndObservable.add(function () {
  102853. _this.onScaleBoxDragEndObservable.notifyObservers({});
  102854. _this._selectNode(null);
  102855. });
  102856. this_2._scaleBoxesParent.addChild(box);
  102857. };
  102858. var this_2 = this, _dragBehavior;
  102859. for (var k = 0; k < 2; k++) {
  102860. _loop_2();
  102861. }
  102862. }
  102863. }
  102864. _this._rootMesh.addChild(_this._scaleBoxesParent);
  102865. // Hover color change
  102866. var pointerIds = new Array();
  102867. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102868. if (!pointerIds[pointerInfo.event.pointerId]) {
  102869. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  102870. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  102871. pointerIds[pointerInfo.event.pointerId] = mesh;
  102872. mesh.material = hoverColoredMaterial;
  102873. }
  102874. });
  102875. }
  102876. else {
  102877. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  102878. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  102879. delete pointerIds[pointerInfo.event.pointerId];
  102880. }
  102881. }
  102882. });
  102883. // Update bounding box positions
  102884. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  102885. // Only update the bouding box if scaling has changed
  102886. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  102887. _this.updateBoundingBox();
  102888. }
  102889. });
  102890. _this.updateBoundingBox();
  102891. return _this;
  102892. }
  102893. /** @hidden */
  102894. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  102895. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  102896. // Save old pivot and set pivot to 0,0,0
  102897. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  102898. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  102899. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  102900. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  102901. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  102902. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  102903. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  102904. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  102905. }
  102906. }
  102907. BoundingBoxGizmo._PivotCached++;
  102908. };
  102909. /** @hidden */
  102910. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  102911. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  102912. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  102913. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  102914. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  102915. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  102916. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  102917. }
  102918. this._PivotCached--;
  102919. };
  102920. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  102921. if (value) {
  102922. // Reset anchor mesh to match attached mesh's scale
  102923. // This is needed to avoid invalid box/sphere position on first drag
  102924. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  102925. this._anchorMesh.addChild(value);
  102926. this._anchorMesh.removeChild(value);
  102927. BoundingBoxGizmo._RestorePivotPoint(value);
  102928. this.updateBoundingBox();
  102929. }
  102930. };
  102931. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  102932. this._rotateSpheresParent.getChildMeshes()
  102933. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  102934. m.isVisible = (!selectedMesh || m == selectedMesh);
  102935. });
  102936. };
  102937. /**
  102938. * Updates the bounding box information for the Gizmo
  102939. */
  102940. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  102941. if (this.attachedMesh) {
  102942. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  102943. this._update();
  102944. // Rotate based on axis
  102945. if (!this.attachedMesh.rotationQuaternion) {
  102946. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  102947. }
  102948. if (!this._anchorMesh.rotationQuaternion) {
  102949. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  102950. }
  102951. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  102952. // Store original position and reset mesh to origin before computing the bounding box
  102953. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  102954. this._tmpVector.copyFrom(this.attachedMesh.position);
  102955. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  102956. this.attachedMesh.position.set(0, 0, 0);
  102957. // Update bounding dimensions/positions
  102958. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  102959. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  102960. // Update gizmo to match bounding box scaling and rotation
  102961. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  102962. 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);
  102963. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  102964. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  102965. this._lineBoundingBox.computeWorldMatrix();
  102966. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  102967. // restore position/rotation values
  102968. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  102969. this.attachedMesh.position.copyFrom(this._tmpVector);
  102970. }
  102971. // Update rotation sphere locations
  102972. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  102973. for (var i = 0; i < 3; i++) {
  102974. for (var j = 0; j < 2; j++) {
  102975. for (var k = 0; k < 2; k++) {
  102976. var index = ((i * 4) + (j * 2)) + k;
  102977. if (i == 0) {
  102978. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  102979. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  102980. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  102981. }
  102982. if (i == 1) {
  102983. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  102984. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  102985. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  102986. }
  102987. if (i == 2) {
  102988. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  102989. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  102990. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  102991. }
  102992. if (this.fixedDragMeshScreenSize) {
  102993. this._rootMesh.computeWorldMatrix();
  102994. this._rotateSpheresParent.computeWorldMatrix();
  102995. rotateSpheres[index].computeWorldMatrix();
  102996. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  102997. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  102998. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  102999. }
  103000. else {
  103001. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  103002. }
  103003. }
  103004. }
  103005. }
  103006. // Update scale box locations
  103007. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  103008. for (var i = 0; i < 2; i++) {
  103009. for (var j = 0; j < 2; j++) {
  103010. for (var k = 0; k < 2; k++) {
  103011. var index = ((i * 4) + (j * 2)) + k;
  103012. if (scaleBoxes[index]) {
  103013. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  103014. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103015. if (this.fixedDragMeshScreenSize) {
  103016. this._rootMesh.computeWorldMatrix();
  103017. this._scaleBoxesParent.computeWorldMatrix();
  103018. scaleBoxes[index].computeWorldMatrix();
  103019. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  103020. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  103021. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  103022. }
  103023. else {
  103024. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  103025. }
  103026. }
  103027. }
  103028. }
  103029. }
  103030. if (this.attachedMesh) {
  103031. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  103032. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  103033. }
  103034. };
  103035. /**
  103036. * Enables rotation on the specified axis and disables rotation on the others
  103037. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  103038. */
  103039. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  103040. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  103041. if (i < 4) {
  103042. m.setEnabled(axis.indexOf("x") != -1);
  103043. }
  103044. else if (i < 8) {
  103045. m.setEnabled(axis.indexOf("y") != -1);
  103046. }
  103047. else {
  103048. m.setEnabled(axis.indexOf("z") != -1);
  103049. }
  103050. });
  103051. };
  103052. /**
  103053. * Disposes of the gizmo
  103054. */
  103055. BoundingBoxGizmo.prototype.dispose = function () {
  103056. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  103057. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  103058. this._lineBoundingBox.dispose();
  103059. this._rotateSpheresParent.dispose();
  103060. this._scaleBoxesParent.dispose();
  103061. _super.prototype.dispose.call(this);
  103062. };
  103063. /**
  103064. * 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)
  103065. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  103066. * @returns the bounding box mesh with the passed in mesh as a child
  103067. */
  103068. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  103069. var makeNotPickable = function (root) {
  103070. root.isPickable = false;
  103071. root.getChildMeshes().forEach(function (c) {
  103072. makeNotPickable(c);
  103073. });
  103074. };
  103075. makeNotPickable(mesh);
  103076. // Reset position to get boudning box from origin with no rotation
  103077. if (!mesh.rotationQuaternion) {
  103078. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  103079. }
  103080. var oldPos = mesh.position.clone();
  103081. var oldRot = mesh.rotationQuaternion.clone();
  103082. mesh.rotationQuaternion.set(0, 0, 0, 1);
  103083. mesh.position.set(0, 0, 0);
  103084. // Update bounding dimensions/positions
  103085. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  103086. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  103087. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  103088. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  103089. // Restore original positions
  103090. mesh.addChild(box);
  103091. mesh.rotationQuaternion.copyFrom(oldRot);
  103092. mesh.position.copyFrom(oldPos);
  103093. // Reverse parenting
  103094. mesh.removeChild(box);
  103095. box.addChild(mesh);
  103096. box.visibility = 0;
  103097. return box;
  103098. };
  103099. /**
  103100. * CustomMeshes are not supported by this gizmo
  103101. * @param mesh The mesh to replace the default mesh of the gizmo
  103102. */
  103103. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  103104. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  103105. };
  103106. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  103107. // store/remove pivot point should only be applied during their outermost calls
  103108. BoundingBoxGizmo._PivotCached = 0;
  103109. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  103110. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  103111. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  103112. return BoundingBoxGizmo;
  103113. }(BABYLON.Gizmo));
  103114. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  103115. })(BABYLON || (BABYLON = {}));
  103116. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  103117. var BABYLON;
  103118. (function (BABYLON) {
  103119. /**
  103120. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  103121. */
  103122. var GizmoManager = /** @class */ (function () {
  103123. /**
  103124. * Instatiates a gizmo manager
  103125. * @param scene the scene to overlay the gizmos on top of
  103126. */
  103127. function GizmoManager(scene) {
  103128. var _this = this;
  103129. this.scene = scene;
  103130. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  103131. this._pointerObserver = null;
  103132. this._attachedMesh = null;
  103133. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  103134. /**
  103135. * When bounding box gizmo is enabled, this can be used to track drag/end events
  103136. */
  103137. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  103138. /**
  103139. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  103140. */
  103141. this.attachableMeshes = null;
  103142. /**
  103143. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  103144. */
  103145. this.usePointerToAttachGizmos = true;
  103146. this._defaultKeepDepthUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  103147. this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  103148. this._defaultUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  103149. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  103150. // Instatiate/dispose gizmos based on pointer actions
  103151. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  103152. if (!_this.usePointerToAttachGizmos) {
  103153. return;
  103154. }
  103155. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  103156. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  103157. var node = pointerInfo.pickInfo.pickedMesh;
  103158. if (_this.attachableMeshes == null) {
  103159. // Attach to the most parent node
  103160. while (node && node.parent != null) {
  103161. node = node.parent;
  103162. }
  103163. }
  103164. else {
  103165. // Attach to the parent node that is an attachableMesh
  103166. var found = false;
  103167. _this.attachableMeshes.forEach(function (mesh) {
  103168. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  103169. node = mesh;
  103170. found = true;
  103171. }
  103172. });
  103173. if (!found) {
  103174. node = null;
  103175. }
  103176. }
  103177. if (node instanceof BABYLON.AbstractMesh) {
  103178. if (_this._attachedMesh != node) {
  103179. _this.attachToMesh(node);
  103180. }
  103181. }
  103182. else {
  103183. _this.attachToMesh(null);
  103184. }
  103185. }
  103186. else {
  103187. _this.attachToMesh(null);
  103188. }
  103189. }
  103190. });
  103191. }
  103192. /**
  103193. * Attaches a set of gizmos to the specified mesh
  103194. * @param mesh The mesh the gizmo's should be attached to
  103195. */
  103196. GizmoManager.prototype.attachToMesh = function (mesh) {
  103197. if (this._attachedMesh) {
  103198. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  103199. }
  103200. this._attachedMesh = mesh;
  103201. for (var key in this.gizmos) {
  103202. var gizmo = (this.gizmos[key]);
  103203. if (gizmo && this._gizmosEnabled[key]) {
  103204. gizmo.attachedMesh = mesh;
  103205. }
  103206. }
  103207. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  103208. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  103209. }
  103210. };
  103211. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  103212. get: function () {
  103213. return this._gizmosEnabled.positionGizmo;
  103214. },
  103215. /**
  103216. * If the position gizmo is enabled
  103217. */
  103218. set: function (value) {
  103219. if (value) {
  103220. if (!this.gizmos.positionGizmo) {
  103221. this.gizmos.positionGizmo = new BABYLON.PositionGizmo(this._defaultUtilityLayer);
  103222. }
  103223. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  103224. }
  103225. else if (this.gizmos.positionGizmo) {
  103226. this.gizmos.positionGizmo.attachedMesh = null;
  103227. }
  103228. this._gizmosEnabled.positionGizmo = value;
  103229. },
  103230. enumerable: true,
  103231. configurable: true
  103232. });
  103233. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  103234. get: function () {
  103235. return this._gizmosEnabled.rotationGizmo;
  103236. },
  103237. /**
  103238. * If the rotation gizmo is enabled
  103239. */
  103240. set: function (value) {
  103241. if (value) {
  103242. if (!this.gizmos.rotationGizmo) {
  103243. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo(this._defaultUtilityLayer);
  103244. }
  103245. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  103246. }
  103247. else if (this.gizmos.rotationGizmo) {
  103248. this.gizmos.rotationGizmo.attachedMesh = null;
  103249. }
  103250. this._gizmosEnabled.rotationGizmo = value;
  103251. },
  103252. enumerable: true,
  103253. configurable: true
  103254. });
  103255. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  103256. get: function () {
  103257. return this._gizmosEnabled.scaleGizmo;
  103258. },
  103259. /**
  103260. * If the scale gizmo is enabled
  103261. */
  103262. set: function (value) {
  103263. if (value) {
  103264. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo(this._defaultUtilityLayer);
  103265. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  103266. }
  103267. else if (this.gizmos.scaleGizmo) {
  103268. this.gizmos.scaleGizmo.attachedMesh = null;
  103269. }
  103270. this._gizmosEnabled.scaleGizmo = value;
  103271. },
  103272. enumerable: true,
  103273. configurable: true
  103274. });
  103275. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  103276. get: function () {
  103277. return this._gizmosEnabled.boundingBoxGizmo;
  103278. },
  103279. /**
  103280. * If the boundingBox gizmo is enabled
  103281. */
  103282. set: function (value) {
  103283. if (value) {
  103284. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
  103285. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  103286. if (this._attachedMesh) {
  103287. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  103288. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  103289. }
  103290. }
  103291. else if (this.gizmos.boundingBoxGizmo) {
  103292. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  103293. }
  103294. this._gizmosEnabled.boundingBoxGizmo = value;
  103295. },
  103296. enumerable: true,
  103297. configurable: true
  103298. });
  103299. /**
  103300. * Disposes of the gizmo manager
  103301. */
  103302. GizmoManager.prototype.dispose = function () {
  103303. this.scene.onPointerObservable.remove(this._pointerObserver);
  103304. for (var key in this.gizmos) {
  103305. var gizmo = (this.gizmos[key]);
  103306. if (gizmo) {
  103307. gizmo.dispose();
  103308. }
  103309. }
  103310. this._defaultKeepDepthUtilityLayer.dispose();
  103311. this._defaultUtilityLayer.dispose();
  103312. this.boundingBoxDragBehavior.detach();
  103313. };
  103314. return GizmoManager;
  103315. }());
  103316. BABYLON.GizmoManager = GizmoManager;
  103317. })(BABYLON || (BABYLON = {}));
  103318. //# sourceMappingURL=babylon.gizmoManager.js.map
  103319. var BABYLON;
  103320. (function (BABYLON) {
  103321. /**
  103322. * Defines a target to use with MorphTargetManager
  103323. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  103324. */
  103325. var MorphTarget = /** @class */ (function () {
  103326. /**
  103327. * Creates a new MorphTarget
  103328. * @param name defines the name of the target
  103329. * @param influence defines the influence to use
  103330. */
  103331. function MorphTarget(
  103332. /** defines the name of the target */
  103333. name, influence, scene) {
  103334. if (influence === void 0) { influence = 0; }
  103335. if (scene === void 0) { scene = null; }
  103336. this.name = name;
  103337. /**
  103338. * Gets or sets the list of animations
  103339. */
  103340. this.animations = new Array();
  103341. this._positions = null;
  103342. this._normals = null;
  103343. this._tangents = null;
  103344. /**
  103345. * Observable raised when the influence changes
  103346. */
  103347. this.onInfluenceChanged = new BABYLON.Observable();
  103348. /** @hidden */
  103349. this._onDataLayoutChanged = new BABYLON.Observable();
  103350. this._animationPropertiesOverride = null;
  103351. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  103352. this.influence = influence;
  103353. }
  103354. Object.defineProperty(MorphTarget.prototype, "influence", {
  103355. /**
  103356. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  103357. */
  103358. get: function () {
  103359. return this._influence;
  103360. },
  103361. set: function (influence) {
  103362. if (this._influence === influence) {
  103363. return;
  103364. }
  103365. var previous = this._influence;
  103366. this._influence = influence;
  103367. if (this.onInfluenceChanged.hasObservers) {
  103368. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  103369. }
  103370. },
  103371. enumerable: true,
  103372. configurable: true
  103373. });
  103374. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  103375. /**
  103376. * Gets or sets the animation properties override
  103377. */
  103378. get: function () {
  103379. if (!this._animationPropertiesOverride && this._scene) {
  103380. return this._scene.animationPropertiesOverride;
  103381. }
  103382. return this._animationPropertiesOverride;
  103383. },
  103384. set: function (value) {
  103385. this._animationPropertiesOverride = value;
  103386. },
  103387. enumerable: true,
  103388. configurable: true
  103389. });
  103390. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  103391. /**
  103392. * Gets a boolean defining if the target contains position data
  103393. */
  103394. get: function () {
  103395. return !!this._positions;
  103396. },
  103397. enumerable: true,
  103398. configurable: true
  103399. });
  103400. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  103401. /**
  103402. * Gets a boolean defining if the target contains normal data
  103403. */
  103404. get: function () {
  103405. return !!this._normals;
  103406. },
  103407. enumerable: true,
  103408. configurable: true
  103409. });
  103410. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  103411. /**
  103412. * Gets a boolean defining if the target contains tangent data
  103413. */
  103414. get: function () {
  103415. return !!this._tangents;
  103416. },
  103417. enumerable: true,
  103418. configurable: true
  103419. });
  103420. /**
  103421. * Affects position data to this target
  103422. * @param data defines the position data to use
  103423. */
  103424. MorphTarget.prototype.setPositions = function (data) {
  103425. var hadPositions = this.hasPositions;
  103426. this._positions = data;
  103427. if (hadPositions !== this.hasPositions) {
  103428. this._onDataLayoutChanged.notifyObservers(undefined);
  103429. }
  103430. };
  103431. /**
  103432. * Gets the position data stored in this target
  103433. * @returns a FloatArray containing the position data (or null if not present)
  103434. */
  103435. MorphTarget.prototype.getPositions = function () {
  103436. return this._positions;
  103437. };
  103438. /**
  103439. * Affects normal data to this target
  103440. * @param data defines the normal data to use
  103441. */
  103442. MorphTarget.prototype.setNormals = function (data) {
  103443. var hadNormals = this.hasNormals;
  103444. this._normals = data;
  103445. if (hadNormals !== this.hasNormals) {
  103446. this._onDataLayoutChanged.notifyObservers(undefined);
  103447. }
  103448. };
  103449. /**
  103450. * Gets the normal data stored in this target
  103451. * @returns a FloatArray containing the normal data (or null if not present)
  103452. */
  103453. MorphTarget.prototype.getNormals = function () {
  103454. return this._normals;
  103455. };
  103456. /**
  103457. * Affects tangent data to this target
  103458. * @param data defines the tangent data to use
  103459. */
  103460. MorphTarget.prototype.setTangents = function (data) {
  103461. var hadTangents = this.hasTangents;
  103462. this._tangents = data;
  103463. if (hadTangents !== this.hasTangents) {
  103464. this._onDataLayoutChanged.notifyObservers(undefined);
  103465. }
  103466. };
  103467. /**
  103468. * Gets the tangent data stored in this target
  103469. * @returns a FloatArray containing the tangent data (or null if not present)
  103470. */
  103471. MorphTarget.prototype.getTangents = function () {
  103472. return this._tangents;
  103473. };
  103474. /**
  103475. * Serializes the current target into a Serialization object
  103476. * @returns the serialized object
  103477. */
  103478. MorphTarget.prototype.serialize = function () {
  103479. var serializationObject = {};
  103480. serializationObject.name = this.name;
  103481. serializationObject.influence = this.influence;
  103482. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  103483. if (this.hasNormals) {
  103484. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  103485. }
  103486. if (this.hasTangents) {
  103487. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  103488. }
  103489. // Animations
  103490. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  103491. return serializationObject;
  103492. };
  103493. // Statics
  103494. /**
  103495. * Creates a new target from serialized data
  103496. * @param serializationObject defines the serialized data to use
  103497. * @returns a new MorphTarget
  103498. */
  103499. MorphTarget.Parse = function (serializationObject) {
  103500. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  103501. result.setPositions(serializationObject.positions);
  103502. if (serializationObject.normals) {
  103503. result.setNormals(serializationObject.normals);
  103504. }
  103505. if (serializationObject.tangents) {
  103506. result.setTangents(serializationObject.tangents);
  103507. }
  103508. // Animations
  103509. if (serializationObject.animations) {
  103510. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  103511. var parsedAnimation = serializationObject.animations[animationIndex];
  103512. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  103513. }
  103514. }
  103515. return result;
  103516. };
  103517. /**
  103518. * Creates a MorphTarget from mesh data
  103519. * @param mesh defines the source mesh
  103520. * @param name defines the name to use for the new target
  103521. * @param influence defines the influence to attach to the target
  103522. * @returns a new MorphTarget
  103523. */
  103524. MorphTarget.FromMesh = function (mesh, name, influence) {
  103525. if (!name) {
  103526. name = mesh.name;
  103527. }
  103528. var result = new MorphTarget(name, influence, mesh.getScene());
  103529. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  103530. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  103531. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  103532. }
  103533. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  103534. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  103535. }
  103536. return result;
  103537. };
  103538. return MorphTarget;
  103539. }());
  103540. BABYLON.MorphTarget = MorphTarget;
  103541. })(BABYLON || (BABYLON = {}));
  103542. //# sourceMappingURL=babylon.morphTarget.js.map
  103543. var BABYLON;
  103544. (function (BABYLON) {
  103545. /**
  103546. * This class is used to deform meshes using morphing between different targets
  103547. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  103548. */
  103549. var MorphTargetManager = /** @class */ (function () {
  103550. /**
  103551. * Creates a new MorphTargetManager
  103552. * @param scene defines the current scene
  103553. */
  103554. function MorphTargetManager(scene) {
  103555. if (scene === void 0) { scene = null; }
  103556. this._targets = new Array();
  103557. this._targetInfluenceChangedObservers = new Array();
  103558. this._targetDataLayoutChangedObservers = new Array();
  103559. this._activeTargets = new BABYLON.SmartArray(16);
  103560. this._supportsNormals = false;
  103561. this._supportsTangents = false;
  103562. this._vertexCount = 0;
  103563. this._uniqueId = 0;
  103564. this._tempInfluences = new Array();
  103565. if (!scene) {
  103566. scene = BABYLON.Engine.LastCreatedScene;
  103567. }
  103568. this._scene = scene;
  103569. if (this._scene) {
  103570. this._scene.morphTargetManagers.push(this);
  103571. this._uniqueId = this._scene.getUniqueId();
  103572. }
  103573. }
  103574. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  103575. /**
  103576. * Gets the unique ID of this manager
  103577. */
  103578. get: function () {
  103579. return this._uniqueId;
  103580. },
  103581. enumerable: true,
  103582. configurable: true
  103583. });
  103584. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  103585. /**
  103586. * Gets the number of vertices handled by this manager
  103587. */
  103588. get: function () {
  103589. return this._vertexCount;
  103590. },
  103591. enumerable: true,
  103592. configurable: true
  103593. });
  103594. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  103595. /**
  103596. * Gets a boolean indicating if this manager supports morphing of normals
  103597. */
  103598. get: function () {
  103599. return this._supportsNormals;
  103600. },
  103601. enumerable: true,
  103602. configurable: true
  103603. });
  103604. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  103605. /**
  103606. * Gets a boolean indicating if this manager supports morphing of tangents
  103607. */
  103608. get: function () {
  103609. return this._supportsTangents;
  103610. },
  103611. enumerable: true,
  103612. configurable: true
  103613. });
  103614. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  103615. /**
  103616. * Gets the number of targets stored in this manager
  103617. */
  103618. get: function () {
  103619. return this._targets.length;
  103620. },
  103621. enumerable: true,
  103622. configurable: true
  103623. });
  103624. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  103625. /**
  103626. * Gets the number of influencers (ie. the number of targets with influences > 0)
  103627. */
  103628. get: function () {
  103629. return this._activeTargets.length;
  103630. },
  103631. enumerable: true,
  103632. configurable: true
  103633. });
  103634. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  103635. /**
  103636. * Gets the list of influences (one per target)
  103637. */
  103638. get: function () {
  103639. return this._influences;
  103640. },
  103641. enumerable: true,
  103642. configurable: true
  103643. });
  103644. /**
  103645. * Gets the active target at specified index. An active target is a target with an influence > 0
  103646. * @param index defines the index to check
  103647. * @returns the requested target
  103648. */
  103649. MorphTargetManager.prototype.getActiveTarget = function (index) {
  103650. return this._activeTargets.data[index];
  103651. };
  103652. /**
  103653. * Gets the target at specified index
  103654. * @param index defines the index to check
  103655. * @returns the requested target
  103656. */
  103657. MorphTargetManager.prototype.getTarget = function (index) {
  103658. return this._targets[index];
  103659. };
  103660. /**
  103661. * Add a new target to this manager
  103662. * @param target defines the target to add
  103663. */
  103664. MorphTargetManager.prototype.addTarget = function (target) {
  103665. var _this = this;
  103666. this._targets.push(target);
  103667. this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add(function (needUpdate) {
  103668. _this._syncActiveTargets(needUpdate);
  103669. }));
  103670. this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(function () {
  103671. _this._syncActiveTargets(true);
  103672. }));
  103673. this._syncActiveTargets(true);
  103674. };
  103675. /**
  103676. * Removes a target from the manager
  103677. * @param target defines the target to remove
  103678. */
  103679. MorphTargetManager.prototype.removeTarget = function (target) {
  103680. var index = this._targets.indexOf(target);
  103681. if (index >= 0) {
  103682. this._targets.splice(index, 1);
  103683. target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]);
  103684. target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]);
  103685. this._syncActiveTargets(true);
  103686. }
  103687. };
  103688. /**
  103689. * Serializes the current manager into a Serialization object
  103690. * @returns the serialized object
  103691. */
  103692. MorphTargetManager.prototype.serialize = function () {
  103693. var serializationObject = {};
  103694. serializationObject.id = this.uniqueId;
  103695. serializationObject.targets = [];
  103696. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  103697. var target = _a[_i];
  103698. serializationObject.targets.push(target.serialize());
  103699. }
  103700. return serializationObject;
  103701. };
  103702. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  103703. var influenceCount = 0;
  103704. this._activeTargets.reset();
  103705. this._supportsNormals = true;
  103706. this._supportsTangents = true;
  103707. this._vertexCount = 0;
  103708. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  103709. var target = _a[_i];
  103710. if (target.influence === 0) {
  103711. continue;
  103712. }
  103713. this._activeTargets.push(target);
  103714. this._tempInfluences[influenceCount++] = target.influence;
  103715. this._supportsNormals = this._supportsNormals && target.hasNormals;
  103716. this._supportsTangents = this._supportsTangents && target.hasTangents;
  103717. var positions = target.getPositions();
  103718. if (positions) {
  103719. var vertexCount = positions.length / 3;
  103720. if (this._vertexCount === 0) {
  103721. this._vertexCount = vertexCount;
  103722. }
  103723. else if (this._vertexCount !== vertexCount) {
  103724. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  103725. return;
  103726. }
  103727. }
  103728. }
  103729. if (!this._influences || this._influences.length !== influenceCount) {
  103730. this._influences = new Float32Array(influenceCount);
  103731. }
  103732. for (var index = 0; index < influenceCount; index++) {
  103733. this._influences[index] = this._tempInfluences[index];
  103734. }
  103735. if (needUpdate) {
  103736. this.synchronize();
  103737. }
  103738. };
  103739. /**
  103740. * Syncrhonize the targets with all the meshes using this morph target manager
  103741. */
  103742. MorphTargetManager.prototype.synchronize = function () {
  103743. if (!this._scene) {
  103744. return;
  103745. }
  103746. // Flag meshes as dirty to resync with the active targets
  103747. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  103748. var mesh = _a[_i];
  103749. if (mesh.morphTargetManager === this) {
  103750. mesh._syncGeometryWithMorphTargetManager();
  103751. }
  103752. }
  103753. };
  103754. // Statics
  103755. /**
  103756. * Creates a new MorphTargetManager from serialized data
  103757. * @param serializationObject defines the serialized data
  103758. * @param scene defines the hosting scene
  103759. * @returns the new MorphTargetManager
  103760. */
  103761. MorphTargetManager.Parse = function (serializationObject, scene) {
  103762. var result = new MorphTargetManager(scene);
  103763. result._uniqueId = serializationObject.id;
  103764. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  103765. var targetData = _a[_i];
  103766. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  103767. }
  103768. return result;
  103769. };
  103770. return MorphTargetManager;
  103771. }());
  103772. BABYLON.MorphTargetManager = MorphTargetManager;
  103773. })(BABYLON || (BABYLON = {}));
  103774. //# sourceMappingURL=babylon.morphTargetManager.js.map
  103775. var BABYLON;
  103776. (function (BABYLON) {
  103777. /**
  103778. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  103779. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  103780. */
  103781. var Octree = /** @class */ (function () {
  103782. /**
  103783. * Creates a octree
  103784. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  103785. * @param creationFunc function to be used to instatiate the octree
  103786. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  103787. * @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.)
  103788. */
  103789. function Octree(creationFunc, maxBlockCapacity,
  103790. /** 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.) */
  103791. maxDepth) {
  103792. if (maxDepth === void 0) { maxDepth = 2; }
  103793. this.maxDepth = maxDepth;
  103794. /**
  103795. * Content stored in the octree
  103796. */
  103797. this.dynamicContent = new Array();
  103798. this._maxBlockCapacity = maxBlockCapacity || 64;
  103799. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  103800. this._creationFunc = creationFunc;
  103801. }
  103802. // Methods
  103803. /**
  103804. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  103805. * @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);
  103806. * @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);
  103807. * @param entries meshes to be added to the octree blocks
  103808. */
  103809. Octree.prototype.update = function (worldMin, worldMax, entries) {
  103810. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  103811. };
  103812. /**
  103813. * Adds a mesh to the octree
  103814. * @param entry Mesh to add to the octree
  103815. */
  103816. Octree.prototype.addMesh = function (entry) {
  103817. for (var index = 0; index < this.blocks.length; index++) {
  103818. var block = this.blocks[index];
  103819. block.addEntry(entry);
  103820. }
  103821. };
  103822. /**
  103823. * Selects an array of meshes within the frustum
  103824. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  103825. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  103826. * @returns array of meshes within the frustum
  103827. */
  103828. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  103829. this._selectionContent.reset();
  103830. for (var index = 0; index < this.blocks.length; index++) {
  103831. var block = this.blocks[index];
  103832. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  103833. }
  103834. if (allowDuplicate) {
  103835. this._selectionContent.concat(this.dynamicContent);
  103836. }
  103837. else {
  103838. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  103839. }
  103840. return this._selectionContent;
  103841. };
  103842. /**
  103843. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  103844. * @param sphereCenter defines the bounding sphere center
  103845. * @param sphereRadius defines the bounding sphere radius
  103846. * @param allowDuplicate defines if the selection array can contains duplicated entries
  103847. * @returns an array of objects that intersect the sphere
  103848. */
  103849. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  103850. this._selectionContent.reset();
  103851. for (var index = 0; index < this.blocks.length; index++) {
  103852. var block = this.blocks[index];
  103853. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  103854. }
  103855. if (allowDuplicate) {
  103856. this._selectionContent.concat(this.dynamicContent);
  103857. }
  103858. else {
  103859. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  103860. }
  103861. return this._selectionContent;
  103862. };
  103863. /**
  103864. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  103865. * @param ray defines the ray to test with
  103866. * @returns array of intersected objects
  103867. */
  103868. Octree.prototype.intersectsRay = function (ray) {
  103869. this._selectionContent.reset();
  103870. for (var index = 0; index < this.blocks.length; index++) {
  103871. var block = this.blocks[index];
  103872. block.intersectsRay(ray, this._selectionContent);
  103873. }
  103874. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  103875. return this._selectionContent;
  103876. };
  103877. /**
  103878. * @hidden
  103879. */
  103880. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  103881. target.blocks = new Array();
  103882. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  103883. // Segmenting space
  103884. for (var x = 0; x < 2; x++) {
  103885. for (var y = 0; y < 2; y++) {
  103886. for (var z = 0; z < 2; z++) {
  103887. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  103888. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  103889. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  103890. block.addEntries(entries);
  103891. target.blocks.push(block);
  103892. }
  103893. }
  103894. }
  103895. };
  103896. /**
  103897. * Adds a mesh into the octree block if it intersects the block
  103898. */
  103899. Octree.CreationFuncForMeshes = function (entry, block) {
  103900. var boundingInfo = entry.getBoundingInfo();
  103901. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  103902. block.entries.push(entry);
  103903. }
  103904. };
  103905. /**
  103906. * Adds a submesh into the octree block if it intersects the block
  103907. */
  103908. Octree.CreationFuncForSubMeshes = function (entry, block) {
  103909. var boundingInfo = entry.getBoundingInfo();
  103910. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  103911. block.entries.push(entry);
  103912. }
  103913. };
  103914. return Octree;
  103915. }());
  103916. BABYLON.Octree = Octree;
  103917. })(BABYLON || (BABYLON = {}));
  103918. //# sourceMappingURL=babylon.octree.js.map
  103919. var BABYLON;
  103920. (function (BABYLON) {
  103921. /**
  103922. * Class used to store a cell in an octree
  103923. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  103924. */
  103925. var OctreeBlock = /** @class */ (function () {
  103926. /**
  103927. * Creates a new block
  103928. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  103929. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  103930. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  103931. * @param depth defines the current depth of this block in the octree
  103932. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  103933. * @param creationFunc defines a callback to call when an element is added to the block
  103934. */
  103935. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  103936. /**
  103937. * Gets the content of the current block
  103938. */
  103939. this.entries = new Array();
  103940. this._boundingVectors = new Array();
  103941. this._capacity = capacity;
  103942. this._depth = depth;
  103943. this._maxDepth = maxDepth;
  103944. this._creationFunc = creationFunc;
  103945. this._minPoint = minPoint;
  103946. this._maxPoint = maxPoint;
  103947. this._boundingVectors.push(minPoint.clone());
  103948. this._boundingVectors.push(maxPoint.clone());
  103949. this._boundingVectors.push(minPoint.clone());
  103950. this._boundingVectors[2].x = maxPoint.x;
  103951. this._boundingVectors.push(minPoint.clone());
  103952. this._boundingVectors[3].y = maxPoint.y;
  103953. this._boundingVectors.push(minPoint.clone());
  103954. this._boundingVectors[4].z = maxPoint.z;
  103955. this._boundingVectors.push(maxPoint.clone());
  103956. this._boundingVectors[5].z = minPoint.z;
  103957. this._boundingVectors.push(maxPoint.clone());
  103958. this._boundingVectors[6].x = minPoint.x;
  103959. this._boundingVectors.push(maxPoint.clone());
  103960. this._boundingVectors[7].y = minPoint.y;
  103961. }
  103962. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  103963. // Property
  103964. /**
  103965. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  103966. */
  103967. get: function () {
  103968. return this._capacity;
  103969. },
  103970. enumerable: true,
  103971. configurable: true
  103972. });
  103973. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  103974. /**
  103975. * Gets the minimum vector (in world space) of the block's bounding box
  103976. */
  103977. get: function () {
  103978. return this._minPoint;
  103979. },
  103980. enumerable: true,
  103981. configurable: true
  103982. });
  103983. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  103984. /**
  103985. * Gets the maximum vector (in world space) of the block's bounding box
  103986. */
  103987. get: function () {
  103988. return this._maxPoint;
  103989. },
  103990. enumerable: true,
  103991. configurable: true
  103992. });
  103993. // Methods
  103994. /**
  103995. * Add a new element to this block
  103996. * @param entry defines the element to add
  103997. */
  103998. OctreeBlock.prototype.addEntry = function (entry) {
  103999. if (this.blocks) {
  104000. for (var index = 0; index < this.blocks.length; index++) {
  104001. var block = this.blocks[index];
  104002. block.addEntry(entry);
  104003. }
  104004. return;
  104005. }
  104006. this._creationFunc(entry, this);
  104007. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  104008. this.createInnerBlocks();
  104009. }
  104010. };
  104011. /**
  104012. * Add an array of elements to this block
  104013. * @param entries defines the array of elements to add
  104014. */
  104015. OctreeBlock.prototype.addEntries = function (entries) {
  104016. for (var index = 0; index < entries.length; index++) {
  104017. var mesh = entries[index];
  104018. this.addEntry(mesh);
  104019. }
  104020. };
  104021. /**
  104022. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  104023. * @param frustumPlanes defines the frustum planes to test
  104024. * @param selection defines the array to store current content if selection is positive
  104025. * @param allowDuplicate defines if the selection array can contains duplicated entries
  104026. */
  104027. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  104028. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  104029. if (this.blocks) {
  104030. for (var index = 0; index < this.blocks.length; index++) {
  104031. var block = this.blocks[index];
  104032. block.select(frustumPlanes, selection, allowDuplicate);
  104033. }
  104034. return;
  104035. }
  104036. if (allowDuplicate) {
  104037. selection.concat(this.entries);
  104038. }
  104039. else {
  104040. selection.concatWithNoDuplicate(this.entries);
  104041. }
  104042. }
  104043. };
  104044. /**
  104045. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  104046. * @param sphereCenter defines the bounding sphere center
  104047. * @param sphereRadius defines the bounding sphere radius
  104048. * @param selection defines the array to store current content if selection is positive
  104049. * @param allowDuplicate defines if the selection array can contains duplicated entries
  104050. */
  104051. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  104052. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  104053. if (this.blocks) {
  104054. for (var index = 0; index < this.blocks.length; index++) {
  104055. var block = this.blocks[index];
  104056. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  104057. }
  104058. return;
  104059. }
  104060. if (allowDuplicate) {
  104061. selection.concat(this.entries);
  104062. }
  104063. else {
  104064. selection.concatWithNoDuplicate(this.entries);
  104065. }
  104066. }
  104067. };
  104068. /**
  104069. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  104070. * @param ray defines the ray to test with
  104071. * @param selection defines the array to store current content if selection is positive
  104072. */
  104073. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  104074. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  104075. if (this.blocks) {
  104076. for (var index = 0; index < this.blocks.length; index++) {
  104077. var block = this.blocks[index];
  104078. block.intersectsRay(ray, selection);
  104079. }
  104080. return;
  104081. }
  104082. selection.concatWithNoDuplicate(this.entries);
  104083. }
  104084. };
  104085. /**
  104086. * Subdivide the content into child blocks (this block will then be empty)
  104087. */
  104088. OctreeBlock.prototype.createInnerBlocks = function () {
  104089. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  104090. };
  104091. return OctreeBlock;
  104092. }());
  104093. BABYLON.OctreeBlock = OctreeBlock;
  104094. })(BABYLON || (BABYLON = {}));
  104095. //# sourceMappingURL=babylon.octreeBlock.js.map
  104096. var BABYLON;
  104097. (function (BABYLON) {
  104098. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  104099. if (maxCapacity === void 0) { maxCapacity = 64; }
  104100. if (maxDepth === void 0) { maxDepth = 2; }
  104101. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  104102. if (!component) {
  104103. component = new OctreeSceneComponent(this);
  104104. this._addComponent(component);
  104105. }
  104106. if (!this._selectionOctree) {
  104107. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  104108. }
  104109. var worldExtends = this.getWorldExtends();
  104110. // Update octree
  104111. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  104112. return this._selectionOctree;
  104113. };
  104114. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  104115. get: function () {
  104116. return this._selectionOctree;
  104117. },
  104118. enumerable: true,
  104119. configurable: true
  104120. });
  104121. /**
  104122. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  104123. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  104124. * @param maxCapacity defines the maximum size of each block (64 by default)
  104125. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  104126. * @returns the new octree
  104127. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  104128. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  104129. */
  104130. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  104131. if (maxCapacity === void 0) { maxCapacity = 64; }
  104132. if (maxDepth === void 0) { maxDepth = 2; }
  104133. var scene = this.getScene();
  104134. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  104135. if (!component) {
  104136. component = new OctreeSceneComponent(scene);
  104137. scene._addComponent(component);
  104138. }
  104139. if (!this._submeshesOctree) {
  104140. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  104141. }
  104142. this.computeWorldMatrix(true);
  104143. var boundingInfo = this.getBoundingInfo();
  104144. // Update octree
  104145. var bbox = boundingInfo.boundingBox;
  104146. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  104147. return this._submeshesOctree;
  104148. };
  104149. /**
  104150. * Defines the octree scene component responsible to manage any octrees
  104151. * in a given scene.
  104152. */
  104153. var OctreeSceneComponent = /** @class */ (function () {
  104154. /**
  104155. * Creates a new instance of the component for the given scene
  104156. * @param scene Defines the scene to register the component in
  104157. */
  104158. function OctreeSceneComponent(scene) {
  104159. /**
  104160. * The component name helpfull to identify the component in the list of scene components.
  104161. */
  104162. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  104163. /**
  104164. * Indicates if the meshes have been checked to make sure they are isEnabled()
  104165. */
  104166. this.checksIsEnabled = true;
  104167. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  104168. this.scene = scene;
  104169. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  104170. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  104171. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  104172. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  104173. }
  104174. /**
  104175. * Registers the component in a given scene
  104176. */
  104177. OctreeSceneComponent.prototype.register = function () {
  104178. var _this = this;
  104179. this.scene.onMeshRemovedObservable.add(function (mesh) {
  104180. var sceneOctree = _this.scene.selectionOctree;
  104181. if (sceneOctree !== undefined && sceneOctree !== null) {
  104182. var index = sceneOctree.dynamicContent.indexOf(mesh);
  104183. if (index !== -1) {
  104184. sceneOctree.dynamicContent.splice(index, 1);
  104185. }
  104186. }
  104187. });
  104188. this.scene.onMeshImportedObservable.add(function (mesh) {
  104189. var sceneOctree = _this.scene.selectionOctree;
  104190. if (sceneOctree !== undefined && sceneOctree !== null) {
  104191. sceneOctree.addMesh(mesh);
  104192. }
  104193. });
  104194. };
  104195. /**
  104196. * Return the list of active meshes
  104197. * @returns the list of active meshes
  104198. */
  104199. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  104200. if (this.scene._selectionOctree) {
  104201. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  104202. return selection;
  104203. }
  104204. return this.scene._getDefaultMeshCandidates();
  104205. };
  104206. /**
  104207. * Return the list of active sub meshes
  104208. * @param mesh The mesh to get the candidates sub meshes from
  104209. * @returns the list of active sub meshes
  104210. */
  104211. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  104212. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  104213. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  104214. return intersections;
  104215. }
  104216. return this.scene._getDefaultSubMeshCandidates(mesh);
  104217. };
  104218. /**
  104219. * Return the list of sub meshes intersecting with a given local ray
  104220. * @param mesh defines the mesh to find the submesh for
  104221. * @param localRay defines the ray in local space
  104222. * @returns the list of intersecting sub meshes
  104223. */
  104224. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  104225. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  104226. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  104227. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  104228. return intersections;
  104229. }
  104230. return this.scene._getDefaultSubMeshCandidates(mesh);
  104231. };
  104232. /**
  104233. * Return the list of sub meshes colliding with a collider
  104234. * @param mesh defines the mesh to find the submesh for
  104235. * @param collider defines the collider to evaluate the collision against
  104236. * @returns the list of colliding sub meshes
  104237. */
  104238. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  104239. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  104240. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  104241. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  104242. return intersections;
  104243. }
  104244. return this.scene._getDefaultSubMeshCandidates(mesh);
  104245. };
  104246. /**
  104247. * Rebuilds the elements related to this component in case of
  104248. * context lost for instance.
  104249. */
  104250. OctreeSceneComponent.prototype.rebuild = function () {
  104251. // Nothing to do here.
  104252. };
  104253. /**
  104254. * Disposes the component and the associated ressources.
  104255. */
  104256. OctreeSceneComponent.prototype.dispose = function () {
  104257. // Nothing to do here.
  104258. };
  104259. return OctreeSceneComponent;
  104260. }());
  104261. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  104262. })(BABYLON || (BABYLON = {}));
  104263. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  104264. var BABYLON;
  104265. (function (BABYLON) {
  104266. /**
  104267. * Postprocess used to generate anaglyphic rendering
  104268. */
  104269. var AnaglyphPostProcess = /** @class */ (function (_super) {
  104270. __extends(AnaglyphPostProcess, _super);
  104271. /**
  104272. * Creates a new AnaglyphPostProcess
  104273. * @param name defines postprocess name
  104274. * @param options defines creation options or target ratio scale
  104275. * @param rigCameras defines cameras using this postprocess
  104276. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  104277. * @param engine defines hosting engine
  104278. * @param reusable defines if the postprocess will be reused multiple times per frame
  104279. */
  104280. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  104281. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  104282. _this._passedProcess = rigCameras[0]._rigPostProcess;
  104283. _this.onApplyObservable.add(function (effect) {
  104284. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  104285. });
  104286. return _this;
  104287. }
  104288. return AnaglyphPostProcess;
  104289. }(BABYLON.PostProcess));
  104290. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  104291. })(BABYLON || (BABYLON = {}));
  104292. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  104293. var BABYLON;
  104294. (function (BABYLON) {
  104295. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  104296. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104297. });
  104298. /**
  104299. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  104300. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104301. */
  104302. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  104303. __extends(AnaglyphArcRotateCamera, _super);
  104304. /**
  104305. * Creates a new AnaglyphArcRotateCamera
  104306. * @param name defines camera name
  104307. * @param alpha defines alpha angle (in radians)
  104308. * @param beta defines beta angle (in radians)
  104309. * @param radius defines radius
  104310. * @param target defines camera target
  104311. * @param interaxialDistance defines distance between each color axis
  104312. * @param scene defines the hosting scene
  104313. */
  104314. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  104315. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104316. _this.interaxialDistance = interaxialDistance;
  104317. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104318. return _this;
  104319. }
  104320. /**
  104321. * Gets camera class name
  104322. * @returns AnaglyphArcRotateCamera
  104323. */
  104324. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  104325. return "AnaglyphArcRotateCamera";
  104326. };
  104327. return AnaglyphArcRotateCamera;
  104328. }(BABYLON.ArcRotateCamera));
  104329. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  104330. })(BABYLON || (BABYLON = {}));
  104331. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  104332. var BABYLON;
  104333. (function (BABYLON) {
  104334. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  104335. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104336. });
  104337. /**
  104338. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  104339. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104340. */
  104341. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  104342. __extends(AnaglyphFreeCamera, _super);
  104343. /**
  104344. * Creates a new AnaglyphFreeCamera
  104345. * @param name defines camera name
  104346. * @param position defines initial position
  104347. * @param interaxialDistance defines distance between each color axis
  104348. * @param scene defines the hosting scene
  104349. */
  104350. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  104351. var _this = _super.call(this, name, position, scene) || this;
  104352. _this.interaxialDistance = interaxialDistance;
  104353. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104354. return _this;
  104355. }
  104356. /**
  104357. * Gets camera class name
  104358. * @returns AnaglyphFreeCamera
  104359. */
  104360. AnaglyphFreeCamera.prototype.getClassName = function () {
  104361. return "AnaglyphFreeCamera";
  104362. };
  104363. return AnaglyphFreeCamera;
  104364. }(BABYLON.FreeCamera));
  104365. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  104366. })(BABYLON || (BABYLON = {}));
  104367. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  104368. var BABYLON;
  104369. (function (BABYLON) {
  104370. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  104371. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104372. });
  104373. /**
  104374. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  104375. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104376. */
  104377. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  104378. __extends(AnaglyphGamepadCamera, _super);
  104379. /**
  104380. * Creates a new AnaglyphGamepadCamera
  104381. * @param name defines camera name
  104382. * @param position defines initial position
  104383. * @param interaxialDistance defines distance between each color axis
  104384. * @param scene defines the hosting scene
  104385. */
  104386. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  104387. var _this = _super.call(this, name, position, scene) || this;
  104388. _this.interaxialDistance = interaxialDistance;
  104389. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104390. return _this;
  104391. }
  104392. /**
  104393. * Gets camera class name
  104394. * @returns AnaglyphGamepadCamera
  104395. */
  104396. AnaglyphGamepadCamera.prototype.getClassName = function () {
  104397. return "AnaglyphGamepadCamera";
  104398. };
  104399. return AnaglyphGamepadCamera;
  104400. }(BABYLON.GamepadCamera));
  104401. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  104402. })(BABYLON || (BABYLON = {}));
  104403. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  104404. var BABYLON;
  104405. (function (BABYLON) {
  104406. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  104407. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104408. });
  104409. /**
  104410. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  104411. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104412. */
  104413. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  104414. __extends(AnaglyphUniversalCamera, _super);
  104415. /**
  104416. * Creates a new AnaglyphUniversalCamera
  104417. * @param name defines camera name
  104418. * @param position defines initial position
  104419. * @param interaxialDistance defines distance between each color axis
  104420. * @param scene defines the hosting scene
  104421. */
  104422. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  104423. var _this = _super.call(this, name, position, scene) || this;
  104424. _this.interaxialDistance = interaxialDistance;
  104425. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104426. return _this;
  104427. }
  104428. /**
  104429. * Gets camera class name
  104430. * @returns AnaglyphUniversalCamera
  104431. */
  104432. AnaglyphUniversalCamera.prototype.getClassName = function () {
  104433. return "AnaglyphUniversalCamera";
  104434. };
  104435. return AnaglyphUniversalCamera;
  104436. }(BABYLON.UniversalCamera));
  104437. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  104438. })(BABYLON || (BABYLON = {}));
  104439. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  104440. var BABYLON;
  104441. (function (BABYLON) {
  104442. /**
  104443. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  104444. */
  104445. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  104446. __extends(StereoscopicInterlacePostProcess, _super);
  104447. /**
  104448. * Initializes a StereoscopicInterlacePostProcess
  104449. * @param name The name of the effect.
  104450. * @param rigCameras The rig cameras to be appled to the post process
  104451. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  104452. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  104453. * @param engine The engine which the post process will be applied. (default: current engine)
  104454. * @param reusable If the post process can be reused on the same frame. (default: false)
  104455. */
  104456. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  104457. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  104458. _this._passedProcess = rigCameras[0]._rigPostProcess;
  104459. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  104460. _this.onSizeChangedObservable.add(function () {
  104461. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  104462. });
  104463. _this.onApplyObservable.add(function (effect) {
  104464. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  104465. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  104466. });
  104467. return _this;
  104468. }
  104469. return StereoscopicInterlacePostProcess;
  104470. }(BABYLON.PostProcess));
  104471. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  104472. })(BABYLON || (BABYLON = {}));
  104473. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  104474. var BABYLON;
  104475. (function (BABYLON) {
  104476. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  104477. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104478. });
  104479. /**
  104480. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  104481. * @see http://doc.babylonjs.com/features/cameras
  104482. */
  104483. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  104484. __extends(StereoscopicArcRotateCamera, _super);
  104485. /**
  104486. * Creates a new StereoscopicArcRotateCamera
  104487. * @param name defines camera name
  104488. * @param alpha defines alpha angle (in radians)
  104489. * @param beta defines beta angle (in radians)
  104490. * @param radius defines radius
  104491. * @param target defines camera target
  104492. * @param interaxialDistance defines distance between each color axis
  104493. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104494. * @param scene defines the hosting scene
  104495. */
  104496. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  104497. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104498. _this.interaxialDistance = interaxialDistance;
  104499. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104500. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104501. return _this;
  104502. }
  104503. /**
  104504. * Gets camera class name
  104505. * @returns StereoscopicArcRotateCamera
  104506. */
  104507. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  104508. return "StereoscopicArcRotateCamera";
  104509. };
  104510. return StereoscopicArcRotateCamera;
  104511. }(BABYLON.ArcRotateCamera));
  104512. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  104513. })(BABYLON || (BABYLON = {}));
  104514. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  104515. var BABYLON;
  104516. (function (BABYLON) {
  104517. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  104518. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104519. });
  104520. /**
  104521. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  104522. * @see http://doc.babylonjs.com/features/cameras
  104523. */
  104524. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  104525. __extends(StereoscopicFreeCamera, _super);
  104526. /**
  104527. * Creates a new StereoscopicFreeCamera
  104528. * @param name defines camera name
  104529. * @param position defines initial position
  104530. * @param interaxialDistance defines distance between each color axis
  104531. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104532. * @param scene defines the hosting scene
  104533. */
  104534. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104535. var _this = _super.call(this, name, position, scene) || this;
  104536. _this.interaxialDistance = interaxialDistance;
  104537. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104538. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104539. return _this;
  104540. }
  104541. /**
  104542. * Gets camera class name
  104543. * @returns StereoscopicFreeCamera
  104544. */
  104545. StereoscopicFreeCamera.prototype.getClassName = function () {
  104546. return "StereoscopicFreeCamera";
  104547. };
  104548. return StereoscopicFreeCamera;
  104549. }(BABYLON.FreeCamera));
  104550. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  104551. })(BABYLON || (BABYLON = {}));
  104552. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  104553. var BABYLON;
  104554. (function (BABYLON) {
  104555. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  104556. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104557. });
  104558. /**
  104559. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  104560. * @see http://doc.babylonjs.com/features/cameras
  104561. */
  104562. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  104563. __extends(StereoscopicGamepadCamera, _super);
  104564. /**
  104565. * Creates a new StereoscopicGamepadCamera
  104566. * @param name defines camera name
  104567. * @param position defines initial position
  104568. * @param interaxialDistance defines distance between each color axis
  104569. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104570. * @param scene defines the hosting scene
  104571. */
  104572. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104573. var _this = _super.call(this, name, position, scene) || this;
  104574. _this.interaxialDistance = interaxialDistance;
  104575. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104576. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104577. return _this;
  104578. }
  104579. /**
  104580. * Gets camera class name
  104581. * @returns StereoscopicGamepadCamera
  104582. */
  104583. StereoscopicGamepadCamera.prototype.getClassName = function () {
  104584. return "StereoscopicGamepadCamera";
  104585. };
  104586. return StereoscopicGamepadCamera;
  104587. }(BABYLON.GamepadCamera));
  104588. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  104589. })(BABYLON || (BABYLON = {}));
  104590. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  104591. var BABYLON;
  104592. (function (BABYLON) {
  104593. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  104594. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104595. });
  104596. /**
  104597. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  104598. * @see http://doc.babylonjs.com/features/cameras
  104599. */
  104600. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  104601. __extends(StereoscopicUniversalCamera, _super);
  104602. /**
  104603. * Creates a new StereoscopicUniversalCamera
  104604. * @param name defines camera name
  104605. * @param position defines initial position
  104606. * @param interaxialDistance defines distance between each color axis
  104607. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104608. * @param scene defines the hosting scene
  104609. */
  104610. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104611. var _this = _super.call(this, name, position, scene) || this;
  104612. _this.interaxialDistance = interaxialDistance;
  104613. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104614. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104615. return _this;
  104616. }
  104617. /**
  104618. * Gets camera class name
  104619. * @returns StereoscopicUniversalCamera
  104620. */
  104621. StereoscopicUniversalCamera.prototype.getClassName = function () {
  104622. return "StereoscopicUniversalCamera";
  104623. };
  104624. return StereoscopicUniversalCamera;
  104625. }(BABYLON.UniversalCamera));
  104626. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  104627. })(BABYLON || (BABYLON = {}));
  104628. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  104629. var BABYLON;
  104630. (function (BABYLON) {
  104631. /**
  104632. * VRDistortionCorrectionPostProcess used for mobile VR
  104633. */
  104634. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  104635. __extends(VRDistortionCorrectionPostProcess, _super);
  104636. /**
  104637. * Initializes the VRDistortionCorrectionPostProcess
  104638. * @param name The name of the effect.
  104639. * @param camera The camera to apply the render pass to.
  104640. * @param isRightEye If this is for the right eye distortion
  104641. * @param vrMetrics All the required metrics for the VR camera
  104642. */
  104643. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  104644. var _this = _super.call(this, name, "vrDistortionCorrection", [
  104645. 'LensCenter',
  104646. 'Scale',
  104647. 'ScaleIn',
  104648. 'HmdWarpParam'
  104649. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  104650. _this._isRightEye = isRightEye;
  104651. _this._distortionFactors = vrMetrics.distortionK;
  104652. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  104653. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  104654. _this.adaptScaleToCurrentViewport = true;
  104655. _this.onSizeChangedObservable.add(function () {
  104656. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  104657. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  104658. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  104659. });
  104660. _this.onApplyObservable.add(function (effect) {
  104661. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  104662. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  104663. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  104664. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  104665. });
  104666. return _this;
  104667. }
  104668. return VRDistortionCorrectionPostProcess;
  104669. }(BABYLON.PostProcess));
  104670. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  104671. })(BABYLON || (BABYLON = {}));
  104672. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  104673. var BABYLON;
  104674. (function (BABYLON) {
  104675. /**
  104676. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  104677. * Screen rotation is taken into account.
  104678. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104679. */
  104680. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  104681. /**
  104682. * Instantiates a new input
  104683. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104684. */
  104685. function FreeCameraDeviceOrientationInput() {
  104686. var _this = this;
  104687. this._screenOrientationAngle = 0;
  104688. this._screenQuaternion = new BABYLON.Quaternion();
  104689. this._alpha = 0;
  104690. this._beta = 0;
  104691. this._gamma = 0;
  104692. this._orientationChanged = function () {
  104693. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && (window.screen.orientation)['angle'] ? (window.screen.orientation).angle : 0));
  104694. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  104695. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  104696. };
  104697. this._deviceOrientation = function (evt) {
  104698. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  104699. _this._beta = evt.beta !== null ? evt.beta : 0;
  104700. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  104701. };
  104702. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  104703. this._orientationChanged();
  104704. }
  104705. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  104706. /**
  104707. * Define the camera controlled by the input.
  104708. */
  104709. get: function () {
  104710. return this._camera;
  104711. },
  104712. set: function (camera) {
  104713. this._camera = camera;
  104714. if (this._camera != null && !this._camera.rotationQuaternion) {
  104715. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  104716. }
  104717. },
  104718. enumerable: true,
  104719. configurable: true
  104720. });
  104721. /**
  104722. * Attach the input controls to a specific dom element to get the input from.
  104723. * @param element Defines the element the controls should be listened from
  104724. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  104725. */
  104726. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  104727. window.addEventListener("orientationchange", this._orientationChanged);
  104728. window.addEventListener("deviceorientation", this._deviceOrientation);
  104729. //In certain cases, the attach control is called AFTER orientation was changed,
  104730. //So this is needed.
  104731. this._orientationChanged();
  104732. };
  104733. /**
  104734. * Detach the current controls from the specified dom element.
  104735. * @param element Defines the element to stop listening the inputs from
  104736. */
  104737. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  104738. window.removeEventListener("orientationchange", this._orientationChanged);
  104739. window.removeEventListener("deviceorientation", this._deviceOrientation);
  104740. };
  104741. /**
  104742. * Update the current camera state depending on the inputs that have been used this frame.
  104743. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  104744. */
  104745. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  104746. //if no device orientation provided, don't update the rotation.
  104747. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  104748. if (!this._alpha) {
  104749. return;
  104750. }
  104751. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  104752. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  104753. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  104754. //Mirror on XY Plane
  104755. this._camera.rotationQuaternion.z *= -1;
  104756. this._camera.rotationQuaternion.w *= -1;
  104757. };
  104758. /**
  104759. * Gets the class name of the current intput.
  104760. * @returns the class name
  104761. */
  104762. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  104763. return "FreeCameraDeviceOrientationInput";
  104764. };
  104765. /**
  104766. * Get the friendly name associated with the input class.
  104767. * @returns the input friendly name
  104768. */
  104769. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  104770. return "deviceOrientation";
  104771. };
  104772. return FreeCameraDeviceOrientationInput;
  104773. }());
  104774. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  104775. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  104776. })(BABYLON || (BABYLON = {}));
  104777. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  104778. var BABYLON;
  104779. (function (BABYLON) {
  104780. /**
  104781. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  104782. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104783. */
  104784. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  104785. /**
  104786. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  104787. */
  104788. function ArcRotateCameraVRDeviceOrientationInput() {
  104789. /**
  104790. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  104791. */
  104792. this.alphaCorrection = 1;
  104793. /**
  104794. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  104795. */
  104796. this.gammaCorrection = 1;
  104797. this._alpha = 0;
  104798. this._gamma = 0;
  104799. this._dirty = false;
  104800. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  104801. }
  104802. /**
  104803. * Attach the input controls to a specific dom element to get the input from.
  104804. * @param element Defines the element the controls should be listened from
  104805. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  104806. */
  104807. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  104808. this.camera.attachControl(element, noPreventDefault);
  104809. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  104810. };
  104811. /** @hidden */
  104812. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  104813. if (evt.alpha !== null) {
  104814. this._alpha = (+evt.alpha | 0) * this.alphaCorrection;
  104815. }
  104816. if (evt.gamma !== null) {
  104817. this._gamma = (+evt.gamma | 0) * this.gammaCorrection;
  104818. }
  104819. this._dirty = true;
  104820. };
  104821. /**
  104822. * Update the current camera state depending on the inputs that have been used this frame.
  104823. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  104824. */
  104825. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  104826. if (this._dirty) {
  104827. this._dirty = false;
  104828. if (this._gamma < 0) {
  104829. this._gamma = 180 + this._gamma;
  104830. }
  104831. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  104832. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  104833. }
  104834. };
  104835. /**
  104836. * Detach the current controls from the specified dom element.
  104837. * @param element Defines the element to stop listening the inputs from
  104838. */
  104839. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  104840. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  104841. };
  104842. /**
  104843. * Gets the class name of the current intput.
  104844. * @returns the class name
  104845. */
  104846. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  104847. return "ArcRotateCameraVRDeviceOrientationInput";
  104848. };
  104849. /**
  104850. * Get the friendly name associated with the input class.
  104851. * @returns the input friendly name
  104852. */
  104853. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  104854. return "VRDeviceOrientation";
  104855. };
  104856. return ArcRotateCameraVRDeviceOrientationInput;
  104857. }());
  104858. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  104859. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  104860. })(BABYLON || (BABYLON = {}));
  104861. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  104862. var BABYLON;
  104863. (function (BABYLON) {
  104864. /**
  104865. * This represents all the required metrics to create a VR camera.
  104866. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  104867. */
  104868. var VRCameraMetrics = /** @class */ (function () {
  104869. function VRCameraMetrics() {
  104870. /**
  104871. * Define if the current vr camera should compensate the distortion of the lense or not.
  104872. */
  104873. this.compensateDistortion = true;
  104874. }
  104875. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  104876. /**
  104877. * Gets the rendering aspect ratio based on the provided resolutions.
  104878. */
  104879. get: function () {
  104880. return this.hResolution / (2 * this.vResolution);
  104881. },
  104882. enumerable: true,
  104883. configurable: true
  104884. });
  104885. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  104886. /**
  104887. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  104888. */
  104889. get: function () {
  104890. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  104891. },
  104892. enumerable: true,
  104893. configurable: true
  104894. });
  104895. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  104896. /**
  104897. * @hidden
  104898. */
  104899. get: function () {
  104900. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  104901. var h = (4 * meters) / this.hScreenSize;
  104902. return BABYLON.Matrix.Translation(h, 0, 0);
  104903. },
  104904. enumerable: true,
  104905. configurable: true
  104906. });
  104907. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  104908. /**
  104909. * @hidden
  104910. */
  104911. get: function () {
  104912. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  104913. var h = (4 * meters) / this.hScreenSize;
  104914. return BABYLON.Matrix.Translation(-h, 0, 0);
  104915. },
  104916. enumerable: true,
  104917. configurable: true
  104918. });
  104919. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  104920. /**
  104921. * @hidden
  104922. */
  104923. get: function () {
  104924. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  104925. },
  104926. enumerable: true,
  104927. configurable: true
  104928. });
  104929. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  104930. /**
  104931. * @hidden
  104932. */
  104933. get: function () {
  104934. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  104935. },
  104936. enumerable: true,
  104937. configurable: true
  104938. });
  104939. /**
  104940. * Get the default VRMetrics based on the most generic setup.
  104941. * @returns the default vr metrics
  104942. */
  104943. VRCameraMetrics.GetDefault = function () {
  104944. var result = new VRCameraMetrics();
  104945. result.hResolution = 1280;
  104946. result.vResolution = 800;
  104947. result.hScreenSize = 0.149759993;
  104948. result.vScreenSize = 0.0935999975;
  104949. result.vScreenCenter = 0.0467999987;
  104950. result.eyeToScreenDistance = 0.0410000011;
  104951. result.lensSeparationDistance = 0.0635000020;
  104952. result.interpupillaryDistance = 0.0640000030;
  104953. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  104954. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  104955. result.postProcessScaleFactor = 1.714605507808412;
  104956. result.lensCenterOffset = 0.151976421;
  104957. return result;
  104958. };
  104959. return VRCameraMetrics;
  104960. }());
  104961. BABYLON.VRCameraMetrics = VRCameraMetrics;
  104962. })(BABYLON || (BABYLON = {}));
  104963. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  104964. var BABYLON;
  104965. (function (BABYLON) {
  104966. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  104967. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  104968. });
  104969. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  104970. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  104971. });
  104972. /**
  104973. * This represents a WebVR camera.
  104974. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  104975. * @example http://doc.babylonjs.com/how_to/webvr_camera
  104976. */
  104977. var WebVRFreeCamera = /** @class */ (function (_super) {
  104978. __extends(WebVRFreeCamera, _super);
  104979. /**
  104980. * Instantiates a WebVRFreeCamera.
  104981. * @param name The name of the WebVRFreeCamera
  104982. * @param position The starting anchor position for the camera
  104983. * @param scene The scene the camera belongs to
  104984. * @param webVROptions a set of customizable options for the webVRCamera
  104985. */
  104986. function WebVRFreeCamera(name, position, scene, webVROptions) {
  104987. if (webVROptions === void 0) { webVROptions = {}; }
  104988. var _this = _super.call(this, name, position, scene) || this;
  104989. _this.webVROptions = webVROptions;
  104990. /**
  104991. * @hidden
  104992. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  104993. */
  104994. _this._vrDevice = null;
  104995. /**
  104996. * The rawPose of the vrDevice.
  104997. */
  104998. _this.rawPose = null;
  104999. _this._specsVersion = "1.1";
  105000. _this._attached = false;
  105001. _this._descendants = [];
  105002. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  105003. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  105004. /** @hidden */
  105005. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  105006. _this._standingMatrix = null;
  105007. /**
  105008. * Represents device position in babylon space.
  105009. */
  105010. _this.devicePosition = BABYLON.Vector3.Zero();
  105011. /**
  105012. * Represents device rotation in babylon space.
  105013. */
  105014. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  105015. /**
  105016. * The scale of the device to be used when translating from device space to babylon space.
  105017. */
  105018. _this.deviceScaleFactor = 1;
  105019. _this._deviceToWorld = BABYLON.Matrix.Identity();
  105020. _this._worldToDevice = BABYLON.Matrix.Identity();
  105021. /**
  105022. * References to the webVR controllers for the vrDevice.
  105023. */
  105024. _this.controllers = [];
  105025. /**
  105026. * Emits an event when a controller is attached.
  105027. */
  105028. _this.onControllersAttachedObservable = new BABYLON.Observable();
  105029. /**
  105030. * Emits an event when a controller's mesh has been loaded;
  105031. */
  105032. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  105033. /**
  105034. * Emits an event when the HMD's pose has been updated.
  105035. */
  105036. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  105037. _this._poseSet = false;
  105038. /**
  105039. * If the rig cameras be used as parent instead of this camera.
  105040. */
  105041. _this.rigParenting = true;
  105042. _this._defaultHeight = undefined;
  105043. _this._htmlElementAttached = null;
  105044. _this._detachIfAttached = function () {
  105045. var vrDisplay = _this.getEngine().getVRDevice();
  105046. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  105047. _this.detachControl(_this._htmlElementAttached);
  105048. }
  105049. };
  105050. _this._workingVector = BABYLON.Vector3.Zero();
  105051. _this._oneVector = BABYLON.Vector3.One();
  105052. _this._workingMatrix = BABYLON.Matrix.Identity();
  105053. _this._tmpMatrix = new BABYLON.Matrix();
  105054. _this._cache.position = BABYLON.Vector3.Zero();
  105055. if (webVROptions.defaultHeight) {
  105056. _this._defaultHeight = webVROptions.defaultHeight;
  105057. _this.position.y = _this._defaultHeight;
  105058. }
  105059. _this.minZ = 0.1;
  105060. //legacy support - the compensation boolean was removed.
  105061. if (arguments.length === 5) {
  105062. _this.webVROptions = arguments[4];
  105063. }
  105064. // default webVR options
  105065. if (_this.webVROptions.trackPosition == undefined) {
  105066. _this.webVROptions.trackPosition = true;
  105067. }
  105068. if (_this.webVROptions.controllerMeshes == undefined) {
  105069. _this.webVROptions.controllerMeshes = true;
  105070. }
  105071. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  105072. _this.webVROptions.defaultLightingOnControllers = true;
  105073. }
  105074. _this.rotationQuaternion = new BABYLON.Quaternion();
  105075. if (_this.webVROptions && _this.webVROptions.positionScale) {
  105076. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  105077. }
  105078. //enable VR
  105079. var engine = _this.getEngine();
  105080. _this._onVREnabled = function (success) { if (success) {
  105081. _this.initControllers();
  105082. } };
  105083. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  105084. engine.initWebVR().add(function (event) {
  105085. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  105086. return;
  105087. }
  105088. _this._vrDevice = event.vrDisplay;
  105089. //reset the rig parameters.
  105090. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  105091. if (_this._attached) {
  105092. _this.getEngine().enableVR();
  105093. }
  105094. });
  105095. if (typeof (VRFrameData) !== "undefined") {
  105096. _this._frameData = new VRFrameData();
  105097. }
  105098. /**
  105099. * The idea behind the following lines:
  105100. * objects that have the camera as parent should actually have the rig cameras as a parent.
  105101. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  105102. * the second will not show it correctly.
  105103. *
  105104. * To solve this - each object that has the camera as parent will be added to a protected array.
  105105. * When the rig camera renders, it will take this array and set all of those to be its children.
  105106. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  105107. * Amazing!
  105108. */
  105109. scene.onBeforeCameraRenderObservable.add(function (camera) {
  105110. if (camera.parent === _this && _this.rigParenting) {
  105111. _this._descendants = _this.getDescendants(true, function (n) {
  105112. // don't take the cameras or the controllers!
  105113. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  105114. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  105115. return !isController && !isRigCamera;
  105116. });
  105117. _this._descendants.forEach(function (node) {
  105118. node.parent = camera;
  105119. });
  105120. }
  105121. });
  105122. scene.onAfterCameraRenderObservable.add(function (camera) {
  105123. if (camera.parent === _this && _this.rigParenting) {
  105124. _this._descendants.forEach(function (node) {
  105125. node.parent = _this;
  105126. });
  105127. }
  105128. });
  105129. return _this;
  105130. }
  105131. /**
  105132. * Gets the device distance from the ground in meters.
  105133. * @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.
  105134. */
  105135. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  105136. if (this._standingMatrix) {
  105137. // Add standing matrix offset to get real offset from ground in room
  105138. this._standingMatrix.getTranslationToRef(this._workingVector);
  105139. return this._deviceRoomPosition.y + this._workingVector.y;
  105140. }
  105141. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  105142. return this._defaultHeight || 0;
  105143. };
  105144. /**
  105145. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  105146. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  105147. */
  105148. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  105149. var _this = this;
  105150. if (callback === void 0) { callback = function (bool) { }; }
  105151. // Use standing matrix if available
  105152. this.getEngine().initWebVRAsync().then(function (result) {
  105153. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  105154. callback(false);
  105155. }
  105156. else {
  105157. _this._standingMatrix = new BABYLON.Matrix();
  105158. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  105159. if (!_this.getScene().useRightHandedSystem) {
  105160. if (_this._standingMatrix) {
  105161. _this._standingMatrix.toggleModelMatrixHandInPlace();
  105162. }
  105163. }
  105164. callback(true);
  105165. }
  105166. });
  105167. };
  105168. /**
  105169. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  105170. * @returns A promise with a boolean set to if the standing matrix is supported.
  105171. */
  105172. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  105173. var _this = this;
  105174. return new Promise(function (res, rej) {
  105175. _this.useStandingMatrix(function (supported) {
  105176. res(supported);
  105177. });
  105178. });
  105179. };
  105180. /**
  105181. * Disposes the camera
  105182. */
  105183. WebVRFreeCamera.prototype.dispose = function () {
  105184. this._detachIfAttached();
  105185. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  105186. if (this._updateCacheWhenTrackingDisabledObserver) {
  105187. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  105188. }
  105189. _super.prototype.dispose.call(this);
  105190. };
  105191. /**
  105192. * Gets a vrController by name.
  105193. * @param name The name of the controller to retreive
  105194. * @returns the controller matching the name specified or null if not found
  105195. */
  105196. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  105197. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  105198. var gp = _a[_i];
  105199. if (gp.hand === name) {
  105200. return gp;
  105201. }
  105202. }
  105203. return null;
  105204. };
  105205. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  105206. /**
  105207. * The controller corrisponding to the users left hand.
  105208. */
  105209. get: function () {
  105210. if (!this._leftController) {
  105211. this._leftController = this.getControllerByName("left");
  105212. }
  105213. return this._leftController;
  105214. },
  105215. enumerable: true,
  105216. configurable: true
  105217. });
  105218. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  105219. /**
  105220. * The controller corrisponding to the users right hand.
  105221. */
  105222. get: function () {
  105223. if (!this._rightController) {
  105224. this._rightController = this.getControllerByName("right");
  105225. }
  105226. return this._rightController;
  105227. },
  105228. enumerable: true,
  105229. configurable: true
  105230. });
  105231. /**
  105232. * Casts a ray forward from the vrCamera's gaze.
  105233. * @param length Length of the ray (default: 100)
  105234. * @returns the ray corrisponding to the gaze
  105235. */
  105236. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  105237. if (length === void 0) { length = 100; }
  105238. if (this.leftCamera) {
  105239. // Use left eye to avoid computation to compute center on every call
  105240. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  105241. }
  105242. else {
  105243. return _super.prototype.getForwardRay.call(this, length);
  105244. }
  105245. };
  105246. /**
  105247. * @hidden
  105248. * Updates the camera based on device's frame data
  105249. */
  105250. WebVRFreeCamera.prototype._checkInputs = function () {
  105251. if (this._vrDevice && this._vrDevice.isPresenting) {
  105252. this._vrDevice.getFrameData(this._frameData);
  105253. this.updateFromDevice(this._frameData.pose);
  105254. }
  105255. _super.prototype._checkInputs.call(this);
  105256. };
  105257. /**
  105258. * Updates the poseControlled values based on the input device pose.
  105259. * @param poseData Pose coming from the device
  105260. */
  105261. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  105262. if (poseData && poseData.orientation) {
  105263. this.rawPose = poseData;
  105264. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  105265. if (this.getScene().useRightHandedSystem) {
  105266. this._deviceRoomRotationQuaternion.z *= -1;
  105267. this._deviceRoomRotationQuaternion.w *= -1;
  105268. }
  105269. if (this.webVROptions.trackPosition && this.rawPose.position) {
  105270. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  105271. if (this.getScene().useRightHandedSystem) {
  105272. this._deviceRoomPosition.z *= -1;
  105273. }
  105274. }
  105275. this._poseSet = true;
  105276. }
  105277. };
  105278. /**
  105279. * WebVR's attach control will start broadcasting frames to the device.
  105280. * Note that in certain browsers (chrome for example) this function must be called
  105281. * within a user-interaction callback. Example:
  105282. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  105283. *
  105284. * @param element html element to attach the vrDevice to
  105285. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  105286. */
  105287. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  105288. _super.prototype.attachControl.call(this, element, noPreventDefault);
  105289. this._attached = true;
  105290. this._htmlElementAttached = element;
  105291. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  105292. if (this._vrDevice) {
  105293. this.getEngine().enableVR();
  105294. }
  105295. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  105296. };
  105297. /**
  105298. * Detaches the camera from the html element and disables VR
  105299. *
  105300. * @param element html element to detach from
  105301. */
  105302. WebVRFreeCamera.prototype.detachControl = function (element) {
  105303. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  105304. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  105305. _super.prototype.detachControl.call(this, element);
  105306. this._attached = false;
  105307. this.getEngine().disableVR();
  105308. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  105309. };
  105310. /**
  105311. * @returns the name of this class
  105312. */
  105313. WebVRFreeCamera.prototype.getClassName = function () {
  105314. return "WebVRFreeCamera";
  105315. };
  105316. /**
  105317. * Calls resetPose on the vrDisplay
  105318. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  105319. */
  105320. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  105321. //uses the vrDisplay's "resetPose()".
  105322. //pitch and roll won't be affected.
  105323. this._vrDevice.resetPose();
  105324. };
  105325. /**
  105326. * @hidden
  105327. * Updates the rig cameras (left and right eye)
  105328. */
  105329. WebVRFreeCamera.prototype._updateRigCameras = function () {
  105330. var camLeft = this._rigCameras[0];
  105331. var camRight = this._rigCameras[1];
  105332. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  105333. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  105334. camLeft.position.copyFrom(this._deviceRoomPosition);
  105335. camRight.position.copyFrom(this._deviceRoomPosition);
  105336. };
  105337. // Remove translation from 6dof headset if trackposition is set to false
  105338. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  105339. if (isViewMatrix === void 0) { isViewMatrix = false; }
  105340. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  105341. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  105342. if (!isViewMatrix) {
  105343. this._tmpMatrix.invert();
  105344. }
  105345. this._tmpMatrix.multiplyToRef(matrix, matrix);
  105346. }
  105347. };
  105348. /**
  105349. * @hidden
  105350. * Updates the cached values of the camera
  105351. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  105352. */
  105353. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  105354. var _this = this;
  105355. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  105356. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  105357. if (!this.updateCacheCalled) {
  105358. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  105359. this.updateCacheCalled = true;
  105360. this.update();
  105361. }
  105362. // Set working vector to the device position in room space rotated by the new rotation
  105363. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  105364. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  105365. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  105366. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  105367. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  105368. // Add translation from anchor position
  105369. this._deviceToWorld.getTranslationToRef(this._workingVector);
  105370. this._workingVector.addInPlace(this.position);
  105371. this._workingVector.subtractInPlace(this._cache.position);
  105372. this._deviceToWorld.setTranslation(this._workingVector);
  105373. // Set an inverted matrix to be used when updating the camera
  105374. this._deviceToWorld.invertToRef(this._worldToDevice);
  105375. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  105376. this.controllers.forEach(function (controller) {
  105377. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  105378. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  105379. controller.update();
  105380. });
  105381. }
  105382. if (!ignoreParentClass) {
  105383. _super.prototype._updateCache.call(this);
  105384. }
  105385. this.updateCacheCalled = false;
  105386. };
  105387. /**
  105388. * @hidden
  105389. * Get current device position in babylon world
  105390. */
  105391. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  105392. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  105393. };
  105394. /**
  105395. * Updates the current device position and rotation in the babylon world
  105396. */
  105397. WebVRFreeCamera.prototype.update = function () {
  105398. this._computeDevicePosition();
  105399. // Get current device rotation in babylon world
  105400. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  105401. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  105402. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  105403. if (this._poseSet) {
  105404. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  105405. }
  105406. _super.prototype.update.call(this);
  105407. };
  105408. /**
  105409. * @hidden
  105410. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  105411. * @returns an identity matrix
  105412. */
  105413. WebVRFreeCamera.prototype._getViewMatrix = function () {
  105414. return BABYLON.Matrix.Identity();
  105415. };
  105416. /**
  105417. * This function is called by the two RIG cameras.
  105418. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  105419. */
  105420. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  105421. // Update the parent camera prior to using a child camera to avoid desynchronization
  105422. var parentCamera = this._cameraRigParams["parentCamera"];
  105423. parentCamera._updateCache();
  105424. //WebVR 1.1
  105425. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  105426. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  105427. if (!this.getScene().useRightHandedSystem) {
  105428. this._webvrViewMatrix.toggleModelMatrixHandInPlace();
  105429. }
  105430. // update the camera rotation matrix
  105431. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  105432. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  105433. // Computing target and final matrix
  105434. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  105435. // should the view matrix be updated with scale and position offset?
  105436. if (parentCamera.deviceScaleFactor !== 1) {
  105437. this._webvrViewMatrix.invert();
  105438. // scale the position, if set
  105439. if (parentCamera.deviceScaleFactor) {
  105440. this._webvrViewMatrix.multiplyAtIndex(12, parentCamera.deviceScaleFactor);
  105441. this._webvrViewMatrix.multiplyAtIndex(13, parentCamera.deviceScaleFactor);
  105442. this._webvrViewMatrix.multiplyAtIndex(14, parentCamera.deviceScaleFactor);
  105443. }
  105444. this._webvrViewMatrix.invert();
  105445. }
  105446. // Remove translation from 6dof headset if trackposition is set to false
  105447. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  105448. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  105449. // Compute global position
  105450. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  105451. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  105452. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  105453. this._workingMatrix.getTranslationToRef(this._globalPosition);
  105454. this._markSyncedWithParent();
  105455. return this._webvrViewMatrix;
  105456. };
  105457. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  105458. var parentCamera = this.parent;
  105459. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  105460. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  105461. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  105462. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  105463. //babylon compatible matrix
  105464. if (!this.getScene().useRightHandedSystem) {
  105465. this._projectionMatrix.toggleProjectionMatrixHandInPlace();
  105466. }
  105467. return this._projectionMatrix;
  105468. };
  105469. /**
  105470. * Initializes the controllers and their meshes
  105471. */
  105472. WebVRFreeCamera.prototype.initControllers = function () {
  105473. var _this = this;
  105474. this.controllers = [];
  105475. var manager = this.getScene().gamepadManager;
  105476. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  105477. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  105478. var webVrController = gamepad;
  105479. if (webVrController.defaultModel) {
  105480. webVrController.defaultModel.setEnabled(false);
  105481. }
  105482. if (webVrController.hand === "right") {
  105483. _this._rightController = null;
  105484. }
  105485. if (webVrController.hand === "left") {
  105486. _this._leftController = null;
  105487. }
  105488. var controllerIndex = _this.controllers.indexOf(webVrController);
  105489. if (controllerIndex !== -1) {
  105490. _this.controllers.splice(controllerIndex, 1);
  105491. }
  105492. }
  105493. });
  105494. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  105495. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  105496. var webVrController_1 = gamepad;
  105497. if (!_this.webVROptions.trackPosition) {
  105498. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  105499. // Cache must be updated before rendering controllers to avoid them being one frame behind
  105500. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  105501. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  105502. _this._updateCache();
  105503. });
  105504. }
  105505. }
  105506. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  105507. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  105508. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  105509. if (_this.webVROptions.controllerMeshes) {
  105510. if (webVrController_1.defaultModel) {
  105511. webVrController_1.defaultModel.setEnabled(true);
  105512. }
  105513. else {
  105514. // Load the meshes
  105515. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  105516. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  105517. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  105518. if (_this.webVROptions.defaultLightingOnControllers) {
  105519. if (!_this._lightOnControllers) {
  105520. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  105521. }
  105522. var activateLightOnSubMeshes_1 = function (mesh, light) {
  105523. var children = mesh.getChildren();
  105524. if (children && children.length !== 0) {
  105525. children.forEach(function (mesh) {
  105526. light.includedOnlyMeshes.push(mesh);
  105527. activateLightOnSubMeshes_1(mesh, light);
  105528. });
  105529. }
  105530. };
  105531. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  105532. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  105533. }
  105534. });
  105535. }
  105536. }
  105537. webVrController_1.attachToPoseControlledCamera(_this);
  105538. // since this is async - sanity check. Is the controller already stored?
  105539. if (_this.controllers.indexOf(webVrController_1) === -1) {
  105540. //add to the controllers array
  105541. _this.controllers.push(webVrController_1);
  105542. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  105543. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  105544. // So we're overriding setting left & right manually to be sure
  105545. var firstViveWandDetected = false;
  105546. for (var i = 0; i < _this.controllers.length; i++) {
  105547. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  105548. if (!firstViveWandDetected) {
  105549. firstViveWandDetected = true;
  105550. _this.controllers[i].hand = "left";
  105551. }
  105552. else {
  105553. _this.controllers[i].hand = "right";
  105554. }
  105555. }
  105556. }
  105557. //did we find enough controllers? Great! let the developer know.
  105558. if (_this.controllers.length >= 2) {
  105559. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  105560. }
  105561. }
  105562. }
  105563. });
  105564. };
  105565. return WebVRFreeCamera;
  105566. }(BABYLON.FreeCamera));
  105567. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  105568. })(BABYLON || (BABYLON = {}));
  105569. //# sourceMappingURL=babylon.webVRCamera.js.map
  105570. var BABYLON;
  105571. (function (BABYLON) {
  105572. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  105573. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  105574. });
  105575. // We're mainly based on the logic defined into the FreeCamera code
  105576. /**
  105577. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  105578. * being tilted forward or back and left or right.
  105579. */
  105580. var DeviceOrientationCamera = /** @class */ (function (_super) {
  105581. __extends(DeviceOrientationCamera, _super);
  105582. /**
  105583. * Creates a new device orientation camera
  105584. * @param name The name of the camera
  105585. * @param position The start position camera
  105586. * @param scene The scene the camera belongs to
  105587. */
  105588. function DeviceOrientationCamera(name, position, scene) {
  105589. var _this = _super.call(this, name, position, scene) || this;
  105590. _this._quaternionCache = new BABYLON.Quaternion();
  105591. _this.inputs.addDeviceOrientation();
  105592. return _this;
  105593. }
  105594. /**
  105595. * Gets the current instance class name ("DeviceOrientationCamera").
  105596. * This helps avoiding instanceof at run time.
  105597. * @returns the class name
  105598. */
  105599. DeviceOrientationCamera.prototype.getClassName = function () {
  105600. return "DeviceOrientationCamera";
  105601. };
  105602. /**
  105603. * @hidden
  105604. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  105605. */
  105606. DeviceOrientationCamera.prototype._checkInputs = function () {
  105607. _super.prototype._checkInputs.call(this);
  105608. this._quaternionCache.copyFrom(this.rotationQuaternion);
  105609. if (this._initialQuaternion) {
  105610. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  105611. }
  105612. };
  105613. /**
  105614. * Reset the camera to its default orientation on the specified axis only.
  105615. * @param axis The axis to reset
  105616. */
  105617. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  105618. var _this = this;
  105619. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  105620. //can only work if this camera has a rotation quaternion already.
  105621. if (!this.rotationQuaternion) {
  105622. return;
  105623. }
  105624. if (!this._initialQuaternion) {
  105625. this._initialQuaternion = new BABYLON.Quaternion();
  105626. }
  105627. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  105628. ['x', 'y', 'z'].forEach(function (axisName) {
  105629. if (!axis[axisName]) {
  105630. _this._initialQuaternion[axisName] = 0;
  105631. }
  105632. else {
  105633. _this._initialQuaternion[axisName] *= -1;
  105634. }
  105635. });
  105636. this._initialQuaternion.normalize();
  105637. //force rotation update
  105638. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  105639. };
  105640. return DeviceOrientationCamera;
  105641. }(BABYLON.FreeCamera));
  105642. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  105643. })(BABYLON || (BABYLON = {}));
  105644. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  105645. var BABYLON;
  105646. (function (BABYLON) {
  105647. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  105648. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  105649. });
  105650. /**
  105651. * Camera used to simulate VR rendering (based on FreeCamera)
  105652. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105653. */
  105654. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  105655. __extends(VRDeviceOrientationFreeCamera, _super);
  105656. /**
  105657. * Creates a new VRDeviceOrientationFreeCamera
  105658. * @param name defines camera name
  105659. * @param position defines the start position of the camera
  105660. * @param scene defines the scene the camera belongs to
  105661. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105662. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105663. */
  105664. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  105665. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105666. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105667. var _this = _super.call(this, name, position, scene) || this;
  105668. vrCameraMetrics.compensateDistortion = compensateDistortion;
  105669. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  105670. return _this;
  105671. }
  105672. /**
  105673. * Gets camera class name
  105674. * @returns VRDeviceOrientationFreeCamera
  105675. */
  105676. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  105677. return "VRDeviceOrientationFreeCamera";
  105678. };
  105679. return VRDeviceOrientationFreeCamera;
  105680. }(BABYLON.DeviceOrientationCamera));
  105681. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  105682. })(BABYLON || (BABYLON = {}));
  105683. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  105684. var BABYLON;
  105685. (function (BABYLON) {
  105686. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  105687. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  105688. });
  105689. /**
  105690. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  105691. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105692. */
  105693. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  105694. __extends(VRDeviceOrientationArcRotateCamera, _super);
  105695. /**
  105696. * Creates a new VRDeviceOrientationArcRotateCamera
  105697. * @param name defines camera name
  105698. * @param alpha defines the camera rotation along the logitudinal axis
  105699. * @param beta defines the camera rotation along the latitudinal axis
  105700. * @param radius defines the camera distance from its target
  105701. * @param target defines the camera target
  105702. * @param scene defines the scene the camera belongs to
  105703. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105704. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105705. */
  105706. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  105707. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105708. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105709. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  105710. vrCameraMetrics.compensateDistortion = compensateDistortion;
  105711. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  105712. _this.inputs.addVRDeviceOrientation();
  105713. return _this;
  105714. }
  105715. /**
  105716. * Gets camera class name
  105717. * @returns VRDeviceOrientationArcRotateCamera
  105718. */
  105719. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  105720. return "VRDeviceOrientationArcRotateCamera";
  105721. };
  105722. return VRDeviceOrientationArcRotateCamera;
  105723. }(BABYLON.ArcRotateCamera));
  105724. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  105725. })(BABYLON || (BABYLON = {}));
  105726. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  105727. var BABYLON;
  105728. (function (BABYLON) {
  105729. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  105730. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  105731. });
  105732. /**
  105733. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  105734. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105735. */
  105736. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  105737. __extends(VRDeviceOrientationGamepadCamera, _super);
  105738. /**
  105739. * Creates a new VRDeviceOrientationGamepadCamera
  105740. * @param name defines camera name
  105741. * @param position defines the start position of the camera
  105742. * @param scene defines the scene the camera belongs to
  105743. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105744. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105745. */
  105746. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  105747. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105748. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105749. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  105750. _this.inputs.addGamepad();
  105751. return _this;
  105752. }
  105753. /**
  105754. * Gets camera class name
  105755. * @returns VRDeviceOrientationGamepadCamera
  105756. */
  105757. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  105758. return "VRDeviceOrientationGamepadCamera";
  105759. };
  105760. return VRDeviceOrientationGamepadCamera;
  105761. }(BABYLON.VRDeviceOrientationFreeCamera));
  105762. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  105763. })(BABYLON || (BABYLON = {}));
  105764. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  105765. var BABYLON;
  105766. (function (BABYLON) {
  105767. var VRExperienceHelperGazer = /** @class */ (function () {
  105768. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  105769. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  105770. this.scene = scene;
  105771. /** @hidden */
  105772. this._pointerDownOnMeshAsked = false;
  105773. /** @hidden */
  105774. this._isActionableMesh = false;
  105775. /** @hidden */
  105776. this._teleportationRequestInitiated = false;
  105777. /** @hidden */
  105778. this._teleportationBackRequestInitiated = false;
  105779. /** @hidden */
  105780. this._rotationRightAsked = false;
  105781. /** @hidden */
  105782. this._rotationLeftAsked = false;
  105783. /** @hidden */
  105784. this._dpadPressed = true;
  105785. /** @hidden */
  105786. this._activePointer = false;
  105787. this._id = VRExperienceHelperGazer._idCounter++;
  105788. // Gaze tracker
  105789. if (!gazeTrackerToClone) {
  105790. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  105791. this._gazeTracker.bakeCurrentTransformIntoVertices();
  105792. this._gazeTracker.isPickable = false;
  105793. this._gazeTracker.isVisible = false;
  105794. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  105795. targetMat.specularColor = BABYLON.Color3.Black();
  105796. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  105797. targetMat.backFaceCulling = false;
  105798. this._gazeTracker.material = targetMat;
  105799. }
  105800. else {
  105801. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  105802. }
  105803. }
  105804. /** @hidden */
  105805. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  105806. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  105807. };
  105808. /** @hidden */
  105809. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  105810. this._pointerDownOnMeshAsked = true;
  105811. if (this._currentHit) {
  105812. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  105813. }
  105814. };
  105815. /** @hidden */
  105816. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  105817. if (this._currentHit) {
  105818. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  105819. }
  105820. this._pointerDownOnMeshAsked = false;
  105821. };
  105822. /** @hidden */
  105823. VRExperienceHelperGazer.prototype._activatePointer = function () {
  105824. this._activePointer = true;
  105825. };
  105826. /** @hidden */
  105827. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  105828. this._activePointer = false;
  105829. };
  105830. /** @hidden */
  105831. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  105832. if (distance === void 0) { distance = 100; }
  105833. };
  105834. VRExperienceHelperGazer.prototype.dispose = function () {
  105835. this._interactionsEnabled = false;
  105836. this._teleportationEnabled = false;
  105837. if (this._gazeTracker) {
  105838. this._gazeTracker.dispose();
  105839. }
  105840. };
  105841. VRExperienceHelperGazer._idCounter = 0;
  105842. return VRExperienceHelperGazer;
  105843. }());
  105844. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  105845. __extends(VRExperienceHelperControllerGazer, _super);
  105846. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  105847. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  105848. _this.webVRController = webVRController;
  105849. // Laser pointer
  105850. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  105851. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  105852. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  105853. laserPointerMaterial.alpha = 0.6;
  105854. _this._laserPointer.material = laserPointerMaterial;
  105855. _this._laserPointer.rotation.x = Math.PI / 2;
  105856. _this._laserPointer.position.z = -0.5;
  105857. _this._laserPointer.isVisible = false;
  105858. _this._laserPointer.isPickable = false;
  105859. if (!webVRController.mesh) {
  105860. // Create an empty mesh that is used prior to loading the high quality model
  105861. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  105862. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  105863. preloadPointerPose.rotation.x = -0.7;
  105864. preloadMesh.addChild(preloadPointerPose);
  105865. webVRController.attachToMesh(preloadMesh);
  105866. }
  105867. _this._setLaserPointerParent(webVRController.mesh);
  105868. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  105869. _this._setLaserPointerParent(mesh);
  105870. });
  105871. return _this;
  105872. }
  105873. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  105874. return this.webVRController.getForwardRay(length);
  105875. };
  105876. /** @hidden */
  105877. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  105878. _super.prototype._activatePointer.call(this);
  105879. this._laserPointer.isVisible = true;
  105880. };
  105881. /** @hidden */
  105882. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  105883. _super.prototype._deactivatePointer.call(this);
  105884. this._laserPointer.isVisible = false;
  105885. };
  105886. /** @hidden */
  105887. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  105888. this._laserPointer.material.emissiveColor = color;
  105889. };
  105890. /** @hidden */
  105891. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  105892. var makeNotPick = function (root) {
  105893. root.isPickable = false;
  105894. root.getChildMeshes().forEach(function (c) {
  105895. makeNotPick(c);
  105896. });
  105897. };
  105898. makeNotPick(mesh);
  105899. var childMeshes = mesh.getChildMeshes();
  105900. this.webVRController._pointingPoseNode = null;
  105901. for (var i = 0; i < childMeshes.length; i++) {
  105902. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  105903. mesh = childMeshes[i];
  105904. this.webVRController._pointingPoseNode = mesh;
  105905. break;
  105906. }
  105907. }
  105908. this._laserPointer.parent = mesh;
  105909. };
  105910. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  105911. if (distance === void 0) { distance = 100; }
  105912. this._laserPointer.scaling.y = distance;
  105913. this._laserPointer.position.z = -distance / 2;
  105914. };
  105915. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  105916. _super.prototype.dispose.call(this);
  105917. this._laserPointer.dispose();
  105918. if (this._meshAttachedObserver) {
  105919. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  105920. }
  105921. };
  105922. return VRExperienceHelperControllerGazer;
  105923. }(VRExperienceHelperGazer));
  105924. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  105925. __extends(VRExperienceHelperCameraGazer, _super);
  105926. function VRExperienceHelperCameraGazer(getCamera, scene) {
  105927. var _this = _super.call(this, scene) || this;
  105928. _this.getCamera = getCamera;
  105929. return _this;
  105930. }
  105931. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  105932. var camera = this.getCamera();
  105933. if (camera) {
  105934. return camera.getForwardRay(length);
  105935. }
  105936. else {
  105937. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  105938. }
  105939. };
  105940. return VRExperienceHelperCameraGazer;
  105941. }(VRExperienceHelperGazer));
  105942. /**
  105943. * Helps to quickly add VR support to an existing scene.
  105944. * See http://doc.babylonjs.com/how_to/webvr_helper
  105945. */
  105946. var VRExperienceHelper = /** @class */ (function () {
  105947. /**
  105948. * Instantiates a VRExperienceHelper.
  105949. * Helps to quickly add VR support to an existing scene.
  105950. * @param scene The scene the VRExperienceHelper belongs to.
  105951. * @param webVROptions Options to modify the vr experience helper's behavior.
  105952. */
  105953. function VRExperienceHelper(scene,
  105954. /** Options to modify the vr experience helper's behavior. */
  105955. webVROptions) {
  105956. if (webVROptions === void 0) { webVROptions = {}; }
  105957. var _this = this;
  105958. this.webVROptions = webVROptions;
  105959. // Can the system support WebVR, even if a headset isn't plugged in?
  105960. this._webVRsupported = false;
  105961. // If WebVR is supported, is a headset plugged in and are we ready to present?
  105962. this._webVRready = false;
  105963. // Are we waiting for the requestPresent callback to complete?
  105964. this._webVRrequesting = false;
  105965. // Are we presenting to the headset right now? (this is the vrDevice state)
  105966. this._webVRpresenting = false;
  105967. // Are we presenting in the fullscreen fallback?
  105968. this._fullscreenVRpresenting = false;
  105969. /**
  105970. * Observable raised when entering VR.
  105971. */
  105972. this.onEnteringVRObservable = new BABYLON.Observable();
  105973. /**
  105974. * Observable raised when exiting VR.
  105975. */
  105976. this.onExitingVRObservable = new BABYLON.Observable();
  105977. /**
  105978. * Observable raised when controller mesh is loaded.
  105979. */
  105980. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  105981. this._useCustomVRButton = false;
  105982. this._teleportationRequested = false;
  105983. this._teleportActive = false;
  105984. this._floorMeshesCollection = [];
  105985. this._rotationAllowed = true;
  105986. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  105987. this._isDefaultTeleportationTarget = true;
  105988. this._teleportationFillColor = "#444444";
  105989. this._teleportationBorderColor = "#FFFFFF";
  105990. this._rotationAngle = 0;
  105991. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  105992. this._padSensibilityUp = 0.65;
  105993. this._padSensibilityDown = 0.35;
  105994. this._leftController = null;
  105995. this._rightController = null;
  105996. /**
  105997. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  105998. */
  105999. this.onNewMeshSelected = new BABYLON.Observable();
  106000. /**
  106001. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  106002. */
  106003. this.onNewMeshPicked = new BABYLON.Observable();
  106004. /**
  106005. * Observable raised before camera teleportation
  106006. */
  106007. this.onBeforeCameraTeleport = new BABYLON.Observable();
  106008. /**
  106009. * Observable raised after camera teleportation
  106010. */
  106011. this.onAfterCameraTeleport = new BABYLON.Observable();
  106012. /**
  106013. * Observable raised when current selected mesh gets unselected
  106014. */
  106015. this.onSelectedMeshUnselected = new BABYLON.Observable();
  106016. /**
  106017. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  106018. */
  106019. this.teleportationEnabled = true;
  106020. this._teleportationInitialized = false;
  106021. this._interactionsEnabled = false;
  106022. this._interactionsRequested = false;
  106023. this._displayGaze = true;
  106024. this._displayLaserPointer = true;
  106025. /**
  106026. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  106027. */
  106028. this.updateGazeTrackerScale = true;
  106029. this._onResize = function () {
  106030. _this.moveButtonToBottomRight();
  106031. if (_this._fullscreenVRpresenting && _this._webVRready) {
  106032. _this.exitVR();
  106033. }
  106034. };
  106035. this._onFullscreenChange = function () {
  106036. if (document.fullscreen !== undefined) {
  106037. _this._fullscreenVRpresenting = document.fullscreen;
  106038. }
  106039. else if (document.mozFullScreen !== undefined) {
  106040. _this._fullscreenVRpresenting = document.mozFullScreen;
  106041. }
  106042. else if (document.webkitIsFullScreen !== undefined) {
  106043. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  106044. }
  106045. else if (document.msIsFullScreen !== undefined) {
  106046. _this._fullscreenVRpresenting = document.msIsFullScreen;
  106047. }
  106048. else if (document.msFullscreenElement !== undefined) {
  106049. _this._fullscreenVRpresenting = document.msFullscreenElement;
  106050. }
  106051. if (!_this._fullscreenVRpresenting && _this._canvas) {
  106052. _this.exitVR();
  106053. if (!_this._useCustomVRButton) {
  106054. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  106055. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  106056. }
  106057. }
  106058. };
  106059. this.beforeRender = function () {
  106060. if (_this._leftController && _this._leftController._activePointer) {
  106061. _this._castRayAndSelectObject(_this._leftController);
  106062. }
  106063. if (_this._rightController && _this._rightController._activePointer) {
  106064. _this._castRayAndSelectObject(_this._rightController);
  106065. }
  106066. if (_this._noControllerIsActive) {
  106067. _this._castRayAndSelectObject(_this._cameraGazer);
  106068. }
  106069. else {
  106070. _this._cameraGazer._gazeTracker.isVisible = false;
  106071. }
  106072. };
  106073. this._onNewGamepadConnected = function (gamepad) {
  106074. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  106075. if (gamepad.leftStick) {
  106076. gamepad.onleftstickchanged(function (stickValues) {
  106077. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  106078. // Listening to classic/xbox gamepad only if no VR controller is active
  106079. if ((!_this._leftController && !_this._rightController) ||
  106080. ((_this._leftController && !_this._leftController._activePointer) &&
  106081. (_this._rightController && !_this._rightController._activePointer))) {
  106082. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  106083. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  106084. }
  106085. }
  106086. });
  106087. }
  106088. if (gamepad.rightStick) {
  106089. gamepad.onrightstickchanged(function (stickValues) {
  106090. if (_this._teleportationInitialized) {
  106091. _this._checkRotate(stickValues, _this._cameraGazer);
  106092. }
  106093. });
  106094. }
  106095. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  106096. gamepad.onbuttondown(function (buttonPressed) {
  106097. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  106098. _this._cameraGazer._selectionPointerDown();
  106099. }
  106100. });
  106101. gamepad.onbuttonup(function (buttonPressed) {
  106102. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  106103. _this._cameraGazer._selectionPointerUp();
  106104. }
  106105. });
  106106. }
  106107. }
  106108. else {
  106109. var webVRController = gamepad;
  106110. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  106111. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  106112. _this._rightController = controller;
  106113. }
  106114. else {
  106115. _this._leftController = controller;
  106116. }
  106117. _this._tryEnableInteractionOnController(controller);
  106118. }
  106119. };
  106120. // 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
  106121. this._tryEnableInteractionOnController = function (controller) {
  106122. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  106123. _this._enableInteractionOnController(controller);
  106124. }
  106125. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  106126. _this._enableTeleportationOnController(controller);
  106127. }
  106128. };
  106129. this._onNewGamepadDisconnected = function (gamepad) {
  106130. if (gamepad instanceof BABYLON.WebVRController) {
  106131. if (gamepad.hand === "left" && _this._leftController != null) {
  106132. _this._leftController.dispose();
  106133. _this._leftController = null;
  106134. }
  106135. if (gamepad.hand === "right" && _this._rightController != null) {
  106136. _this._rightController.dispose();
  106137. _this._rightController = null;
  106138. }
  106139. }
  106140. };
  106141. this._workingVector = BABYLON.Vector3.Zero();
  106142. this._workingQuaternion = BABYLON.Quaternion.Identity();
  106143. this._workingMatrix = BABYLON.Matrix.Identity();
  106144. this._scene = scene;
  106145. this._canvas = scene.getEngine().getRenderingCanvas();
  106146. // Parse options
  106147. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  106148. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  106149. }
  106150. if (webVROptions.createDeviceOrientationCamera === undefined) {
  106151. webVROptions.createDeviceOrientationCamera = true;
  106152. }
  106153. if (webVROptions.laserToggle === undefined) {
  106154. webVROptions.laserToggle = true;
  106155. }
  106156. if (webVROptions.defaultHeight === undefined) {
  106157. webVROptions.defaultHeight = 1.7;
  106158. }
  106159. if (webVROptions.useCustomVRButton) {
  106160. this._useCustomVRButton = true;
  106161. if (webVROptions.customVRButton) {
  106162. this._btnVR = webVROptions.customVRButton;
  106163. }
  106164. }
  106165. if (webVROptions.rayLength) {
  106166. this._rayLength = webVROptions.rayLength;
  106167. }
  106168. this._defaultHeight = webVROptions.defaultHeight;
  106169. if (webVROptions.positionScale) {
  106170. this._rayLength *= webVROptions.positionScale;
  106171. this._defaultHeight *= webVROptions.positionScale;
  106172. }
  106173. this._hasEnteredVR = false;
  106174. // Set position
  106175. if (this._scene.activeCamera) {
  106176. this._position = this._scene.activeCamera.position.clone();
  106177. }
  106178. else {
  106179. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  106180. }
  106181. // Set non-vr camera
  106182. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  106183. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  106184. // Copy data from existing camera
  106185. if (this._scene.activeCamera) {
  106186. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  106187. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  106188. // Set rotation from previous camera
  106189. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  106190. var targetCamera = this._scene.activeCamera;
  106191. if (targetCamera.rotationQuaternion) {
  106192. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  106193. }
  106194. else {
  106195. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  106196. }
  106197. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  106198. }
  106199. }
  106200. this._scene.activeCamera = this._deviceOrientationCamera;
  106201. if (this._canvas) {
  106202. this._scene.activeCamera.attachControl(this._canvas);
  106203. }
  106204. }
  106205. else {
  106206. this._existingCamera = this._scene.activeCamera;
  106207. }
  106208. // Create VR cameras
  106209. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  106210. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  106211. }
  106212. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  106213. this._webVRCamera.useStandingMatrix();
  106214. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  106215. // Create default button
  106216. if (!this._useCustomVRButton) {
  106217. this._btnVR = document.createElement("BUTTON");
  106218. this._btnVR.className = "babylonVRicon";
  106219. this._btnVR.id = "babylonVRiconbtn";
  106220. this._btnVR.title = "Click to switch to VR";
  106221. 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) }";
  106222. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  106223. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  106224. // css += ".babylonVRicon.vrdisplaysupported { }";
  106225. // css += ".babylonVRicon.vrdisplayready { }";
  106226. // css += ".babylonVRicon.vrdisplayrequesting { }";
  106227. var style = document.createElement('style');
  106228. style.appendChild(document.createTextNode(css));
  106229. document.getElementsByTagName('head')[0].appendChild(style);
  106230. this.moveButtonToBottomRight();
  106231. }
  106232. // VR button click event
  106233. if (this._btnVR) {
  106234. this._btnVR.addEventListener("click", function () {
  106235. if (!_this.isInVRMode) {
  106236. _this.enterVR();
  106237. }
  106238. else {
  106239. _this.exitVR();
  106240. }
  106241. });
  106242. }
  106243. // Window events
  106244. window.addEventListener("resize", this._onResize);
  106245. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  106246. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  106247. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  106248. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  106249. document.onmsfullscreenchange = this._onFullscreenChange;
  106250. // Display vr button when headset is connected
  106251. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  106252. this.displayVRButton();
  106253. }
  106254. else {
  106255. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  106256. if (e.vrDisplay) {
  106257. _this.displayVRButton();
  106258. }
  106259. });
  106260. }
  106261. // Exiting VR mode using 'ESC' key on desktop
  106262. this._onKeyDown = function (event) {
  106263. if (event.keyCode === 27 && _this.isInVRMode) {
  106264. _this.exitVR();
  106265. }
  106266. };
  106267. document.addEventListener("keydown", this._onKeyDown);
  106268. // Exiting VR mode double tapping the touch screen
  106269. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  106270. if (_this.isInVRMode) {
  106271. _this.exitVR();
  106272. if (_this._fullscreenVRpresenting) {
  106273. _this._scene.getEngine().switchFullscreen(true);
  106274. }
  106275. }
  106276. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  106277. // Listen for WebVR display changes
  106278. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  106279. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  106280. this._onVRRequestPresentStart = function () {
  106281. _this._webVRrequesting = true;
  106282. _this.updateButtonVisibility();
  106283. };
  106284. this._onVRRequestPresentComplete = function (success) {
  106285. _this._webVRrequesting = false;
  106286. _this.updateButtonVisibility();
  106287. };
  106288. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  106289. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  106290. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  106291. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  106292. scene.onDisposeObservable.add(function () {
  106293. _this.dispose();
  106294. });
  106295. // Gamepad connection events
  106296. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  106297. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  106298. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  106299. this.updateButtonVisibility();
  106300. //create easing functions
  106301. this._circleEase = new BABYLON.CircleEase();
  106302. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  106303. if (this.webVROptions.floorMeshes) {
  106304. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  106305. }
  106306. }
  106307. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  106308. /** Return this.onEnteringVRObservable
  106309. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  106310. */
  106311. get: function () {
  106312. return this.onEnteringVRObservable;
  106313. },
  106314. enumerable: true,
  106315. configurable: true
  106316. });
  106317. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  106318. /** Return this.onExitingVRObservable
  106319. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  106320. */
  106321. get: function () {
  106322. return this.onExitingVRObservable;
  106323. },
  106324. enumerable: true,
  106325. configurable: true
  106326. });
  106327. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  106328. /** Return this.onControllerMeshLoadedObservable
  106329. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  106330. */
  106331. get: function () {
  106332. return this.onControllerMeshLoadedObservable;
  106333. },
  106334. enumerable: true,
  106335. configurable: true
  106336. });
  106337. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  106338. /**
  106339. * The mesh used to display where the user is going to teleport.
  106340. */
  106341. get: function () {
  106342. return this._teleportationTarget;
  106343. },
  106344. /**
  106345. * Sets the mesh to be used to display where the user is going to teleport.
  106346. */
  106347. set: function (value) {
  106348. if (value) {
  106349. value.name = "teleportationTarget";
  106350. this._isDefaultTeleportationTarget = false;
  106351. this._teleportationTarget = value;
  106352. }
  106353. },
  106354. enumerable: true,
  106355. configurable: true
  106356. });
  106357. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  106358. /**
  106359. * 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
  106360. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  106361. * See http://doc.babylonjs.com/resources/baking_transformations
  106362. */
  106363. get: function () {
  106364. return this._cameraGazer._gazeTracker;
  106365. },
  106366. set: function (value) {
  106367. if (value) {
  106368. // Dispose of existing meshes
  106369. if (this._cameraGazer._gazeTracker) {
  106370. this._cameraGazer._gazeTracker.dispose();
  106371. }
  106372. if (this._leftController && this._leftController._gazeTracker) {
  106373. this._leftController._gazeTracker.dispose();
  106374. }
  106375. if (this._rightController && this._rightController._gazeTracker) {
  106376. this._rightController._gazeTracker.dispose();
  106377. }
  106378. // Set and create gaze trackers on head and controllers
  106379. this._cameraGazer._gazeTracker = value;
  106380. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  106381. this._cameraGazer._gazeTracker.isPickable = false;
  106382. this._cameraGazer._gazeTracker.isVisible = false;
  106383. this._cameraGazer._gazeTracker.name = "gazeTracker";
  106384. if (this._leftController) {
  106385. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  106386. }
  106387. if (this._rightController) {
  106388. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  106389. }
  106390. }
  106391. },
  106392. enumerable: true,
  106393. configurable: true
  106394. });
  106395. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  106396. /**
  106397. * The gaze tracking mesh corresponding to the left controller
  106398. */
  106399. get: function () {
  106400. if (this._leftController) {
  106401. return this._leftController._gazeTracker;
  106402. }
  106403. return null;
  106404. },
  106405. enumerable: true,
  106406. configurable: true
  106407. });
  106408. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  106409. /**
  106410. * The gaze tracking mesh corresponding to the right controller
  106411. */
  106412. get: function () {
  106413. if (this._rightController) {
  106414. return this._rightController._gazeTracker;
  106415. }
  106416. return null;
  106417. },
  106418. enumerable: true,
  106419. configurable: true
  106420. });
  106421. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  106422. /**
  106423. * If the ray of the gaze should be displayed.
  106424. */
  106425. get: function () {
  106426. return this._displayGaze;
  106427. },
  106428. /**
  106429. * Sets if the ray of the gaze should be displayed.
  106430. */
  106431. set: function (value) {
  106432. this._displayGaze = value;
  106433. if (!value) {
  106434. this._cameraGazer._gazeTracker.isVisible = false;
  106435. if (this._leftController) {
  106436. this._leftController._gazeTracker.isVisible = false;
  106437. }
  106438. if (this._rightController) {
  106439. this._rightController._gazeTracker.isVisible = false;
  106440. }
  106441. }
  106442. },
  106443. enumerable: true,
  106444. configurable: true
  106445. });
  106446. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  106447. /**
  106448. * If the ray of the LaserPointer should be displayed.
  106449. */
  106450. get: function () {
  106451. return this._displayLaserPointer;
  106452. },
  106453. /**
  106454. * Sets if the ray of the LaserPointer should be displayed.
  106455. */
  106456. set: function (value) {
  106457. this._displayLaserPointer = value;
  106458. if (!value) {
  106459. if (this._rightController) {
  106460. this._rightController._deactivatePointer();
  106461. this._rightController._gazeTracker.isVisible = false;
  106462. }
  106463. if (this._leftController) {
  106464. this._leftController._deactivatePointer();
  106465. this._leftController._gazeTracker.isVisible = false;
  106466. }
  106467. }
  106468. else {
  106469. if (this._rightController) {
  106470. this._rightController._activatePointer();
  106471. }
  106472. if (this._leftController) {
  106473. this._leftController._activatePointer();
  106474. }
  106475. }
  106476. },
  106477. enumerable: true,
  106478. configurable: true
  106479. });
  106480. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  106481. /**
  106482. * The deviceOrientationCamera used as the camera when not in VR.
  106483. */
  106484. get: function () {
  106485. return this._deviceOrientationCamera;
  106486. },
  106487. enumerable: true,
  106488. configurable: true
  106489. });
  106490. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  106491. /**
  106492. * Based on the current WebVR support, returns the current VR camera used.
  106493. */
  106494. get: function () {
  106495. if (this._webVRready) {
  106496. return this._webVRCamera;
  106497. }
  106498. else {
  106499. return this._scene.activeCamera;
  106500. }
  106501. },
  106502. enumerable: true,
  106503. configurable: true
  106504. });
  106505. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  106506. /**
  106507. * The webVRCamera which is used when in VR.
  106508. */
  106509. get: function () {
  106510. return this._webVRCamera;
  106511. },
  106512. enumerable: true,
  106513. configurable: true
  106514. });
  106515. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  106516. /**
  106517. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  106518. */
  106519. get: function () {
  106520. return this._vrDeviceOrientationCamera;
  106521. },
  106522. enumerable: true,
  106523. configurable: true
  106524. });
  106525. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  106526. get: function () {
  106527. var result = this._cameraGazer._teleportationRequestInitiated
  106528. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  106529. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  106530. return result;
  106531. },
  106532. enumerable: true,
  106533. configurable: true
  106534. });
  106535. // Raised when one of the controller has loaded successfully its associated default mesh
  106536. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  106537. if (this._leftController && this._leftController.webVRController == webVRController) {
  106538. if (webVRController.mesh) {
  106539. this._leftController._setLaserPointerParent(webVRController.mesh);
  106540. }
  106541. }
  106542. if (this._rightController && this._rightController.webVRController == webVRController) {
  106543. if (webVRController.mesh) {
  106544. this._rightController._setLaserPointerParent(webVRController.mesh);
  106545. }
  106546. }
  106547. try {
  106548. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  106549. }
  106550. catch (err) {
  106551. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  106552. }
  106553. };
  106554. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  106555. /**
  106556. * Gets a value indicating if we are currently in VR mode.
  106557. */
  106558. get: function () {
  106559. return this._webVRpresenting || this._fullscreenVRpresenting;
  106560. },
  106561. enumerable: true,
  106562. configurable: true
  106563. });
  106564. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  106565. var vrDisplay = this._scene.getEngine().getVRDevice();
  106566. if (vrDisplay) {
  106567. var wasPresenting = this._webVRpresenting;
  106568. this._webVRpresenting = vrDisplay.isPresenting;
  106569. if (wasPresenting && !this._webVRpresenting) {
  106570. this.exitVR();
  106571. }
  106572. }
  106573. else {
  106574. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  106575. }
  106576. this.updateButtonVisibility();
  106577. };
  106578. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  106579. this._webVRsupported = eventArgs.vrSupported;
  106580. this._webVRready = !!eventArgs.vrDisplay;
  106581. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  106582. this.updateButtonVisibility();
  106583. };
  106584. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  106585. if (this._canvas && !this._useCustomVRButton) {
  106586. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  106587. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  106588. }
  106589. };
  106590. VRExperienceHelper.prototype.displayVRButton = function () {
  106591. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  106592. document.body.appendChild(this._btnVR);
  106593. this._btnVRDisplayed = true;
  106594. }
  106595. };
  106596. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  106597. if (!this._btnVR || this._useCustomVRButton) {
  106598. return;
  106599. }
  106600. this._btnVR.className = "babylonVRicon";
  106601. if (this.isInVRMode) {
  106602. this._btnVR.className += " vrdisplaypresenting";
  106603. }
  106604. else {
  106605. if (this._webVRready) {
  106606. this._btnVR.className += " vrdisplayready";
  106607. }
  106608. if (this._webVRsupported) {
  106609. this._btnVR.className += " vrdisplaysupported";
  106610. }
  106611. if (this._webVRrequesting) {
  106612. this._btnVR.className += " vrdisplayrequesting";
  106613. }
  106614. }
  106615. };
  106616. /**
  106617. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  106618. * Otherwise, will use the fullscreen API.
  106619. */
  106620. VRExperienceHelper.prototype.enterVR = function () {
  106621. if (this.onEnteringVRObservable) {
  106622. try {
  106623. this.onEnteringVRObservable.notifyObservers(this);
  106624. }
  106625. catch (err) {
  106626. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  106627. }
  106628. }
  106629. if (this._scene.activeCamera) {
  106630. this._position = this._scene.activeCamera.position.clone();
  106631. // make sure that we return to the last active camera
  106632. this._existingCamera = this._scene.activeCamera;
  106633. }
  106634. if (this._webVRrequesting) {
  106635. return;
  106636. }
  106637. // If WebVR is supported and a headset is connected
  106638. if (this._webVRready) {
  106639. if (!this._webVRpresenting) {
  106640. this._webVRCamera.position = this._position;
  106641. this._scene.activeCamera = this._webVRCamera;
  106642. }
  106643. }
  106644. else if (this._vrDeviceOrientationCamera) {
  106645. this._vrDeviceOrientationCamera.position = this._position;
  106646. if (this._scene.activeCamera) {
  106647. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  106648. }
  106649. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  106650. this._scene.getEngine().switchFullscreen(true);
  106651. this.updateButtonVisibility();
  106652. }
  106653. if (this._scene.activeCamera && this._canvas) {
  106654. this._scene.activeCamera.attachControl(this._canvas);
  106655. }
  106656. if (this._interactionsEnabled) {
  106657. this._scene.registerBeforeRender(this.beforeRender);
  106658. }
  106659. this._hasEnteredVR = true;
  106660. };
  106661. /**
  106662. * Attempt to exit VR, or fullscreen.
  106663. */
  106664. VRExperienceHelper.prototype.exitVR = function () {
  106665. if (this._hasEnteredVR) {
  106666. if (this.onExitingVRObservable) {
  106667. try {
  106668. this.onExitingVRObservable.notifyObservers(this);
  106669. }
  106670. catch (err) {
  106671. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  106672. }
  106673. }
  106674. if (this._webVRpresenting) {
  106675. this._scene.getEngine().disableVR();
  106676. }
  106677. if (this._scene.activeCamera) {
  106678. this._position = this._scene.activeCamera.position.clone();
  106679. }
  106680. if (this._deviceOrientationCamera) {
  106681. this._deviceOrientationCamera.position = this._position;
  106682. this._scene.activeCamera = this._deviceOrientationCamera;
  106683. if (this._canvas) {
  106684. this._scene.activeCamera.attachControl(this._canvas);
  106685. }
  106686. }
  106687. else if (this._existingCamera) {
  106688. this._existingCamera.position = this._position;
  106689. this._scene.activeCamera = this._existingCamera;
  106690. }
  106691. this.updateButtonVisibility();
  106692. if (this._interactionsEnabled) {
  106693. this._scene.unregisterBeforeRender(this.beforeRender);
  106694. this._cameraGazer._gazeTracker.isVisible = false;
  106695. if (this._leftController) {
  106696. this._leftController._gazeTracker.isVisible = false;
  106697. }
  106698. if (this._rightController) {
  106699. this._rightController._gazeTracker.isVisible = false;
  106700. }
  106701. }
  106702. // resize to update width and height when exiting vr exits fullscreen
  106703. this._scene.getEngine().resize();
  106704. this._hasEnteredVR = false;
  106705. }
  106706. };
  106707. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  106708. /**
  106709. * The position of the vr experience helper.
  106710. */
  106711. get: function () {
  106712. return this._position;
  106713. },
  106714. /**
  106715. * Sets the position of the vr experience helper.
  106716. */
  106717. set: function (value) {
  106718. this._position = value;
  106719. if (this._scene.activeCamera) {
  106720. this._scene.activeCamera.position = value;
  106721. }
  106722. },
  106723. enumerable: true,
  106724. configurable: true
  106725. });
  106726. /**
  106727. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  106728. */
  106729. VRExperienceHelper.prototype.enableInteractions = function () {
  106730. var _this = this;
  106731. if (!this._interactionsEnabled) {
  106732. this._interactionsRequested = true;
  106733. if (this._leftController) {
  106734. this._enableInteractionOnController(this._leftController);
  106735. }
  106736. if (this._rightController) {
  106737. this._enableInteractionOnController(this._rightController);
  106738. }
  106739. this.raySelectionPredicate = function (mesh) {
  106740. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  106741. };
  106742. this.meshSelectionPredicate = function (mesh) {
  106743. return true;
  106744. };
  106745. this._raySelectionPredicate = function (mesh) {
  106746. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  106747. && mesh.name.indexOf("teleportationTarget") === -1
  106748. && mesh.name.indexOf("torusTeleportation") === -1)) {
  106749. return _this.raySelectionPredicate(mesh);
  106750. }
  106751. return false;
  106752. };
  106753. this._interactionsEnabled = true;
  106754. }
  106755. };
  106756. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  106757. get: function () {
  106758. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  106759. },
  106760. enumerable: true,
  106761. configurable: true
  106762. });
  106763. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  106764. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  106765. if (this._floorMeshesCollection[i].id === mesh.id) {
  106766. return true;
  106767. }
  106768. }
  106769. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  106770. return true;
  106771. }
  106772. return false;
  106773. };
  106774. /**
  106775. * Adds a floor mesh to be used for teleportation.
  106776. * @param floorMesh the mesh to be used for teleportation.
  106777. */
  106778. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  106779. if (!this._floorMeshesCollection) {
  106780. return;
  106781. }
  106782. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  106783. return;
  106784. }
  106785. this._floorMeshesCollection.push(floorMesh);
  106786. };
  106787. /**
  106788. * Removes a floor mesh from being used for teleportation.
  106789. * @param floorMesh the mesh to be removed.
  106790. */
  106791. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  106792. if (!this._floorMeshesCollection) {
  106793. return;
  106794. }
  106795. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  106796. if (meshIndex !== -1) {
  106797. this._floorMeshesCollection.splice(meshIndex, 1);
  106798. }
  106799. };
  106800. /**
  106801. * Enables interactions and teleportation using the VR controllers and gaze.
  106802. * @param vrTeleportationOptions options to modify teleportation behavior.
  106803. */
  106804. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  106805. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  106806. if (!this._teleportationInitialized) {
  106807. this._teleportationRequested = true;
  106808. this.enableInteractions();
  106809. if (vrTeleportationOptions.floorMeshName) {
  106810. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  106811. }
  106812. if (vrTeleportationOptions.floorMeshes) {
  106813. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  106814. }
  106815. if (this._leftController != null) {
  106816. this._enableTeleportationOnController(this._leftController);
  106817. }
  106818. if (this._rightController != null) {
  106819. this._enableTeleportationOnController(this._rightController);
  106820. }
  106821. // Creates an image processing post process for the vignette not relying
  106822. // on the main scene configuration for image processing to reduce setup and spaces
  106823. // (gamma/linear) conflicts.
  106824. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  106825. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  106826. imageProcessingConfiguration.vignetteEnabled = true;
  106827. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  106828. this._webVRCamera.detachPostProcess(this._postProcessMove);
  106829. this._teleportationInitialized = true;
  106830. if (this._isDefaultTeleportationTarget) {
  106831. this._createTeleportationCircles();
  106832. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  106833. }
  106834. }
  106835. };
  106836. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  106837. var _this = this;
  106838. var controllerMesh = controller.webVRController.mesh;
  106839. if (controllerMesh) {
  106840. controller._interactionsEnabled = true;
  106841. controller._activatePointer();
  106842. if (this.webVROptions.laserToggle) {
  106843. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  106844. // Enabling / disabling laserPointer
  106845. if (_this._displayLaserPointer && stateObject.value === 1) {
  106846. if (controller._activePointer) {
  106847. controller._deactivatePointer();
  106848. }
  106849. else {
  106850. controller._activatePointer();
  106851. }
  106852. if (_this.displayGaze) {
  106853. controller._gazeTracker.isVisible = controller._activePointer;
  106854. }
  106855. }
  106856. });
  106857. }
  106858. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  106859. var gazer = controller;
  106860. if (_this._noControllerIsActive) {
  106861. gazer = _this._cameraGazer;
  106862. }
  106863. if (!gazer._pointerDownOnMeshAsked) {
  106864. if (stateObject.value > _this._padSensibilityUp) {
  106865. gazer._selectionPointerDown();
  106866. }
  106867. }
  106868. else if (stateObject.value < _this._padSensibilityDown) {
  106869. gazer._selectionPointerUp();
  106870. }
  106871. });
  106872. }
  106873. };
  106874. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  106875. // Dont teleport if another gaze already requested teleportation
  106876. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  106877. return;
  106878. }
  106879. if (!gazer._teleportationRequestInitiated) {
  106880. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  106881. gazer._activatePointer();
  106882. gazer._teleportationRequestInitiated = true;
  106883. }
  106884. }
  106885. else {
  106886. // Listening to the proper controller values changes to confirm teleportation
  106887. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  106888. if (this._teleportActive) {
  106889. this.teleportCamera(this._haloCenter);
  106890. }
  106891. gazer._teleportationRequestInitiated = false;
  106892. }
  106893. }
  106894. };
  106895. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  106896. // Only rotate when user is not currently selecting a teleportation location
  106897. if (gazer._teleportationRequestInitiated) {
  106898. return;
  106899. }
  106900. if (!gazer._rotationLeftAsked) {
  106901. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  106902. gazer._rotationLeftAsked = true;
  106903. if (this._rotationAllowed) {
  106904. this._rotateCamera(false);
  106905. }
  106906. }
  106907. }
  106908. else {
  106909. if (stateObject.x > -this._padSensibilityDown) {
  106910. gazer._rotationLeftAsked = false;
  106911. }
  106912. }
  106913. if (!gazer._rotationRightAsked) {
  106914. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  106915. gazer._rotationRightAsked = true;
  106916. if (this._rotationAllowed) {
  106917. this._rotateCamera(true);
  106918. }
  106919. }
  106920. }
  106921. else {
  106922. if (stateObject.x < this._padSensibilityDown) {
  106923. gazer._rotationRightAsked = false;
  106924. }
  106925. }
  106926. };
  106927. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  106928. // Only teleport backwards when user is not currently selecting a teleportation location
  106929. if (gazer._teleportationRequestInitiated) {
  106930. return;
  106931. }
  106932. // Teleport backwards
  106933. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  106934. if (!gazer._teleportationBackRequestInitiated) {
  106935. if (!this.currentVRCamera) {
  106936. return;
  106937. }
  106938. // Get rotation and position of the current camera
  106939. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  106940. var position = this.currentVRCamera.position;
  106941. // If the camera has device position, use that instead
  106942. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  106943. rotation = this.currentVRCamera.deviceRotationQuaternion;
  106944. position = this.currentVRCamera.devicePosition;
  106945. }
  106946. // Get matrix with only the y rotation of the device rotation
  106947. rotation.toEulerAnglesToRef(this._workingVector);
  106948. this._workingVector.z = 0;
  106949. this._workingVector.x = 0;
  106950. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  106951. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  106952. // Rotate backwards ray by device rotation to cast at the ground behind the user
  106953. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  106954. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  106955. var ray = new BABYLON.Ray(position, this._workingVector);
  106956. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  106957. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  106958. this.teleportCamera(hit.pickedPoint);
  106959. }
  106960. gazer._teleportationBackRequestInitiated = true;
  106961. }
  106962. }
  106963. else {
  106964. gazer._teleportationBackRequestInitiated = false;
  106965. }
  106966. };
  106967. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  106968. var _this = this;
  106969. var controllerMesh = controller.webVRController.mesh;
  106970. if (controllerMesh) {
  106971. if (!controller._interactionsEnabled) {
  106972. this._enableInteractionOnController(controller);
  106973. }
  106974. controller._interactionsEnabled = true;
  106975. controller._teleportationEnabled = true;
  106976. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  106977. controller._dpadPressed = false;
  106978. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  106979. controller._dpadPressed = stateObject.pressed;
  106980. if (!controller._dpadPressed) {
  106981. controller._rotationLeftAsked = false;
  106982. controller._rotationRightAsked = false;
  106983. controller._teleportationBackRequestInitiated = false;
  106984. }
  106985. });
  106986. }
  106987. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  106988. if (_this.teleportationEnabled) {
  106989. _this._checkTeleportBackwards(stateObject, controller);
  106990. _this._checkTeleportWithRay(stateObject, controller);
  106991. }
  106992. _this._checkRotate(stateObject, controller);
  106993. });
  106994. }
  106995. };
  106996. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  106997. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  106998. this._teleportationTarget.isPickable = false;
  106999. var length = 512;
  107000. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  107001. dynamicTexture.hasAlpha = true;
  107002. var context = dynamicTexture.getContext();
  107003. var centerX = length / 2;
  107004. var centerY = length / 2;
  107005. var radius = 200;
  107006. context.beginPath();
  107007. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  107008. context.fillStyle = this._teleportationFillColor;
  107009. context.fill();
  107010. context.lineWidth = 10;
  107011. context.strokeStyle = this._teleportationBorderColor;
  107012. context.stroke();
  107013. context.closePath();
  107014. dynamicTexture.update();
  107015. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  107016. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  107017. this._teleportationTarget.material = teleportationCircleMaterial;
  107018. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  107019. torus.isPickable = false;
  107020. torus.parent = this._teleportationTarget;
  107021. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  107022. var keys = [];
  107023. keys.push({
  107024. frame: 0,
  107025. value: 0
  107026. });
  107027. keys.push({
  107028. frame: 30,
  107029. value: 0.4
  107030. });
  107031. keys.push({
  107032. frame: 60,
  107033. value: 0
  107034. });
  107035. animationInnerCircle.setKeys(keys);
  107036. var easingFunction = new BABYLON.SineEase();
  107037. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  107038. animationInnerCircle.setEasingFunction(easingFunction);
  107039. torus.animations = [];
  107040. torus.animations.push(animationInnerCircle);
  107041. this._scene.beginAnimation(torus, 0, 60, true);
  107042. this._hideTeleportationTarget();
  107043. };
  107044. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  107045. this._teleportActive = true;
  107046. if (this._teleportationInitialized) {
  107047. this._teleportationTarget.isVisible = true;
  107048. if (this._isDefaultTeleportationTarget) {
  107049. this._teleportationTarget.getChildren()[0].isVisible = true;
  107050. }
  107051. }
  107052. };
  107053. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  107054. this._teleportActive = false;
  107055. if (this._teleportationInitialized) {
  107056. this._teleportationTarget.isVisible = false;
  107057. if (this._isDefaultTeleportationTarget) {
  107058. this._teleportationTarget.getChildren()[0].isVisible = false;
  107059. }
  107060. }
  107061. };
  107062. VRExperienceHelper.prototype._rotateCamera = function (right) {
  107063. var _this = this;
  107064. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107065. return;
  107066. }
  107067. if (right) {
  107068. this._rotationAngle++;
  107069. }
  107070. else {
  107071. this._rotationAngle--;
  107072. }
  107073. this.currentVRCamera.animations = [];
  107074. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  107075. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107076. var animationRotationKeys = [];
  107077. animationRotationKeys.push({
  107078. frame: 0,
  107079. value: this.currentVRCamera.rotationQuaternion
  107080. });
  107081. animationRotationKeys.push({
  107082. frame: 6,
  107083. value: target
  107084. });
  107085. animationRotation.setKeys(animationRotationKeys);
  107086. animationRotation.setEasingFunction(this._circleEase);
  107087. this.currentVRCamera.animations.push(animationRotation);
  107088. this._postProcessMove.animations = [];
  107089. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107090. var vignetteWeightKeys = [];
  107091. vignetteWeightKeys.push({
  107092. frame: 0,
  107093. value: 0
  107094. });
  107095. vignetteWeightKeys.push({
  107096. frame: 3,
  107097. value: 4
  107098. });
  107099. vignetteWeightKeys.push({
  107100. frame: 6,
  107101. value: 0
  107102. });
  107103. animationPP.setKeys(vignetteWeightKeys);
  107104. animationPP.setEasingFunction(this._circleEase);
  107105. this._postProcessMove.animations.push(animationPP);
  107106. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107107. var vignetteStretchKeys = [];
  107108. vignetteStretchKeys.push({
  107109. frame: 0,
  107110. value: 0
  107111. });
  107112. vignetteStretchKeys.push({
  107113. frame: 3,
  107114. value: 10
  107115. });
  107116. vignetteStretchKeys.push({
  107117. frame: 6,
  107118. value: 0
  107119. });
  107120. animationPP2.setKeys(vignetteStretchKeys);
  107121. animationPP2.setEasingFunction(this._circleEase);
  107122. this._postProcessMove.animations.push(animationPP2);
  107123. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  107124. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  107125. this._postProcessMove.samples = 4;
  107126. this._webVRCamera.attachPostProcess(this._postProcessMove);
  107127. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  107128. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  107129. });
  107130. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  107131. };
  107132. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  107133. if (hit.pickedPoint) {
  107134. if (gazer._teleportationRequestInitiated) {
  107135. this._displayTeleportationTarget();
  107136. this._haloCenter.copyFrom(hit.pickedPoint);
  107137. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  107138. }
  107139. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  107140. if (pickNormal) {
  107141. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  107142. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  107143. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  107144. }
  107145. this._teleportationTarget.position.y += 0.1;
  107146. }
  107147. };
  107148. /**
  107149. * Teleports the users feet to the desired location
  107150. * @param location The location where the user's feet should be placed
  107151. */
  107152. VRExperienceHelper.prototype.teleportCamera = function (location) {
  107153. var _this = this;
  107154. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107155. return;
  107156. }
  107157. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  107158. // offset of the headset from the anchor.
  107159. if (this.webVRCamera.leftCamera) {
  107160. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  107161. this._workingVector.subtractInPlace(this.webVRCamera.position);
  107162. location.subtractToRef(this._workingVector, this._workingVector);
  107163. }
  107164. else {
  107165. this._workingVector.copyFrom(location);
  107166. }
  107167. // Add height to account for user's height offset
  107168. if (this.isInVRMode) {
  107169. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  107170. }
  107171. else {
  107172. this._workingVector.y += this._defaultHeight;
  107173. }
  107174. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  107175. // Create animation from the camera's position to the new location
  107176. this.currentVRCamera.animations = [];
  107177. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107178. var animationCameraTeleportationKeys = [{
  107179. frame: 0,
  107180. value: this.currentVRCamera.position
  107181. },
  107182. {
  107183. frame: 11,
  107184. value: this._workingVector
  107185. }
  107186. ];
  107187. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  107188. animationCameraTeleportation.setEasingFunction(this._circleEase);
  107189. this.currentVRCamera.animations.push(animationCameraTeleportation);
  107190. this._postProcessMove.animations = [];
  107191. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107192. var vignetteWeightKeys = [];
  107193. vignetteWeightKeys.push({
  107194. frame: 0,
  107195. value: 0
  107196. });
  107197. vignetteWeightKeys.push({
  107198. frame: 5,
  107199. value: 8
  107200. });
  107201. vignetteWeightKeys.push({
  107202. frame: 11,
  107203. value: 0
  107204. });
  107205. animationPP.setKeys(vignetteWeightKeys);
  107206. this._postProcessMove.animations.push(animationPP);
  107207. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107208. var vignetteStretchKeys = [];
  107209. vignetteStretchKeys.push({
  107210. frame: 0,
  107211. value: 0
  107212. });
  107213. vignetteStretchKeys.push({
  107214. frame: 5,
  107215. value: 10
  107216. });
  107217. vignetteStretchKeys.push({
  107218. frame: 11,
  107219. value: 0
  107220. });
  107221. animationPP2.setKeys(vignetteStretchKeys);
  107222. this._postProcessMove.animations.push(animationPP2);
  107223. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  107224. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  107225. this._webVRCamera.attachPostProcess(this._postProcessMove);
  107226. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  107227. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  107228. });
  107229. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  107230. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  107231. });
  107232. this._hideTeleportationTarget();
  107233. };
  107234. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  107235. if (normal) {
  107236. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  107237. if (angle < Math.PI / 2) {
  107238. normal.scaleInPlace(-1);
  107239. }
  107240. }
  107241. return normal;
  107242. };
  107243. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  107244. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107245. return;
  107246. }
  107247. var ray = gazer._getForwardRay(this._rayLength);
  107248. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  107249. if (hit) {
  107250. // Populate the contrllers mesh that can be used for drag/drop
  107251. if (gazer._laserPointer) {
  107252. hit.originMesh = gazer._laserPointer.parent;
  107253. }
  107254. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  107255. }
  107256. gazer._currentHit = hit;
  107257. // Moving the gazeTracker on the mesh face targetted
  107258. if (hit && hit.pickedPoint) {
  107259. if (this._displayGaze) {
  107260. var multiplier = 1;
  107261. gazer._gazeTracker.isVisible = true;
  107262. if (gazer._isActionableMesh) {
  107263. multiplier = 3;
  107264. }
  107265. if (this.updateGazeTrackerScale) {
  107266. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  107267. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  107268. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  107269. }
  107270. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  107271. // To avoid z-fighting
  107272. var deltaFighting = 0.002;
  107273. if (pickNormal) {
  107274. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  107275. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  107276. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  107277. }
  107278. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  107279. if (gazer._gazeTracker.position.x < 0) {
  107280. gazer._gazeTracker.position.x += deltaFighting;
  107281. }
  107282. else {
  107283. gazer._gazeTracker.position.x -= deltaFighting;
  107284. }
  107285. if (gazer._gazeTracker.position.y < 0) {
  107286. gazer._gazeTracker.position.y += deltaFighting;
  107287. }
  107288. else {
  107289. gazer._gazeTracker.position.y -= deltaFighting;
  107290. }
  107291. if (gazer._gazeTracker.position.z < 0) {
  107292. gazer._gazeTracker.position.z += deltaFighting;
  107293. }
  107294. else {
  107295. gazer._gazeTracker.position.z -= deltaFighting;
  107296. }
  107297. }
  107298. // Changing the size of the laser pointer based on the distance from the targetted point
  107299. gazer._updatePointerDistance(hit.distance);
  107300. }
  107301. else {
  107302. gazer._updatePointerDistance();
  107303. gazer._gazeTracker.isVisible = false;
  107304. }
  107305. if (hit && hit.pickedMesh) {
  107306. // The object selected is the floor, we're in a teleportation scenario
  107307. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  107308. // Moving the teleportation area to this targetted point
  107309. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  107310. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  107311. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107312. }
  107313. gazer._currentMeshSelected = null;
  107314. if (gazer._teleportationRequestInitiated) {
  107315. this._moveTeleportationSelectorTo(hit, gazer, ray);
  107316. }
  107317. return;
  107318. }
  107319. // If not, we're in a selection scenario
  107320. //this._teleportationAllowed = false;
  107321. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  107322. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  107323. this.onNewMeshPicked.notifyObservers(hit);
  107324. gazer._currentMeshSelected = hit.pickedMesh;
  107325. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  107326. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  107327. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  107328. gazer._isActionableMesh = true;
  107329. }
  107330. else {
  107331. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107332. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107333. gazer._isActionableMesh = false;
  107334. }
  107335. try {
  107336. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  107337. }
  107338. catch (err) {
  107339. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  107340. }
  107341. }
  107342. else {
  107343. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107344. gazer._currentMeshSelected = null;
  107345. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107346. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107347. }
  107348. }
  107349. }
  107350. else {
  107351. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107352. gazer._currentMeshSelected = null;
  107353. //this._teleportationAllowed = false;
  107354. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107355. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107356. }
  107357. };
  107358. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  107359. if (mesh) {
  107360. this.onSelectedMeshUnselected.notifyObservers(mesh);
  107361. }
  107362. };
  107363. /**
  107364. * Sets the color of the laser ray from the vr controllers.
  107365. * @param color new color for the ray.
  107366. */
  107367. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  107368. if (this._leftController) {
  107369. this._leftController._setLaserPointerColor(color);
  107370. }
  107371. if (this._rightController) {
  107372. this._rightController._setLaserPointerColor(color);
  107373. }
  107374. };
  107375. /**
  107376. * Sets the color of the ray from the vr headsets gaze.
  107377. * @param color new color for the ray.
  107378. */
  107379. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  107380. if (!this._cameraGazer._gazeTracker.material) {
  107381. return;
  107382. }
  107383. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  107384. if (this._leftController) {
  107385. this._leftController._gazeTracker.material.emissiveColor = color;
  107386. }
  107387. if (this._rightController) {
  107388. this._rightController._gazeTracker.material.emissiveColor = color;
  107389. }
  107390. };
  107391. /**
  107392. * Exits VR and disposes of the vr experience helper
  107393. */
  107394. VRExperienceHelper.prototype.dispose = function () {
  107395. if (this.isInVRMode) {
  107396. this.exitVR();
  107397. }
  107398. if (this._postProcessMove) {
  107399. this._postProcessMove.dispose();
  107400. }
  107401. if (this._webVRCamera) {
  107402. this._webVRCamera.dispose();
  107403. }
  107404. if (this._vrDeviceOrientationCamera) {
  107405. this._vrDeviceOrientationCamera.dispose();
  107406. }
  107407. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  107408. document.body.removeChild(this._btnVR);
  107409. }
  107410. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  107411. this._deviceOrientationCamera.dispose();
  107412. }
  107413. if (this._cameraGazer) {
  107414. this._cameraGazer.dispose();
  107415. }
  107416. if (this._leftController) {
  107417. this._leftController.dispose();
  107418. }
  107419. if (this._rightController) {
  107420. this._rightController.dispose();
  107421. }
  107422. if (this._teleportationTarget) {
  107423. this._teleportationTarget.dispose();
  107424. }
  107425. this._floorMeshesCollection = [];
  107426. document.removeEventListener("keydown", this._onKeyDown);
  107427. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  107428. window.removeEventListener("resize", this._onResize);
  107429. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  107430. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  107431. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  107432. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  107433. document.onmsfullscreenchange = null;
  107434. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  107435. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  107436. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  107437. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  107438. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  107439. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  107440. this._scene.unregisterBeforeRender(this.beforeRender);
  107441. };
  107442. /**
  107443. * Gets the name of the VRExperienceHelper class
  107444. * @returns "VRExperienceHelper"
  107445. */
  107446. VRExperienceHelper.prototype.getClassName = function () {
  107447. return "VRExperienceHelper";
  107448. };
  107449. return VRExperienceHelper;
  107450. }());
  107451. BABYLON.VRExperienceHelper = VRExperienceHelper;
  107452. })(BABYLON || (BABYLON = {}));
  107453. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  107454. var BABYLON;
  107455. (function (BABYLON) {
  107456. /**
  107457. * WebXR Camera which holds the views for the xrSession
  107458. * @see https://doc.babylonjs.com/how_to/webxr
  107459. */
  107460. var WebXRCamera = /** @class */ (function (_super) {
  107461. __extends(WebXRCamera, _super);
  107462. /**
  107463. * Creates a new webXRCamera, this should only be set at the camera after it has been updated by the xrSessionManager
  107464. * @param name the name of the camera
  107465. * @param scene the scene to add the camera to
  107466. */
  107467. function WebXRCamera(name, scene) {
  107468. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  107469. // Initial camera configuration
  107470. _this.minZ = 0;
  107471. _this.rotationQuaternion = new BABYLON.Quaternion();
  107472. _this.cameraRigMode = BABYLON.Camera.RIG_MODE_CUSTOM;
  107473. _this._updateNumberOfRigCameras(1);
  107474. return _this;
  107475. }
  107476. WebXRCamera.prototype._updateNumberOfRigCameras = function (viewCount) {
  107477. if (viewCount === void 0) { viewCount = 1; }
  107478. while (this.rigCameras.length < viewCount) {
  107479. var newCamera = new BABYLON.TargetCamera("view: " + this.rigCameras.length, BABYLON.Vector3.Zero(), this.getScene());
  107480. newCamera.minZ = 0;
  107481. newCamera.parent = this;
  107482. this.rigCameras.push(newCamera);
  107483. }
  107484. while (this.rigCameras.length > viewCount) {
  107485. var removedCamera = this.rigCameras.pop();
  107486. if (removedCamera) {
  107487. removedCamera.dispose();
  107488. }
  107489. }
  107490. };
  107491. /** @hidden */
  107492. WebXRCamera.prototype._updateForDualEyeDebugging = function (pupilDistance) {
  107493. if (pupilDistance === void 0) { pupilDistance = 0.01; }
  107494. // Create initial camera rigs
  107495. this._updateNumberOfRigCameras(2);
  107496. this.rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  107497. this.rigCameras[0].position.x = -pupilDistance / 2;
  107498. this.rigCameras[0].outputRenderTarget = null;
  107499. this.rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  107500. this.rigCameras[1].position.x = pupilDistance / 2;
  107501. this.rigCameras[1].outputRenderTarget = null;
  107502. };
  107503. /**
  107504. * Updates the cameras position from the current pose information of the XR session
  107505. * @param xrSessionManager the session containing pose information
  107506. * @returns true if the camera has been updated, false if the session did not contain pose or frame data
  107507. */
  107508. WebXRCamera.prototype.updateFromXRSessionManager = function (xrSessionManager) {
  107509. var _this = this;
  107510. // Ensure all frame data is available
  107511. if (!xrSessionManager._currentXRFrame || !xrSessionManager._currentXRFrame.getDevicePose) {
  107512. return false;
  107513. }
  107514. var pose = xrSessionManager._currentXRFrame.getDevicePose(xrSessionManager._frameOfReference);
  107515. if (!pose || !pose.poseModelMatrix) {
  107516. return false;
  107517. }
  107518. // Update the parent cameras matrix
  107519. BABYLON.Matrix.FromFloat32ArrayToRefScaled(pose.poseModelMatrix, 0, 1, WebXRCamera._TmpMatrix);
  107520. if (!this._scene.useRightHandedSystem) {
  107521. WebXRCamera._TmpMatrix.toggleModelMatrixHandInPlace();
  107522. }
  107523. WebXRCamera._TmpMatrix.getTranslationToRef(this.position);
  107524. WebXRCamera._TmpMatrix.getRotationMatrixToRef(WebXRCamera._TmpMatrix);
  107525. BABYLON.Quaternion.FromRotationMatrixToRef(WebXRCamera._TmpMatrix, this.rotationQuaternion);
  107526. this.computeWorldMatrix();
  107527. // Update camera rigs
  107528. this._updateNumberOfRigCameras(xrSessionManager._currentXRFrame.views.length);
  107529. xrSessionManager._currentXRFrame.views.forEach(function (view, i) {
  107530. // Update view/projection matrix
  107531. BABYLON.Matrix.FromFloat32ArrayToRefScaled(pose.getViewMatrix(view), 0, 1, _this.rigCameras[i]._computedViewMatrix);
  107532. BABYLON.Matrix.FromFloat32ArrayToRefScaled(view.projectionMatrix, 0, 1, _this.rigCameras[i]._projectionMatrix);
  107533. if (!_this._scene.useRightHandedSystem) {
  107534. _this.rigCameras[i]._computedViewMatrix.toggleModelMatrixHandInPlace();
  107535. _this.rigCameras[i]._projectionMatrix.toggleProjectionMatrixHandInPlace();
  107536. }
  107537. // Update viewport
  107538. var viewport = xrSessionManager._xrSession.baseLayer.getViewport(view);
  107539. var width = xrSessionManager._xrSession.baseLayer.framebufferWidth;
  107540. var height = xrSessionManager._xrSession.baseLayer.framebufferHeight;
  107541. _this.rigCameras[i].viewport.width = viewport.width / width;
  107542. _this.rigCameras[i].viewport.height = viewport.height / height;
  107543. _this.rigCameras[i].viewport.x = viewport.x / width;
  107544. _this.rigCameras[i].viewport.y = viewport.y / height;
  107545. // Set cameras to render to the session's render target
  107546. _this.rigCameras[i].outputRenderTarget = xrSessionManager._sessionRenderTargetTexture;
  107547. });
  107548. return true;
  107549. };
  107550. WebXRCamera._TmpMatrix = new BABYLON.Matrix();
  107551. return WebXRCamera;
  107552. }(BABYLON.FreeCamera));
  107553. BABYLON.WebXRCamera = WebXRCamera;
  107554. })(BABYLON || (BABYLON = {}));
  107555. //# sourceMappingURL=babylon.webXRCamera.js.map
  107556. var BABYLON;
  107557. (function (BABYLON) {
  107558. /**
  107559. * Manages an XRSession
  107560. * @see https://doc.babylonjs.com/how_to/webxr
  107561. */
  107562. var WebXRSessionManager = /** @class */ (function () {
  107563. /**
  107564. * Constructs a WebXRSessionManager, this must be initialized within a user action before usage
  107565. * @param scene The scene which the session should be created for
  107566. */
  107567. function WebXRSessionManager(scene) {
  107568. this.scene = scene;
  107569. /**
  107570. * Fires every time a new xrFrame arrives which can be used to update the camera
  107571. */
  107572. this.onXRFrameObservable = new BABYLON.Observable();
  107573. /**
  107574. * Fires when the xr session is ended either by the device or manually done
  107575. */
  107576. this.onXRSessionEnded = new BABYLON.Observable();
  107577. /** @hidden */
  107578. this._sessionRenderTargetTexture = null;
  107579. this._tmpMatrix = new BABYLON.Matrix();
  107580. }
  107581. /**
  107582. * Initializes the manager
  107583. * After initialization enterXR can be called to start an XR session
  107584. * @returns Promise which resolves after it is initialized
  107585. */
  107586. WebXRSessionManager.prototype.initializeAsync = function () {
  107587. var _this = this;
  107588. // Check if the browser supports webXR
  107589. this._xrNavigator = navigator;
  107590. if (!this._xrNavigator.xr) {
  107591. return Promise.reject("webXR not supported by this browser");
  107592. }
  107593. // Request the webXR device
  107594. return this._xrNavigator.xr.requestDevice().then(function (device) {
  107595. _this._xrDevice = device;
  107596. return _this.scene.getEngine()._gl.setCompatibleXRDevice(_this._xrDevice);
  107597. });
  107598. };
  107599. /**
  107600. * Enters XR with the desired XR session options, this must be done with a user action (eg. button click event)
  107601. * @param sessionCreationOptions xr options to create the session with
  107602. * @param frameOfReferenceType option to configure how the xr pose is expressed
  107603. * @returns Promise which resolves after it enters XR
  107604. */
  107605. WebXRSessionManager.prototype.enterXRAsync = function (sessionCreationOptions, frameOfReferenceType) {
  107606. var _this = this;
  107607. // initialize session
  107608. return this._xrDevice.requestSession(sessionCreationOptions).then(function (session) {
  107609. _this._xrSession = session;
  107610. // handle when the session is ended (By calling session.end or device ends its own session eg. pressing home button on phone)
  107611. _this._xrSession.addEventListener("end", function () {
  107612. // Remove render target texture and notify frame obervers
  107613. _this._sessionRenderTargetTexture = null;
  107614. // Restore frame buffer to avoid clear on xr framebuffer after session end
  107615. _this.scene.getEngine().restoreDefaultFramebuffer();
  107616. // Need to restart render loop as after the session is ended the last request for new frame will never call callback
  107617. _this.scene.getEngine().customAnimationFrameRequester = null;
  107618. _this.onXRSessionEnded.notifyObservers(null);
  107619. _this.scene.getEngine()._renderLoop();
  107620. }, { once: true });
  107621. _this._xrSession.baseLayer = new XRWebGLLayer(_this._xrSession, _this.scene.getEngine()._gl);
  107622. return _this._xrSession.requestFrameOfReference(frameOfReferenceType);
  107623. }).then(function (frameOfRef) {
  107624. _this._frameOfReference = frameOfRef;
  107625. // Tell the engine's render loop to be driven by the xr session's refresh rate and provide xr pose information
  107626. _this.scene.getEngine().customAnimationFrameRequester = {
  107627. requestAnimationFrame: _this._xrSession.requestAnimationFrame.bind(_this._xrSession),
  107628. renderFunction: function (timestamp, xrFrame) {
  107629. // Store the XR frame in the manager to be consumed by the XR camera to update pose
  107630. _this._currentXRFrame = xrFrame;
  107631. _this.onXRFrameObservable.notifyObservers(null);
  107632. _this.scene.getEngine()._renderLoop();
  107633. }
  107634. };
  107635. // Create render target texture from xr's webgl render target
  107636. _this._sessionRenderTargetTexture = WebXRSessionManager._CreateRenderTargetTextureFromSession(_this._xrSession, _this.scene);
  107637. // Stop window's animation frame and trigger sessions animation frame
  107638. window.cancelAnimationFrame(_this.scene.getEngine()._frameHandler);
  107639. _this.scene.getEngine()._renderLoop();
  107640. });
  107641. };
  107642. /**
  107643. * Stops the xrSession and restores the renderloop
  107644. * @returns Promise which resolves after it exits XR
  107645. */
  107646. WebXRSessionManager.prototype.exitXRAsync = function () {
  107647. return this._xrSession.end();
  107648. };
  107649. /**
  107650. * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR
  107651. * @param ray ray to cast into the environment
  107652. * @returns Promise which resolves with a collision point in the environment if it exists
  107653. */
  107654. WebXRSessionManager.prototype.environmentPointHitTestAsync = function (ray) {
  107655. var _this = this;
  107656. return new Promise(function (res, rej) {
  107657. // Compute left handed inputs to request hit test
  107658. var origin = new Float32Array([ray.origin.x, ray.origin.y, ray.origin.z]);
  107659. var direction = new Float32Array([ray.direction.x, ray.direction.y, ray.direction.z]);
  107660. if (!_this.scene.useRightHandedSystem) {
  107661. origin[2] *= -1;
  107662. direction[2] *= -1;
  107663. }
  107664. // Fire hittest
  107665. _this._xrSession.requestHitTest(origin, direction, _this._frameOfReference)
  107666. .then(function (hits) {
  107667. if (hits.length > 0) {
  107668. BABYLON.Matrix.FromFloat32ArrayToRefScaled(hits[0].hitMatrix, 0, 1.0, _this._tmpMatrix);
  107669. var hitPoint = _this._tmpMatrix.getTranslation();
  107670. if (!_this.scene.useRightHandedSystem) {
  107671. hitPoint.z *= -1;
  107672. }
  107673. res(hitPoint);
  107674. }
  107675. else {
  107676. res(null);
  107677. }
  107678. }).catch(function (e) {
  107679. res(null);
  107680. });
  107681. });
  107682. };
  107683. /**
  107684. * Checks if a session would be supported for the creation options specified
  107685. * @param options creation options to check if they are supported
  107686. * @returns true if supported
  107687. */
  107688. WebXRSessionManager.prototype.supportsSessionAsync = function (options) {
  107689. return this._xrDevice.supportsSession(options).then(function () {
  107690. return true;
  107691. }).catch(function (e) {
  107692. return false;
  107693. });
  107694. };
  107695. /**
  107696. * @hidden
  107697. * Converts the render layer of xrSession to a render target
  107698. * @param session session to create render target for
  107699. * @param scene scene the new render target should be created for
  107700. */
  107701. WebXRSessionManager._CreateRenderTargetTextureFromSession = function (session, scene) {
  107702. // Create internal texture
  107703. var internalTexture = new BABYLON.InternalTexture(scene.getEngine(), BABYLON.InternalTexture.DATASOURCE_UNKNOWN, true);
  107704. internalTexture.width = session.baseLayer.framebufferWidth;
  107705. internalTexture.height = session.baseLayer.framebufferHeight;
  107706. internalTexture._framebuffer = session.baseLayer.framebuffer;
  107707. // Create render target texture from the internal texture
  107708. var renderTargetTexture = new BABYLON.RenderTargetTexture("XR renderTargetTexture", { width: internalTexture.width, height: internalTexture.height }, scene, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, true);
  107709. renderTargetTexture._texture = internalTexture;
  107710. return renderTargetTexture;
  107711. };
  107712. /**
  107713. * Disposes of the session manager
  107714. */
  107715. WebXRSessionManager.prototype.dispose = function () {
  107716. this.onXRFrameObservable.clear();
  107717. this.onXRSessionEnded.clear();
  107718. };
  107719. return WebXRSessionManager;
  107720. }());
  107721. BABYLON.WebXRSessionManager = WebXRSessionManager;
  107722. })(BABYLON || (BABYLON = {}));
  107723. //# sourceMappingURL=babylon.webXRSessionManager.js.map
  107724. var BABYLON;
  107725. (function (BABYLON) {
  107726. /**
  107727. * States of the webXR experience
  107728. */
  107729. var WebXRState;
  107730. (function (WebXRState) {
  107731. /**
  107732. * Transitioning to being in XR mode
  107733. */
  107734. WebXRState[WebXRState["ENTERING_XR"] = 0] = "ENTERING_XR";
  107735. /**
  107736. * Transitioning to non XR mode
  107737. */
  107738. WebXRState[WebXRState["EXITING_XR"] = 1] = "EXITING_XR";
  107739. /**
  107740. * In XR mode and presenting
  107741. */
  107742. WebXRState[WebXRState["IN_XR"] = 2] = "IN_XR";
  107743. /**
  107744. * Not entered XR mode
  107745. */
  107746. WebXRState[WebXRState["NOT_IN_XR"] = 3] = "NOT_IN_XR";
  107747. })(WebXRState = BABYLON.WebXRState || (BABYLON.WebXRState = {}));
  107748. /**
  107749. * Helper class used to enable XR
  107750. * @see https://doc.babylonjs.com/how_to/webxr
  107751. */
  107752. var WebXRExperienceHelper = /** @class */ (function () {
  107753. /**
  107754. * Creates a WebXRExperienceHelper
  107755. * @param scene The scene the helper should be created in
  107756. */
  107757. function WebXRExperienceHelper(scene) {
  107758. this.scene = scene;
  107759. /**
  107760. * The current state of the XR experience (eg. transitioning, in XR or not in XR)
  107761. */
  107762. this.state = WebXRState.NOT_IN_XR;
  107763. /**
  107764. * Fires when the state of the experience helper has changed
  107765. */
  107766. this.onStateChangedObservable = new BABYLON.Observable();
  107767. this._nonVRCamera = null;
  107768. this._originalSceneAutoClear = true;
  107769. this._supported = false;
  107770. this.camera = new BABYLON.WebXRCamera("", scene);
  107771. this._sessionManager = new BABYLON.WebXRSessionManager(scene);
  107772. this.container = new BABYLON.AbstractMesh("", scene);
  107773. }
  107774. WebXRExperienceHelper.prototype._setState = function (val) {
  107775. this.state = val;
  107776. this.onStateChangedObservable.notifyObservers(this.state);
  107777. };
  107778. /**
  107779. * Creates the experience helper
  107780. * @param scene the scene to attach the experience helper to
  107781. * @returns a promise for the experience helper
  107782. */
  107783. WebXRExperienceHelper.CreateAsync = function (scene) {
  107784. var helper = new WebXRExperienceHelper(scene);
  107785. return helper._sessionManager.initializeAsync().then(function () {
  107786. helper._supported = true;
  107787. return helper;
  107788. }).catch(function () {
  107789. return helper;
  107790. });
  107791. };
  107792. /**
  107793. * Exits XR mode and returns the scene to its original state
  107794. * @returns promise that resolves after xr mode has exited
  107795. */
  107796. WebXRExperienceHelper.prototype.exitXRAsync = function () {
  107797. this._setState(WebXRState.EXITING_XR);
  107798. return this._sessionManager.exitXRAsync();
  107799. };
  107800. /**
  107801. * Enters XR mode (This must be done within a user interaction in most browsers eg. button click)
  107802. * @param sessionCreationOptions options for the XR session
  107803. * @param frameOfReference frame of reference of the XR session
  107804. * @returns promise that resolves after xr mode has entered
  107805. */
  107806. WebXRExperienceHelper.prototype.enterXRAsync = function (sessionCreationOptions, frameOfReference) {
  107807. var _this = this;
  107808. this._setState(WebXRState.ENTERING_XR);
  107809. return this._sessionManager.enterXRAsync(sessionCreationOptions, frameOfReference).then(function () {
  107810. // Cache pre xr scene settings
  107811. _this._originalSceneAutoClear = _this.scene.autoClear;
  107812. _this._nonVRCamera = _this.scene.activeCamera;
  107813. // Overwrite current scene settings
  107814. _this.scene.autoClear = false;
  107815. _this.scene.activeCamera = _this.camera;
  107816. _this._sessionManager.onXRFrameObservable.add(function () {
  107817. _this.camera.updateFromXRSessionManager(_this._sessionManager);
  107818. });
  107819. _this._sessionManager.onXRSessionEnded.addOnce(function () {
  107820. // Reset camera rigs output render target to ensure sessions render target is not drawn after it ends
  107821. _this.camera.rigCameras.forEach(function (c) {
  107822. c.outputRenderTarget = null;
  107823. });
  107824. // Restore scene settings
  107825. _this.scene.autoClear = _this._originalSceneAutoClear;
  107826. _this.scene.activeCamera = _this._nonVRCamera;
  107827. _this._sessionManager.onXRFrameObservable.clear();
  107828. _this._setState(WebXRState.NOT_IN_XR);
  107829. });
  107830. _this._setState(WebXRState.IN_XR);
  107831. });
  107832. };
  107833. /**
  107834. * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR
  107835. * @param ray ray to cast into the environment
  107836. * @returns Promise which resolves with a collision point in the environment if it exists
  107837. */
  107838. WebXRExperienceHelper.prototype.environmentPointHitTestAsync = function (ray) {
  107839. return this._sessionManager.environmentPointHitTestAsync(ray);
  107840. };
  107841. /**
  107842. * Checks if the creation options are supported by the xr session
  107843. * @param options creation options
  107844. * @returns true if supported
  107845. */
  107846. WebXRExperienceHelper.prototype.supportsSessionAsync = function (options) {
  107847. if (!this._supported) {
  107848. return Promise.resolve(false);
  107849. }
  107850. return this._sessionManager.supportsSessionAsync(options);
  107851. };
  107852. /**
  107853. * Disposes of the experience helper
  107854. */
  107855. WebXRExperienceHelper.prototype.dispose = function () {
  107856. this.camera.dispose();
  107857. this.container.dispose();
  107858. this.onStateChangedObservable.clear();
  107859. this._sessionManager.dispose();
  107860. };
  107861. return WebXRExperienceHelper;
  107862. }());
  107863. BABYLON.WebXRExperienceHelper = WebXRExperienceHelper;
  107864. })(BABYLON || (BABYLON = {}));
  107865. //# sourceMappingURL=babylon.webXRExperienceHelper.js.map
  107866. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  107867. return new (P || (P = Promise))(function (resolve, reject) {
  107868. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  107869. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  107870. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  107871. step((generator = generator.apply(thisArg, _arguments || [])).next());
  107872. });
  107873. };
  107874. var __generator = (this && this.__generator) || function (thisArg, body) {
  107875. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  107876. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  107877. function verb(n) { return function (v) { return step([n, v]); }; }
  107878. function step(op) {
  107879. if (f) throw new TypeError("Generator is already executing.");
  107880. while (_) try {
  107881. 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;
  107882. if (y = 0, t) op = [op[0] & 2, t.value];
  107883. switch (op[0]) {
  107884. case 0: case 1: t = op; break;
  107885. case 4: _.label++; return { value: op[1], done: false };
  107886. case 5: _.label++; y = op[1]; op = [0]; continue;
  107887. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  107888. default:
  107889. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  107890. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  107891. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  107892. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  107893. if (t[2]) _.ops.pop();
  107894. _.trys.pop(); continue;
  107895. }
  107896. op = body.call(thisArg, _);
  107897. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  107898. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  107899. }
  107900. };
  107901. var BABYLON;
  107902. (function (BABYLON) {
  107903. /**
  107904. * Button which can be used to enter a different mode of XR
  107905. */
  107906. var WebXREnterExitUIButton = /** @class */ (function () {
  107907. /**
  107908. * Creates a WebXREnterExitUIButton
  107909. * @param element button element
  107910. * @param initializationOptions XR initialization options for the button
  107911. */
  107912. function WebXREnterExitUIButton(
  107913. /** button element */
  107914. element,
  107915. /** XR initialization options for the button */
  107916. initializationOptions) {
  107917. this.element = element;
  107918. this.initializationOptions = initializationOptions;
  107919. }
  107920. /**
  107921. * Overwritable function which can be used to update the button's visuals when the state changes
  107922. * @param activeButton the current active button in the UI
  107923. */
  107924. WebXREnterExitUIButton.prototype.update = function (activeButton) {
  107925. };
  107926. return WebXREnterExitUIButton;
  107927. }());
  107928. BABYLON.WebXREnterExitUIButton = WebXREnterExitUIButton;
  107929. /**
  107930. * Options to create the webXR UI
  107931. */
  107932. var WebXREnterExitUIOptions = /** @class */ (function () {
  107933. function WebXREnterExitUIOptions() {
  107934. }
  107935. return WebXREnterExitUIOptions;
  107936. }());
  107937. BABYLON.WebXREnterExitUIOptions = WebXREnterExitUIOptions;
  107938. /**
  107939. * UI to allow the user to enter/exit XR mode
  107940. */
  107941. var WebXREnterExitUI = /** @class */ (function () {
  107942. function WebXREnterExitUI(scene, options) {
  107943. var _this = this;
  107944. this.scene = scene;
  107945. this._buttons = [];
  107946. this._activeButton = null;
  107947. this._overlay = document.createElement("div");
  107948. this._overlay.style.cssText = "z-index:11;position: absolute; right: 20px;bottom: 50px;";
  107949. if (options.customButtons) {
  107950. this._buttons = options.customButtons;
  107951. }
  107952. else {
  107953. var hmdBtn = document.createElement("button");
  107954. 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;";
  107955. hmdBtn.innerText = "HMD";
  107956. this._buttons.push(new WebXREnterExitUIButton(hmdBtn, { immersive: true, outputContext: options.outputCanvasContext }));
  107957. this._buttons[this._buttons.length - 1].update = function (activeButton) {
  107958. this.element.style.display = (activeButton === null || activeButton === this) ? "" : "none";
  107959. this.element.innerText = activeButton === this ? "EXIT" : "HMD";
  107960. };
  107961. var windowBtn = document.createElement("button");
  107962. windowBtn.style.cssText = hmdBtn.style.cssText;
  107963. windowBtn.innerText = "Window";
  107964. this._buttons.push(new WebXREnterExitUIButton(windowBtn, { immersive: false, environmentIntegration: true, outputContext: options.outputCanvasContext }));
  107965. this._buttons[this._buttons.length - 1].update = function (activeButton) {
  107966. this.element.style.display = (activeButton === null || activeButton === this) ? "" : "none";
  107967. this.element.innerText = activeButton === this ? "EXIT" : "Window";
  107968. };
  107969. this._updateButtons(null);
  107970. }
  107971. var renderCanvas = scene.getEngine().getRenderingCanvas();
  107972. if (renderCanvas && renderCanvas.parentNode) {
  107973. renderCanvas.parentNode.appendChild(this._overlay);
  107974. scene.onDisposeObservable.addOnce(function () {
  107975. _this.dispose();
  107976. });
  107977. }
  107978. }
  107979. /**
  107980. * Creates UI to allow the user to enter/exit XR mode
  107981. * @param scene the scene to add the ui to
  107982. * @param helper the xr experience helper to enter/exit xr with
  107983. * @param options options to configure the UI
  107984. * @returns the created ui
  107985. */
  107986. WebXREnterExitUI.CreateAsync = function (scene, helper, options) {
  107987. var _this = this;
  107988. var ui = new WebXREnterExitUI(scene, options);
  107989. var supportedPromises = ui._buttons.map(function (btn) {
  107990. return helper.supportsSessionAsync(btn.initializationOptions);
  107991. });
  107992. helper.onStateChangedObservable.add(function (state) {
  107993. if (state == BABYLON.WebXRState.NOT_IN_XR) {
  107994. ui._updateButtons(null);
  107995. }
  107996. });
  107997. return Promise.all(supportedPromises).then(function (results) {
  107998. results.forEach(function (supported, i) {
  107999. if (supported) {
  108000. ui._overlay.appendChild(ui._buttons[i].element);
  108001. ui._buttons[i].element.onclick = function () { return __awaiter(_this, void 0, void 0, function () {
  108002. return __generator(this, function (_a) {
  108003. switch (_a.label) {
  108004. case 0:
  108005. if (!(helper.state == BABYLON.WebXRState.IN_XR)) return [3 /*break*/, 2];
  108006. ui._updateButtons(null);
  108007. return [4 /*yield*/, helper.exitXRAsync()];
  108008. case 1:
  108009. _a.sent();
  108010. return [2 /*return*/];
  108011. case 2:
  108012. if (!(helper.state == BABYLON.WebXRState.NOT_IN_XR)) return [3 /*break*/, 4];
  108013. ui._updateButtons(ui._buttons[i]);
  108014. return [4 /*yield*/, helper.enterXRAsync(ui._buttons[i].initializationOptions, "eye-level")];
  108015. case 3:
  108016. _a.sent();
  108017. _a.label = 4;
  108018. case 4: return [2 /*return*/];
  108019. }
  108020. });
  108021. }); };
  108022. }
  108023. });
  108024. });
  108025. };
  108026. WebXREnterExitUI.prototype._updateButtons = function (activeButton) {
  108027. var _this = this;
  108028. this._activeButton = activeButton;
  108029. this._buttons.forEach(function (b) {
  108030. b.update(_this._activeButton);
  108031. });
  108032. };
  108033. /**
  108034. * Disposes of the object
  108035. */
  108036. WebXREnterExitUI.prototype.dispose = function () {
  108037. var renderCanvas = this.scene.getEngine().getRenderingCanvas();
  108038. if (renderCanvas && renderCanvas.parentNode && renderCanvas.parentNode.contains(this._overlay)) {
  108039. renderCanvas.parentNode.removeChild(this._overlay);
  108040. }
  108041. };
  108042. return WebXREnterExitUI;
  108043. }());
  108044. BABYLON.WebXREnterExitUI = WebXREnterExitUI;
  108045. })(BABYLON || (BABYLON = {}));
  108046. //# sourceMappingURL=babylon.webXREnterExitUI.js.map
  108047. var BABYLON;
  108048. (function (BABYLON) {
  108049. /**
  108050. * Creates a canvas that is added/removed from the webpage when entering/exiting XR
  108051. */
  108052. var WebXRManagedOutputCanvas = /** @class */ (function () {
  108053. /**
  108054. * Initializes the canvas to be added/removed upon entering/exiting xr
  108055. * @param helper the xr experience helper used to trigger adding/removing of the canvas
  108056. * @param canvas The canvas to be added/removed (If not specified a full screen canvas will be created)
  108057. */
  108058. function WebXRManagedOutputCanvas(helper, canvas) {
  108059. var _this = this;
  108060. this._canvas = null;
  108061. /**
  108062. * xrpresent context of the canvas which can be used to display/mirror xr content
  108063. */
  108064. this.canvasContext = null;
  108065. if (!canvas) {
  108066. canvas = document.createElement('canvas');
  108067. canvas.style.cssText = "position:absolute; bottom:0px;right:0px;z-index:10;width:100%;height:100%;background-color: #000000;";
  108068. }
  108069. this._setManagedOutputCanvas(canvas);
  108070. helper.onStateChangedObservable.add(function (stateInfo) {
  108071. if (stateInfo == BABYLON.WebXRState.ENTERING_XR) {
  108072. // 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
  108073. _this._addCanvas();
  108074. }
  108075. else if (helper.state == BABYLON.WebXRState.NOT_IN_XR) {
  108076. _this._removeCanvas();
  108077. }
  108078. });
  108079. }
  108080. /**
  108081. * Disposes of the object
  108082. */
  108083. WebXRManagedOutputCanvas.prototype.dispose = function () {
  108084. this._removeCanvas();
  108085. this._setManagedOutputCanvas(null);
  108086. };
  108087. WebXRManagedOutputCanvas.prototype._setManagedOutputCanvas = function (canvas) {
  108088. this._removeCanvas();
  108089. if (!canvas) {
  108090. this._canvas = null;
  108091. this.canvasContext = null;
  108092. }
  108093. else {
  108094. this._canvas = canvas;
  108095. this.canvasContext = this._canvas.getContext('xrpresent');
  108096. }
  108097. };
  108098. WebXRManagedOutputCanvas.prototype._addCanvas = function () {
  108099. if (this._canvas) {
  108100. document.body.appendChild(this._canvas);
  108101. }
  108102. };
  108103. WebXRManagedOutputCanvas.prototype._removeCanvas = function () {
  108104. if (this._canvas && document.body.contains(this._canvas)) {
  108105. document.body.removeChild(this._canvas);
  108106. }
  108107. };
  108108. return WebXRManagedOutputCanvas;
  108109. }());
  108110. BABYLON.WebXRManagedOutputCanvas = WebXRManagedOutputCanvas;
  108111. })(BABYLON || (BABYLON = {}));
  108112. //# sourceMappingURL=babylon.webXRManagedOutputCanvas.js.map
  108113. var BABYLON;
  108114. (function (BABYLON) {
  108115. /**
  108116. * Represents an XR input
  108117. */
  108118. var WebXRController = /** @class */ (function () {
  108119. /**
  108120. * Creates the controller
  108121. * @see https://doc.babylonjs.com/how_to/webxr
  108122. * @param scene the scene which the controller should be associated to
  108123. */
  108124. function WebXRController(scene) {
  108125. this.pointer = new BABYLON.AbstractMesh("controllerPointer", scene);
  108126. }
  108127. /**
  108128. * Disposes of the object
  108129. */
  108130. WebXRController.prototype.dispose = function () {
  108131. if (this.grip) {
  108132. this.grip.dispose();
  108133. }
  108134. this.pointer.dispose();
  108135. };
  108136. return WebXRController;
  108137. }());
  108138. BABYLON.WebXRController = WebXRController;
  108139. /**
  108140. * XR input used to track XR inputs such as controllers/rays
  108141. */
  108142. var WebXRInput = /** @class */ (function () {
  108143. /**
  108144. * Initializes the WebXRInput
  108145. * @param helper experience helper which the input should be created for
  108146. */
  108147. function WebXRInput(helper) {
  108148. var _this = this;
  108149. this.helper = helper;
  108150. /**
  108151. * XR controllers being tracked
  108152. */
  108153. this.controllers = [];
  108154. this._tmpMatrix = new BABYLON.Matrix();
  108155. this._frameObserver = helper._sessionManager.onXRFrameObservable.add(function () {
  108156. if (!helper._sessionManager._currentXRFrame || !helper._sessionManager._currentXRFrame.getDevicePose) {
  108157. return;
  108158. }
  108159. var xrFrame = helper._sessionManager._currentXRFrame;
  108160. var inputSources = helper._sessionManager._xrSession.getInputSources();
  108161. inputSources.forEach(function (input, i) {
  108162. var inputPose = xrFrame.getInputPose(input, helper._sessionManager._frameOfReference);
  108163. if (inputPose) {
  108164. if (_this.controllers.length <= i) {
  108165. _this.controllers.push(new WebXRController(helper.container.getScene()));
  108166. }
  108167. var controller = _this.controllers[i];
  108168. // Manage the grip if it exists
  108169. if (inputPose.gripMatrix) {
  108170. if (!controller.grip) {
  108171. controller.grip = new BABYLON.AbstractMesh("controllerGrip", helper.container.getScene());
  108172. }
  108173. BABYLON.Matrix.FromFloat32ArrayToRefScaled(inputPose.gripMatrix, 0, 1, _this._tmpMatrix);
  108174. if (!controller.grip.getScene().useRightHandedSystem) {
  108175. _this._tmpMatrix.toggleModelMatrixHandInPlace();
  108176. }
  108177. if (!controller.grip.rotationQuaternion) {
  108178. controller.grip.rotationQuaternion = new BABYLON.Quaternion();
  108179. }
  108180. _this._tmpMatrix.decompose(controller.grip.scaling, controller.grip.rotationQuaternion, controller.grip.position);
  108181. }
  108182. // Manager pointer of controller
  108183. BABYLON.Matrix.FromFloat32ArrayToRefScaled(inputPose.targetRay.transformMatrix, 0, 1, _this._tmpMatrix);
  108184. if (!controller.pointer.getScene().useRightHandedSystem) {
  108185. _this._tmpMatrix.toggleModelMatrixHandInPlace();
  108186. }
  108187. if (!controller.pointer.rotationQuaternion) {
  108188. controller.pointer.rotationQuaternion = new BABYLON.Quaternion();
  108189. }
  108190. _this._tmpMatrix.decompose(controller.pointer.scaling, controller.pointer.rotationQuaternion, controller.pointer.position);
  108191. }
  108192. });
  108193. });
  108194. }
  108195. /**
  108196. * Disposes of the object
  108197. */
  108198. WebXRInput.prototype.dispose = function () {
  108199. this.controllers.forEach(function (c) {
  108200. c.dispose();
  108201. });
  108202. this.helper._sessionManager.onXRFrameObservable.remove(this._frameObserver);
  108203. };
  108204. return WebXRInput;
  108205. }());
  108206. BABYLON.WebXRInput = WebXRInput;
  108207. })(BABYLON || (BABYLON = {}));
  108208. //# sourceMappingURL=babylon.webXRInput.js.map
  108209. // Mainly based on these 2 articles :
  108210. // 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
  108211. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  108212. var BABYLON;
  108213. (function (BABYLON) {
  108214. /**
  108215. * Defines the potential axis of a Joystick
  108216. */
  108217. var JoystickAxis;
  108218. (function (JoystickAxis) {
  108219. /** X axis */
  108220. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  108221. /** Y axis */
  108222. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  108223. /** Z axis */
  108224. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  108225. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  108226. /**
  108227. * Class used to define virtual joystick (used in touch mode)
  108228. */
  108229. var VirtualJoystick = /** @class */ (function () {
  108230. /**
  108231. * Creates a new virtual joystick
  108232. * @param leftJoystick defines that the joystick is for left hand (false by default)
  108233. */
  108234. function VirtualJoystick(leftJoystick) {
  108235. var _this = this;
  108236. if (leftJoystick) {
  108237. this._leftJoystick = true;
  108238. }
  108239. else {
  108240. this._leftJoystick = false;
  108241. }
  108242. VirtualJoystick._globalJoystickIndex++;
  108243. // By default left & right arrow keys are moving the X
  108244. // and up & down keys are moving the Y
  108245. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  108246. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  108247. this.reverseLeftRight = false;
  108248. this.reverseUpDown = false;
  108249. // collections of pointers
  108250. this._touches = new BABYLON.StringDictionary();
  108251. this.deltaPosition = BABYLON.Vector3.Zero();
  108252. this._joystickSensibility = 25;
  108253. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  108254. this._onResize = function (evt) {
  108255. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  108256. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  108257. if (VirtualJoystick.vjCanvas) {
  108258. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  108259. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  108260. }
  108261. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  108262. };
  108263. // injecting a canvas element on top of the canvas 3D game
  108264. if (!VirtualJoystick.vjCanvas) {
  108265. window.addEventListener("resize", this._onResize, false);
  108266. VirtualJoystick.vjCanvas = document.createElement("canvas");
  108267. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  108268. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  108269. VirtualJoystick.vjCanvas.width = window.innerWidth;
  108270. VirtualJoystick.vjCanvas.height = window.innerHeight;
  108271. VirtualJoystick.vjCanvas.style.width = "100%";
  108272. VirtualJoystick.vjCanvas.style.height = "100%";
  108273. VirtualJoystick.vjCanvas.style.position = "absolute";
  108274. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  108275. VirtualJoystick.vjCanvas.style.top = "0px";
  108276. VirtualJoystick.vjCanvas.style.left = "0px";
  108277. VirtualJoystick.vjCanvas.style.zIndex = "5";
  108278. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  108279. // Support for jQuery PEP polyfill
  108280. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  108281. var context = VirtualJoystick.vjCanvas.getContext('2d');
  108282. if (!context) {
  108283. throw new Error("Unable to create canvas for virtual joystick");
  108284. }
  108285. VirtualJoystick.vjCanvasContext = context;
  108286. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  108287. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  108288. document.body.appendChild(VirtualJoystick.vjCanvas);
  108289. }
  108290. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  108291. this.pressed = false;
  108292. // default joystick color
  108293. this._joystickColor = "cyan";
  108294. this._joystickPointerID = -1;
  108295. // current joystick position
  108296. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  108297. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  108298. // origin joystick position
  108299. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  108300. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  108301. this._onPointerDownHandlerRef = function (evt) {
  108302. _this._onPointerDown(evt);
  108303. };
  108304. this._onPointerMoveHandlerRef = function (evt) {
  108305. _this._onPointerMove(evt);
  108306. };
  108307. this._onPointerUpHandlerRef = function (evt) {
  108308. _this._onPointerUp(evt);
  108309. };
  108310. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  108311. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  108312. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  108313. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  108314. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  108315. evt.preventDefault(); // Disables system menu
  108316. }, false);
  108317. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  108318. }
  108319. /**
  108320. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  108321. * @param newJoystickSensibility defines the new sensibility
  108322. */
  108323. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  108324. this._joystickSensibility = newJoystickSensibility;
  108325. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  108326. };
  108327. VirtualJoystick.prototype._onPointerDown = function (e) {
  108328. var positionOnScreenCondition;
  108329. e.preventDefault();
  108330. if (this._leftJoystick === true) {
  108331. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  108332. }
  108333. else {
  108334. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  108335. }
  108336. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  108337. // First contact will be dedicated to the virtual joystick
  108338. this._joystickPointerID = e.pointerId;
  108339. this._joystickPointerStartPos.x = e.clientX;
  108340. this._joystickPointerStartPos.y = e.clientY;
  108341. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  108342. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  108343. this._deltaJoystickVector.x = 0;
  108344. this._deltaJoystickVector.y = 0;
  108345. this.pressed = true;
  108346. this._touches.add(e.pointerId.toString(), e);
  108347. }
  108348. else {
  108349. // You can only trigger the action buttons with a joystick declared
  108350. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  108351. this._action();
  108352. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  108353. }
  108354. }
  108355. };
  108356. VirtualJoystick.prototype._onPointerMove = function (e) {
  108357. // If the current pointer is the one associated to the joystick (first touch contact)
  108358. if (this._joystickPointerID == e.pointerId) {
  108359. this._joystickPointerPos.x = e.clientX;
  108360. this._joystickPointerPos.y = e.clientY;
  108361. this._deltaJoystickVector = this._joystickPointerPos.clone();
  108362. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  108363. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  108364. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  108365. switch (this._axisTargetedByLeftAndRight) {
  108366. case JoystickAxis.X:
  108367. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  108368. break;
  108369. case JoystickAxis.Y:
  108370. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  108371. break;
  108372. case JoystickAxis.Z:
  108373. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  108374. break;
  108375. }
  108376. var directionUpDown = this.reverseUpDown ? 1 : -1;
  108377. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  108378. switch (this._axisTargetedByUpAndDown) {
  108379. case JoystickAxis.X:
  108380. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  108381. break;
  108382. case JoystickAxis.Y:
  108383. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  108384. break;
  108385. case JoystickAxis.Z:
  108386. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  108387. break;
  108388. }
  108389. }
  108390. else {
  108391. var data = this._touches.get(e.pointerId.toString());
  108392. if (data) {
  108393. data.x = e.clientX;
  108394. data.y = e.clientY;
  108395. }
  108396. }
  108397. };
  108398. VirtualJoystick.prototype._onPointerUp = function (e) {
  108399. if (this._joystickPointerID == e.pointerId) {
  108400. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  108401. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  108402. this._joystickPointerID = -1;
  108403. this.pressed = false;
  108404. }
  108405. else {
  108406. var touch = this._touches.get(e.pointerId.toString());
  108407. if (touch) {
  108408. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  108409. }
  108410. }
  108411. this._deltaJoystickVector.x = 0;
  108412. this._deltaJoystickVector.y = 0;
  108413. this._touches.remove(e.pointerId.toString());
  108414. };
  108415. /**
  108416. * Change the color of the virtual joystick
  108417. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  108418. */
  108419. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  108420. this._joystickColor = newColor;
  108421. };
  108422. /**
  108423. * Defines a callback to call when the joystick is touched
  108424. * @param action defines the callback
  108425. */
  108426. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  108427. this._action = action;
  108428. };
  108429. /**
  108430. * Defines which axis you'd like to control for left & right
  108431. * @param axis defines the axis to use
  108432. */
  108433. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  108434. switch (axis) {
  108435. case JoystickAxis.X:
  108436. case JoystickAxis.Y:
  108437. case JoystickAxis.Z:
  108438. this._axisTargetedByLeftAndRight = axis;
  108439. break;
  108440. default:
  108441. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  108442. break;
  108443. }
  108444. };
  108445. /**
  108446. * Defines which axis you'd like to control for up & down
  108447. * @param axis defines the axis to use
  108448. */
  108449. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  108450. switch (axis) {
  108451. case JoystickAxis.X:
  108452. case JoystickAxis.Y:
  108453. case JoystickAxis.Z:
  108454. this._axisTargetedByUpAndDown = axis;
  108455. break;
  108456. default:
  108457. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  108458. break;
  108459. }
  108460. };
  108461. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  108462. var _this = this;
  108463. if (this.pressed) {
  108464. this._touches.forEach(function (key, touch) {
  108465. if (touch.pointerId === _this._joystickPointerID) {
  108466. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  108467. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  108468. VirtualJoystick.vjCanvasContext.beginPath();
  108469. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  108470. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  108471. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  108472. VirtualJoystick.vjCanvasContext.stroke();
  108473. VirtualJoystick.vjCanvasContext.closePath();
  108474. VirtualJoystick.vjCanvasContext.beginPath();
  108475. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  108476. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  108477. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  108478. VirtualJoystick.vjCanvasContext.stroke();
  108479. VirtualJoystick.vjCanvasContext.closePath();
  108480. VirtualJoystick.vjCanvasContext.beginPath();
  108481. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  108482. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  108483. VirtualJoystick.vjCanvasContext.stroke();
  108484. VirtualJoystick.vjCanvasContext.closePath();
  108485. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  108486. }
  108487. else {
  108488. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  108489. VirtualJoystick.vjCanvasContext.beginPath();
  108490. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  108491. VirtualJoystick.vjCanvasContext.beginPath();
  108492. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  108493. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  108494. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  108495. VirtualJoystick.vjCanvasContext.stroke();
  108496. VirtualJoystick.vjCanvasContext.closePath();
  108497. touch.prevX = touch.x;
  108498. touch.prevY = touch.y;
  108499. }
  108500. });
  108501. }
  108502. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  108503. };
  108504. /**
  108505. * Release internal HTML canvas
  108506. */
  108507. VirtualJoystick.prototype.releaseCanvas = function () {
  108508. if (VirtualJoystick.vjCanvas) {
  108509. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  108510. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  108511. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  108512. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  108513. window.removeEventListener("resize", this._onResize);
  108514. document.body.removeChild(VirtualJoystick.vjCanvas);
  108515. VirtualJoystick.vjCanvas = null;
  108516. }
  108517. };
  108518. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  108519. VirtualJoystick._globalJoystickIndex = 0;
  108520. return VirtualJoystick;
  108521. }());
  108522. BABYLON.VirtualJoystick = VirtualJoystick;
  108523. })(BABYLON || (BABYLON = {}));
  108524. //# sourceMappingURL=babylon.virtualJoystick.js.map
  108525. var BABYLON;
  108526. (function (BABYLON) {
  108527. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  108528. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  108529. });
  108530. /**
  108531. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  108532. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  108533. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  108534. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  108535. */
  108536. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  108537. __extends(VirtualJoysticksCamera, _super);
  108538. /**
  108539. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  108540. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  108541. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  108542. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  108543. * @param name Define the name of the camera in the scene
  108544. * @param position Define the start position of the camera in the scene
  108545. * @param scene Define the scene the camera belongs to
  108546. */
  108547. function VirtualJoysticksCamera(name, position, scene) {
  108548. var _this = _super.call(this, name, position, scene) || this;
  108549. _this.inputs.addVirtualJoystick();
  108550. return _this;
  108551. }
  108552. /**
  108553. * Gets the current object class name.
  108554. * @return the class name
  108555. */
  108556. VirtualJoysticksCamera.prototype.getClassName = function () {
  108557. return "VirtualJoysticksCamera";
  108558. };
  108559. return VirtualJoysticksCamera;
  108560. }(BABYLON.FreeCamera));
  108561. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  108562. })(BABYLON || (BABYLON = {}));
  108563. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  108564. var BABYLON;
  108565. (function (BABYLON) {
  108566. /**
  108567. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  108568. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  108569. */
  108570. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  108571. function FreeCameraVirtualJoystickInput() {
  108572. }
  108573. /**
  108574. * Gets the left stick of the virtual joystick.
  108575. * @returns The virtual Joystick
  108576. */
  108577. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  108578. return this._leftjoystick;
  108579. };
  108580. /**
  108581. * Gets the right stick of the virtual joystick.
  108582. * @returns The virtual Joystick
  108583. */
  108584. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  108585. return this._rightjoystick;
  108586. };
  108587. /**
  108588. * Update the current camera state depending on the inputs that have been used this frame.
  108589. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  108590. */
  108591. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  108592. if (this._leftjoystick) {
  108593. var camera = this.camera;
  108594. var speed = camera._computeLocalCameraSpeed() * 50;
  108595. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  108596. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  108597. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  108598. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  108599. if (!this._leftjoystick.pressed) {
  108600. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  108601. }
  108602. if (!this._rightjoystick.pressed) {
  108603. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  108604. }
  108605. }
  108606. };
  108607. /**
  108608. * Attach the input controls to a specific dom element to get the input from.
  108609. * @param element Defines the element the controls should be listened from
  108610. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  108611. */
  108612. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  108613. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  108614. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  108615. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  108616. this._leftjoystick.setJoystickSensibility(0.15);
  108617. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  108618. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  108619. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  108620. this._rightjoystick.reverseUpDown = true;
  108621. this._rightjoystick.setJoystickSensibility(0.05);
  108622. this._rightjoystick.setJoystickColor("yellow");
  108623. };
  108624. /**
  108625. * Detach the current controls from the specified dom element.
  108626. * @param element Defines the element to stop listening the inputs from
  108627. */
  108628. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  108629. this._leftjoystick.releaseCanvas();
  108630. this._rightjoystick.releaseCanvas();
  108631. };
  108632. /**
  108633. * Gets the class name of the current intput.
  108634. * @returns the class name
  108635. */
  108636. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  108637. return "FreeCameraVirtualJoystickInput";
  108638. };
  108639. /**
  108640. * Get the friendly name associated with the input class.
  108641. * @returns the input friendly name
  108642. */
  108643. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  108644. return "virtualJoystick";
  108645. };
  108646. return FreeCameraVirtualJoystickInput;
  108647. }());
  108648. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  108649. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  108650. })(BABYLON || (BABYLON = {}));
  108651. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  108652. var BABYLON;
  108653. (function (BABYLON) {
  108654. /**
  108655. * Class used to specify simplification options
  108656. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108657. */
  108658. var SimplificationSettings = /** @class */ (function () {
  108659. /**
  108660. * Creates a SimplificationSettings
  108661. * @param quality expected quality
  108662. * @param distance distance when this optimized version should be used
  108663. * @param optimizeMesh already optimized mesh
  108664. */
  108665. function SimplificationSettings(
  108666. /** expected quality */
  108667. quality,
  108668. /** distance when this optimized version should be used */
  108669. distance,
  108670. /** already optimized mesh */
  108671. optimizeMesh) {
  108672. this.quality = quality;
  108673. this.distance = distance;
  108674. this.optimizeMesh = optimizeMesh;
  108675. }
  108676. return SimplificationSettings;
  108677. }());
  108678. BABYLON.SimplificationSettings = SimplificationSettings;
  108679. /**
  108680. * Queue used to order the simplification tasks
  108681. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108682. */
  108683. var SimplificationQueue = /** @class */ (function () {
  108684. /**
  108685. * Creates a new queue
  108686. */
  108687. function SimplificationQueue() {
  108688. this.running = false;
  108689. this._simplificationArray = [];
  108690. }
  108691. /**
  108692. * Adds a new simplification task
  108693. * @param task defines a task to add
  108694. */
  108695. SimplificationQueue.prototype.addTask = function (task) {
  108696. this._simplificationArray.push(task);
  108697. };
  108698. /**
  108699. * Execute next task
  108700. */
  108701. SimplificationQueue.prototype.executeNext = function () {
  108702. var task = this._simplificationArray.pop();
  108703. if (task) {
  108704. this.running = true;
  108705. this.runSimplification(task);
  108706. }
  108707. else {
  108708. this.running = false;
  108709. }
  108710. };
  108711. /**
  108712. * Execute a simplification task
  108713. * @param task defines the task to run
  108714. */
  108715. SimplificationQueue.prototype.runSimplification = function (task) {
  108716. var _this = this;
  108717. if (task.parallelProcessing) {
  108718. //parallel simplifier
  108719. task.settings.forEach(function (setting) {
  108720. var simplifier = _this.getSimplifier(task);
  108721. simplifier.simplify(setting, function (newMesh) {
  108722. task.mesh.addLODLevel(setting.distance, newMesh);
  108723. newMesh.isVisible = true;
  108724. //check if it is the last
  108725. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  108726. //all done, run the success callback.
  108727. task.successCallback();
  108728. }
  108729. _this.executeNext();
  108730. });
  108731. });
  108732. }
  108733. else {
  108734. //single simplifier.
  108735. var simplifier = this.getSimplifier(task);
  108736. var runDecimation = function (setting, callback) {
  108737. simplifier.simplify(setting, function (newMesh) {
  108738. task.mesh.addLODLevel(setting.distance, newMesh);
  108739. newMesh.isVisible = true;
  108740. //run the next quality level
  108741. callback();
  108742. });
  108743. };
  108744. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  108745. runDecimation(task.settings[loop.index], function () {
  108746. loop.executeNext();
  108747. });
  108748. }, function () {
  108749. //execution ended, run the success callback.
  108750. if (task.successCallback) {
  108751. task.successCallback();
  108752. }
  108753. _this.executeNext();
  108754. });
  108755. }
  108756. };
  108757. SimplificationQueue.prototype.getSimplifier = function (task) {
  108758. switch (task.simplificationType) {
  108759. case SimplificationType.QUADRATIC:
  108760. default:
  108761. return new QuadraticErrorSimplification(task.mesh);
  108762. }
  108763. };
  108764. return SimplificationQueue;
  108765. }());
  108766. BABYLON.SimplificationQueue = SimplificationQueue;
  108767. /**
  108768. * The implemented types of simplification
  108769. * At the moment only Quadratic Error Decimation is implemented
  108770. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108771. */
  108772. var SimplificationType;
  108773. (function (SimplificationType) {
  108774. /** Quadratic error decimation */
  108775. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  108776. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  108777. var DecimationTriangle = /** @class */ (function () {
  108778. function DecimationTriangle(vertices) {
  108779. this.vertices = vertices;
  108780. this.error = new Array(4);
  108781. this.deleted = false;
  108782. this.isDirty = false;
  108783. this.deletePending = false;
  108784. this.borderFactor = 0;
  108785. }
  108786. return DecimationTriangle;
  108787. }());
  108788. var DecimationVertex = /** @class */ (function () {
  108789. function DecimationVertex(position, id) {
  108790. this.position = position;
  108791. this.id = id;
  108792. this.isBorder = true;
  108793. this.q = new QuadraticMatrix();
  108794. this.triangleCount = 0;
  108795. this.triangleStart = 0;
  108796. this.originalOffsets = [];
  108797. }
  108798. DecimationVertex.prototype.updatePosition = function (newPosition) {
  108799. this.position.copyFrom(newPosition);
  108800. };
  108801. return DecimationVertex;
  108802. }());
  108803. var QuadraticMatrix = /** @class */ (function () {
  108804. function QuadraticMatrix(data) {
  108805. this.data = new Array(10);
  108806. for (var i = 0; i < 10; ++i) {
  108807. if (data && data[i]) {
  108808. this.data[i] = data[i];
  108809. }
  108810. else {
  108811. this.data[i] = 0;
  108812. }
  108813. }
  108814. }
  108815. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  108816. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  108817. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  108818. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  108819. return det;
  108820. };
  108821. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  108822. for (var i = 0; i < 10; ++i) {
  108823. this.data[i] += matrix.data[i];
  108824. }
  108825. };
  108826. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  108827. for (var i = 0; i < 10; ++i) {
  108828. this.data[i] += data[i];
  108829. }
  108830. };
  108831. QuadraticMatrix.prototype.add = function (matrix) {
  108832. var m = new QuadraticMatrix();
  108833. for (var i = 0; i < 10; ++i) {
  108834. m.data[i] = this.data[i] + matrix.data[i];
  108835. }
  108836. return m;
  108837. };
  108838. QuadraticMatrix.FromData = function (a, b, c, d) {
  108839. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  108840. };
  108841. //returning an array to avoid garbage collection
  108842. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  108843. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  108844. };
  108845. return QuadraticMatrix;
  108846. }());
  108847. var Reference = /** @class */ (function () {
  108848. function Reference(vertexId, triangleId) {
  108849. this.vertexId = vertexId;
  108850. this.triangleId = triangleId;
  108851. }
  108852. return Reference;
  108853. }());
  108854. /**
  108855. * An implementation of the Quadratic Error simplification algorithm.
  108856. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  108857. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  108858. * @author RaananW
  108859. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108860. */
  108861. var QuadraticErrorSimplification = /** @class */ (function () {
  108862. function QuadraticErrorSimplification(_mesh) {
  108863. this._mesh = _mesh;
  108864. this.syncIterations = 5000;
  108865. this.aggressiveness = 7;
  108866. this.decimationIterations = 100;
  108867. this.boundingBoxEpsilon = BABYLON.Epsilon;
  108868. }
  108869. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  108870. var _this = this;
  108871. this.initDecimatedMesh();
  108872. //iterating through the submeshes array, one after the other.
  108873. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  108874. _this.initWithMesh(loop.index, function () {
  108875. _this.runDecimation(settings, loop.index, function () {
  108876. loop.executeNext();
  108877. });
  108878. }, settings.optimizeMesh);
  108879. }, function () {
  108880. setTimeout(function () {
  108881. successCallback(_this._reconstructedMesh);
  108882. }, 0);
  108883. });
  108884. };
  108885. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  108886. var _this = this;
  108887. var targetCount = ~~(this.triangles.length * settings.quality);
  108888. var deletedTriangles = 0;
  108889. var triangleCount = this.triangles.length;
  108890. var iterationFunction = function (iteration, callback) {
  108891. setTimeout(function () {
  108892. if (iteration % 5 === 0) {
  108893. _this.updateMesh(iteration === 0);
  108894. }
  108895. for (var i = 0; i < _this.triangles.length; ++i) {
  108896. _this.triangles[i].isDirty = false;
  108897. }
  108898. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  108899. var trianglesIterator = function (i) {
  108900. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  108901. var t = _this.triangles[tIdx];
  108902. if (!t) {
  108903. return;
  108904. }
  108905. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  108906. return;
  108907. }
  108908. for (var j = 0; j < 3; ++j) {
  108909. if (t.error[j] < threshold) {
  108910. var deleted0 = [];
  108911. var deleted1 = [];
  108912. var v0 = t.vertices[j];
  108913. var v1 = t.vertices[(j + 1) % 3];
  108914. if (v0.isBorder || v1.isBorder) {
  108915. continue;
  108916. }
  108917. var p = BABYLON.Vector3.Zero();
  108918. var n = BABYLON.Vector3.Zero();
  108919. var uv = BABYLON.Vector2.Zero();
  108920. var color = new BABYLON.Color4(0, 0, 0, 1);
  108921. _this.calculateError(v0, v1, p, n, uv, color);
  108922. var delTr = new Array();
  108923. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr)) {
  108924. continue;
  108925. }
  108926. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr)) {
  108927. continue;
  108928. }
  108929. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
  108930. continue;
  108931. }
  108932. var uniqueArray = new Array();
  108933. delTr.forEach(function (deletedT) {
  108934. if (uniqueArray.indexOf(deletedT) === -1) {
  108935. deletedT.deletePending = true;
  108936. uniqueArray.push(deletedT);
  108937. }
  108938. });
  108939. if (uniqueArray.length % 2 !== 0) {
  108940. continue;
  108941. }
  108942. v0.q = v1.q.add(v0.q);
  108943. v0.updatePosition(p);
  108944. var tStart = _this.references.length;
  108945. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  108946. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  108947. var tCount = _this.references.length - tStart;
  108948. if (tCount <= v0.triangleCount) {
  108949. if (tCount) {
  108950. for (var c = 0; c < tCount; c++) {
  108951. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  108952. }
  108953. }
  108954. }
  108955. else {
  108956. v0.triangleStart = tStart;
  108957. }
  108958. v0.triangleCount = tCount;
  108959. break;
  108960. }
  108961. }
  108962. };
  108963. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  108964. }, 0);
  108965. };
  108966. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  108967. if (triangleCount - deletedTriangles <= targetCount) {
  108968. loop.breakLoop();
  108969. }
  108970. else {
  108971. iterationFunction(loop.index, function () {
  108972. loop.executeNext();
  108973. });
  108974. }
  108975. }, function () {
  108976. setTimeout(function () {
  108977. //reconstruct this part of the mesh
  108978. _this.reconstructMesh(submeshIndex);
  108979. successCallback();
  108980. }, 0);
  108981. });
  108982. };
  108983. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  108984. var _this = this;
  108985. this.vertices = [];
  108986. this.triangles = [];
  108987. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108988. var indices = this._mesh.getIndices();
  108989. var submesh = this._mesh.subMeshes[submeshIndex];
  108990. var findInVertices = function (positionToSearch) {
  108991. if (optimizeMesh) {
  108992. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  108993. if (_this.vertices[ii].position.equals(positionToSearch)) {
  108994. return _this.vertices[ii];
  108995. }
  108996. }
  108997. }
  108998. return null;
  108999. };
  109000. var vertexReferences = [];
  109001. var vertexInit = function (i) {
  109002. if (!positionData) {
  109003. return;
  109004. }
  109005. var offset = i + submesh.verticesStart;
  109006. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  109007. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  109008. vertex.originalOffsets.push(offset);
  109009. if (vertex.id === _this.vertices.length) {
  109010. _this.vertices.push(vertex);
  109011. }
  109012. vertexReferences.push(vertex.id);
  109013. };
  109014. //var totalVertices = mesh.getTotalVertices();
  109015. var totalVertices = submesh.verticesCount;
  109016. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  109017. var indicesInit = function (i) {
  109018. if (!indices) {
  109019. return;
  109020. }
  109021. var offset = (submesh.indexStart / 3) + i;
  109022. var pos = (offset * 3);
  109023. var i0 = indices[pos + 0];
  109024. var i1 = indices[pos + 1];
  109025. var i2 = indices[pos + 2];
  109026. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  109027. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  109028. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  109029. var triangle = new DecimationTriangle([v0, v1, v2]);
  109030. triangle.originalOffset = pos;
  109031. _this.triangles.push(triangle);
  109032. };
  109033. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  109034. _this.init(callback);
  109035. });
  109036. });
  109037. };
  109038. QuadraticErrorSimplification.prototype.init = function (callback) {
  109039. var _this = this;
  109040. var triangleInit1 = function (i) {
  109041. var t = _this.triangles[i];
  109042. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  109043. for (var j = 0; j < 3; j++) {
  109044. 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))));
  109045. }
  109046. };
  109047. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  109048. var triangleInit2 = function (i) {
  109049. var t = _this.triangles[i];
  109050. for (var j = 0; j < 3; ++j) {
  109051. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  109052. }
  109053. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  109054. };
  109055. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  109056. callback();
  109057. });
  109058. });
  109059. };
  109060. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  109061. var newTriangles = [];
  109062. var i;
  109063. for (i = 0; i < this.vertices.length; ++i) {
  109064. this.vertices[i].triangleCount = 0;
  109065. }
  109066. var t;
  109067. var j;
  109068. for (i = 0; i < this.triangles.length; ++i) {
  109069. if (!this.triangles[i].deleted) {
  109070. t = this.triangles[i];
  109071. for (j = 0; j < 3; ++j) {
  109072. t.vertices[j].triangleCount = 1;
  109073. }
  109074. newTriangles.push(t);
  109075. }
  109076. }
  109077. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  109078. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  109079. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  109080. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  109081. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  109082. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  109083. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  109084. var vertexCount = 0;
  109085. for (i = 0; i < this.vertices.length; ++i) {
  109086. var vertex = this.vertices[i];
  109087. vertex.id = vertexCount;
  109088. if (vertex.triangleCount) {
  109089. vertex.originalOffsets.forEach(function (originalOffset) {
  109090. if (!normalData) {
  109091. return;
  109092. }
  109093. newPositionData.push(vertex.position.x);
  109094. newPositionData.push(vertex.position.y);
  109095. newPositionData.push(vertex.position.z);
  109096. newNormalData.push(normalData[originalOffset * 3]);
  109097. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  109098. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  109099. if (uvs && uvs.length) {
  109100. newUVsData.push(uvs[(originalOffset * 2)]);
  109101. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  109102. }
  109103. else if (colorsData && colorsData.length) {
  109104. newColorsData.push(colorsData[(originalOffset * 4)]);
  109105. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  109106. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  109107. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  109108. }
  109109. ++vertexCount;
  109110. });
  109111. }
  109112. }
  109113. var startingIndex = this._reconstructedMesh.getTotalIndices();
  109114. var startingVertex = this._reconstructedMesh.getTotalVertices();
  109115. var submeshesArray = this._reconstructedMesh.subMeshes;
  109116. this._reconstructedMesh.subMeshes = [];
  109117. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  109118. var originalIndices = this._mesh.getIndices();
  109119. for (i = 0; i < newTriangles.length; ++i) {
  109120. t = newTriangles[i]; //now get the new referencing point for each vertex
  109121. [0, 1, 2].forEach(function (idx) {
  109122. var id = originalIndices[t.originalOffset + idx];
  109123. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  109124. if (offset < 0) {
  109125. offset = 0;
  109126. }
  109127. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  109128. });
  109129. }
  109130. //overwriting the old vertex buffers and indices.
  109131. this._reconstructedMesh.setIndices(newIndicesArray);
  109132. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  109133. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  109134. if (newUVsData.length > 0) {
  109135. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  109136. }
  109137. if (newColorsData.length > 0) {
  109138. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  109139. }
  109140. //create submesh
  109141. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  109142. if (submeshIndex > 0) {
  109143. this._reconstructedMesh.subMeshes = [];
  109144. submeshesArray.forEach(function (submesh) {
  109145. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  109146. });
  109147. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  109148. }
  109149. };
  109150. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  109151. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  109152. this._reconstructedMesh.material = this._mesh.material;
  109153. this._reconstructedMesh.parent = this._mesh.parent;
  109154. this._reconstructedMesh.isVisible = false;
  109155. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  109156. };
  109157. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  109158. for (var i = 0; i < vertex1.triangleCount; ++i) {
  109159. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  109160. if (t.deleted) {
  109161. continue;
  109162. }
  109163. var s = this.references[vertex1.triangleStart + i].vertexId;
  109164. var v1 = t.vertices[(s + 1) % 3];
  109165. var v2 = t.vertices[(s + 2) % 3];
  109166. if ((v1 === vertex2 || v2 === vertex2)) {
  109167. deletedArray[i] = true;
  109168. delTr.push(t);
  109169. continue;
  109170. }
  109171. var d1 = v1.position.subtract(point);
  109172. d1 = d1.normalize();
  109173. var d2 = v2.position.subtract(point);
  109174. d2 = d2.normalize();
  109175. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999) {
  109176. return true;
  109177. }
  109178. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  109179. deletedArray[i] = false;
  109180. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2) {
  109181. return true;
  109182. }
  109183. }
  109184. return false;
  109185. };
  109186. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  109187. var newDeleted = deletedTriangles;
  109188. for (var i = 0; i < vertex.triangleCount; ++i) {
  109189. var ref = this.references[vertex.triangleStart + i];
  109190. var t = this.triangles[ref.triangleId];
  109191. if (t.deleted) {
  109192. continue;
  109193. }
  109194. if (deletedArray[i] && t.deletePending) {
  109195. t.deleted = true;
  109196. newDeleted++;
  109197. continue;
  109198. }
  109199. t.vertices[ref.vertexId] = origVertex;
  109200. t.isDirty = true;
  109201. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  109202. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  109203. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  109204. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  109205. this.references.push(ref);
  109206. }
  109207. return newDeleted;
  109208. };
  109209. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  109210. for (var i = 0; i < this.vertices.length; ++i) {
  109211. var vCount = [];
  109212. var vId = [];
  109213. var v = this.vertices[i];
  109214. var j;
  109215. for (j = 0; j < v.triangleCount; ++j) {
  109216. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  109217. for (var ii = 0; ii < 3; ii++) {
  109218. var ofs = 0;
  109219. var vv = triangle.vertices[ii];
  109220. while (ofs < vCount.length) {
  109221. if (vId[ofs] === vv.id) {
  109222. break;
  109223. }
  109224. ++ofs;
  109225. }
  109226. if (ofs === vCount.length) {
  109227. vCount.push(1);
  109228. vId.push(vv.id);
  109229. }
  109230. else {
  109231. vCount[ofs]++;
  109232. }
  109233. }
  109234. }
  109235. for (j = 0; j < vCount.length; ++j) {
  109236. if (vCount[j] === 1) {
  109237. this.vertices[vId[j]].isBorder = true;
  109238. }
  109239. else {
  109240. this.vertices[vId[j]].isBorder = false;
  109241. }
  109242. }
  109243. }
  109244. };
  109245. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  109246. if (identifyBorders === void 0) { identifyBorders = false; }
  109247. var i;
  109248. if (!identifyBorders) {
  109249. var newTrianglesVector = [];
  109250. for (i = 0; i < this.triangles.length; ++i) {
  109251. if (!this.triangles[i].deleted) {
  109252. newTrianglesVector.push(this.triangles[i]);
  109253. }
  109254. }
  109255. this.triangles = newTrianglesVector;
  109256. }
  109257. for (i = 0; i < this.vertices.length; ++i) {
  109258. this.vertices[i].triangleCount = 0;
  109259. this.vertices[i].triangleStart = 0;
  109260. }
  109261. var t;
  109262. var j;
  109263. var v;
  109264. for (i = 0; i < this.triangles.length; ++i) {
  109265. t = this.triangles[i];
  109266. for (j = 0; j < 3; ++j) {
  109267. v = t.vertices[j];
  109268. v.triangleCount++;
  109269. }
  109270. }
  109271. var tStart = 0;
  109272. for (i = 0; i < this.vertices.length; ++i) {
  109273. this.vertices[i].triangleStart = tStart;
  109274. tStart += this.vertices[i].triangleCount;
  109275. this.vertices[i].triangleCount = 0;
  109276. }
  109277. var newReferences = new Array(this.triangles.length * 3);
  109278. for (i = 0; i < this.triangles.length; ++i) {
  109279. t = this.triangles[i];
  109280. for (j = 0; j < 3; ++j) {
  109281. v = t.vertices[j];
  109282. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  109283. v.triangleCount++;
  109284. }
  109285. }
  109286. this.references = newReferences;
  109287. if (identifyBorders) {
  109288. this.identifyBorder();
  109289. }
  109290. };
  109291. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  109292. var x = point.x;
  109293. var y = point.y;
  109294. var z = point.z;
  109295. 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
  109296. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  109297. };
  109298. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  109299. var q = vertex1.q.add(vertex2.q);
  109300. var border = vertex1.isBorder && vertex2.isBorder;
  109301. var error = 0;
  109302. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  109303. if (qDet !== 0 && !border) {
  109304. if (!pointResult) {
  109305. pointResult = BABYLON.Vector3.Zero();
  109306. }
  109307. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  109308. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  109309. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  109310. error = this.vertexError(q, pointResult);
  109311. }
  109312. else {
  109313. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  109314. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  109315. var error1 = this.vertexError(q, vertex1.position);
  109316. var error2 = this.vertexError(q, vertex2.position);
  109317. var error3 = this.vertexError(q, p3);
  109318. error = Math.min(error1, error2, error3);
  109319. if (error === error1) {
  109320. if (pointResult) {
  109321. pointResult.copyFrom(vertex1.position);
  109322. }
  109323. }
  109324. else if (error === error2) {
  109325. if (pointResult) {
  109326. pointResult.copyFrom(vertex2.position);
  109327. }
  109328. }
  109329. else {
  109330. if (pointResult) {
  109331. pointResult.copyFrom(p3);
  109332. }
  109333. }
  109334. }
  109335. return error;
  109336. };
  109337. return QuadraticErrorSimplification;
  109338. }());
  109339. })(BABYLON || (BABYLON = {}));
  109340. //# sourceMappingURL=babylon.meshSimplification.js.map
  109341. var BABYLON;
  109342. (function (BABYLON) {
  109343. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  109344. get: function () {
  109345. if (!this._simplificationQueue) {
  109346. this._simplificationQueue = new BABYLON.SimplificationQueue();
  109347. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  109348. if (!component) {
  109349. component = new SimplicationQueueSceneComponent(this);
  109350. this._addComponent(component);
  109351. }
  109352. }
  109353. return this._simplificationQueue;
  109354. },
  109355. set: function (value) {
  109356. this._simplificationQueue = value;
  109357. },
  109358. enumerable: true,
  109359. configurable: true
  109360. });
  109361. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  109362. if (parallelProcessing === void 0) { parallelProcessing = true; }
  109363. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  109364. this.getScene().simplificationQueue.addTask({
  109365. settings: settings,
  109366. parallelProcessing: parallelProcessing,
  109367. mesh: this,
  109368. simplificationType: simplificationType,
  109369. successCallback: successCallback
  109370. });
  109371. return this;
  109372. };
  109373. /**
  109374. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  109375. * created in a scene
  109376. */
  109377. var SimplicationQueueSceneComponent = /** @class */ (function () {
  109378. /**
  109379. * Creates a new instance of the component for the given scene
  109380. * @param scene Defines the scene to register the component in
  109381. */
  109382. function SimplicationQueueSceneComponent(scene) {
  109383. /**
  109384. * The component name helpfull to identify the component in the list of scene components.
  109385. */
  109386. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  109387. this.scene = scene;
  109388. }
  109389. /**
  109390. * Registers the component in a given scene
  109391. */
  109392. SimplicationQueueSceneComponent.prototype.register = function () {
  109393. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  109394. };
  109395. /**
  109396. * Rebuilds the elements related to this component in case of
  109397. * context lost for instance.
  109398. */
  109399. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  109400. // Nothing to do for this component
  109401. };
  109402. /**
  109403. * Disposes the component and the associated ressources
  109404. */
  109405. SimplicationQueueSceneComponent.prototype.dispose = function () {
  109406. // Nothing to do for this component
  109407. };
  109408. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  109409. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  109410. this.scene._simplificationQueue.executeNext();
  109411. }
  109412. };
  109413. return SimplicationQueueSceneComponent;
  109414. }());
  109415. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  109416. })(BABYLON || (BABYLON = {}));
  109417. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  109418. var BABYLON;
  109419. (function (BABYLON) {
  109420. /**
  109421. * Class used to represent a specific level of detail of a mesh
  109422. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  109423. */
  109424. var MeshLODLevel = /** @class */ (function () {
  109425. /**
  109426. * Creates a new LOD level
  109427. * @param distance defines the distance where this level should star being displayed
  109428. * @param mesh defines the mesh to use to render this level
  109429. */
  109430. function MeshLODLevel(
  109431. /** Defines the distance where this level should star being displayed */
  109432. distance,
  109433. /** Defines the mesh to use to render this level */
  109434. mesh) {
  109435. this.distance = distance;
  109436. this.mesh = mesh;
  109437. }
  109438. return MeshLODLevel;
  109439. }());
  109440. BABYLON.MeshLODLevel = MeshLODLevel;
  109441. })(BABYLON || (BABYLON = {}));
  109442. //# sourceMappingURL=babylon.meshLODLevel.js.map
  109443. var BABYLON;
  109444. (function (BABYLON) {
  109445. /**
  109446. * Defines the root class used to create scene optimization to use with SceneOptimizer
  109447. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109448. */
  109449. var SceneOptimization = /** @class */ (function () {
  109450. /**
  109451. * Creates the SceneOptimization object
  109452. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109453. * @param desc defines the description associated with the optimization
  109454. */
  109455. function SceneOptimization(
  109456. /**
  109457. * Defines the priority of this optimization (0 by default which means first in the list)
  109458. */
  109459. priority) {
  109460. if (priority === void 0) { priority = 0; }
  109461. this.priority = priority;
  109462. }
  109463. /**
  109464. * Gets a string describing the action executed by the current optimization
  109465. * @returns description string
  109466. */
  109467. SceneOptimization.prototype.getDescription = function () {
  109468. return "";
  109469. };
  109470. /**
  109471. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109472. * @param scene defines the current scene where to apply this optimization
  109473. * @param optimizer defines the current optimizer
  109474. * @returns true if everything that can be done was applied
  109475. */
  109476. SceneOptimization.prototype.apply = function (scene, optimizer) {
  109477. return true;
  109478. };
  109479. return SceneOptimization;
  109480. }());
  109481. BABYLON.SceneOptimization = SceneOptimization;
  109482. /**
  109483. * Defines an optimization used to reduce the size of render target textures
  109484. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109485. */
  109486. var TextureOptimization = /** @class */ (function (_super) {
  109487. __extends(TextureOptimization, _super);
  109488. /**
  109489. * Creates the TextureOptimization object
  109490. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109491. * @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
  109492. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  109493. */
  109494. function TextureOptimization(
  109495. /**
  109496. * Defines the priority of this optimization (0 by default which means first in the list)
  109497. */
  109498. priority,
  109499. /**
  109500. * 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
  109501. */
  109502. maximumSize,
  109503. /**
  109504. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  109505. */
  109506. step) {
  109507. if (priority === void 0) { priority = 0; }
  109508. if (maximumSize === void 0) { maximumSize = 1024; }
  109509. if (step === void 0) { step = 0.5; }
  109510. var _this = _super.call(this, priority) || this;
  109511. _this.priority = priority;
  109512. _this.maximumSize = maximumSize;
  109513. _this.step = step;
  109514. return _this;
  109515. }
  109516. /**
  109517. * Gets a string describing the action executed by the current optimization
  109518. * @returns description string
  109519. */
  109520. TextureOptimization.prototype.getDescription = function () {
  109521. return "Reducing render target texture size to " + this.maximumSize;
  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. TextureOptimization.prototype.apply = function (scene, optimizer) {
  109530. var allDone = true;
  109531. for (var index = 0; index < scene.textures.length; index++) {
  109532. var texture = scene.textures[index];
  109533. if (!texture.canRescale || texture.getContext) {
  109534. continue;
  109535. }
  109536. var currentSize = texture.getSize();
  109537. var maxDimension = Math.max(currentSize.width, currentSize.height);
  109538. if (maxDimension > this.maximumSize) {
  109539. texture.scale(this.step);
  109540. allDone = false;
  109541. }
  109542. }
  109543. return allDone;
  109544. };
  109545. return TextureOptimization;
  109546. }(SceneOptimization));
  109547. BABYLON.TextureOptimization = TextureOptimization;
  109548. /**
  109549. * Defines an optimization used to increase or decrease the rendering resolution
  109550. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109551. */
  109552. var HardwareScalingOptimization = /** @class */ (function (_super) {
  109553. __extends(HardwareScalingOptimization, _super);
  109554. /**
  109555. * Creates the HardwareScalingOptimization object
  109556. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109557. * @param maximumScale defines the maximum scale to use (2 by default)
  109558. * @param step defines the step to use between two passes (0.5 by default)
  109559. */
  109560. function HardwareScalingOptimization(
  109561. /**
  109562. * Defines the priority of this optimization (0 by default which means first in the list)
  109563. */
  109564. priority,
  109565. /**
  109566. * Defines the maximum scale to use (2 by default)
  109567. */
  109568. maximumScale,
  109569. /**
  109570. * Defines the step to use between two passes (0.5 by default)
  109571. */
  109572. step) {
  109573. if (priority === void 0) { priority = 0; }
  109574. if (maximumScale === void 0) { maximumScale = 2; }
  109575. if (step === void 0) { step = 0.25; }
  109576. var _this = _super.call(this, priority) || this;
  109577. _this.priority = priority;
  109578. _this.maximumScale = maximumScale;
  109579. _this.step = step;
  109580. _this._currentScale = -1;
  109581. _this._directionOffset = 1;
  109582. return _this;
  109583. }
  109584. /**
  109585. * Gets a string describing the action executed by the current optimization
  109586. * @return description string
  109587. */
  109588. HardwareScalingOptimization.prototype.getDescription = function () {
  109589. return "Setting hardware scaling level to " + this._currentScale;
  109590. };
  109591. /**
  109592. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109593. * @param scene defines the current scene where to apply this optimization
  109594. * @param optimizer defines the current optimizer
  109595. * @returns true if everything that can be done was applied
  109596. */
  109597. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  109598. if (this._currentScale === -1) {
  109599. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  109600. if (this._currentScale > this.maximumScale) {
  109601. this._directionOffset = -1;
  109602. }
  109603. }
  109604. this._currentScale += this._directionOffset * this.step;
  109605. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  109606. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  109607. };
  109608. return HardwareScalingOptimization;
  109609. }(SceneOptimization));
  109610. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  109611. /**
  109612. * Defines an optimization used to remove shadows
  109613. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109614. */
  109615. var ShadowsOptimization = /** @class */ (function (_super) {
  109616. __extends(ShadowsOptimization, _super);
  109617. function ShadowsOptimization() {
  109618. return _super !== null && _super.apply(this, arguments) || this;
  109619. }
  109620. /**
  109621. * Gets a string describing the action executed by the current optimization
  109622. * @return description string
  109623. */
  109624. ShadowsOptimization.prototype.getDescription = function () {
  109625. return "Turning shadows on/off";
  109626. };
  109627. /**
  109628. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109629. * @param scene defines the current scene where to apply this optimization
  109630. * @param optimizer defines the current optimizer
  109631. * @returns true if everything that can be done was applied
  109632. */
  109633. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  109634. scene.shadowsEnabled = optimizer.isInImprovementMode;
  109635. return true;
  109636. };
  109637. return ShadowsOptimization;
  109638. }(SceneOptimization));
  109639. BABYLON.ShadowsOptimization = ShadowsOptimization;
  109640. /**
  109641. * Defines an optimization used to turn post-processes off
  109642. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109643. */
  109644. var PostProcessesOptimization = /** @class */ (function (_super) {
  109645. __extends(PostProcessesOptimization, _super);
  109646. function PostProcessesOptimization() {
  109647. return _super !== null && _super.apply(this, arguments) || this;
  109648. }
  109649. /**
  109650. * Gets a string describing the action executed by the current optimization
  109651. * @return description string
  109652. */
  109653. PostProcessesOptimization.prototype.getDescription = function () {
  109654. return "Turning post-processes on/off";
  109655. };
  109656. /**
  109657. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109658. * @param scene defines the current scene where to apply this optimization
  109659. * @param optimizer defines the current optimizer
  109660. * @returns true if everything that can be done was applied
  109661. */
  109662. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  109663. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  109664. return true;
  109665. };
  109666. return PostProcessesOptimization;
  109667. }(SceneOptimization));
  109668. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  109669. /**
  109670. * Defines an optimization used to turn lens flares off
  109671. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109672. */
  109673. var LensFlaresOptimization = /** @class */ (function (_super) {
  109674. __extends(LensFlaresOptimization, _super);
  109675. function LensFlaresOptimization() {
  109676. return _super !== null && _super.apply(this, arguments) || this;
  109677. }
  109678. /**
  109679. * Gets a string describing the action executed by the current optimization
  109680. * @return description string
  109681. */
  109682. LensFlaresOptimization.prototype.getDescription = function () {
  109683. return "Turning lens flares on/off";
  109684. };
  109685. /**
  109686. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109687. * @param scene defines the current scene where to apply this optimization
  109688. * @param optimizer defines the current optimizer
  109689. * @returns true if everything that can be done was applied
  109690. */
  109691. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  109692. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  109693. return true;
  109694. };
  109695. return LensFlaresOptimization;
  109696. }(SceneOptimization));
  109697. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  109698. /**
  109699. * Defines an optimization based on user defined callback.
  109700. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109701. */
  109702. var CustomOptimization = /** @class */ (function (_super) {
  109703. __extends(CustomOptimization, _super);
  109704. function CustomOptimization() {
  109705. return _super !== null && _super.apply(this, arguments) || this;
  109706. }
  109707. /**
  109708. * Gets a string describing the action executed by the current optimization
  109709. * @returns description string
  109710. */
  109711. CustomOptimization.prototype.getDescription = function () {
  109712. if (this.onGetDescription) {
  109713. return this.onGetDescription();
  109714. }
  109715. return "Running user defined callback";
  109716. };
  109717. /**
  109718. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109719. * @param scene defines the current scene where to apply this optimization
  109720. * @param optimizer defines the current optimizer
  109721. * @returns true if everything that can be done was applied
  109722. */
  109723. CustomOptimization.prototype.apply = function (scene, optimizer) {
  109724. if (this.onApply) {
  109725. return this.onApply(scene, optimizer);
  109726. }
  109727. return true;
  109728. };
  109729. return CustomOptimization;
  109730. }(SceneOptimization));
  109731. BABYLON.CustomOptimization = CustomOptimization;
  109732. /**
  109733. * Defines an optimization used to turn particles off
  109734. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109735. */
  109736. var ParticlesOptimization = /** @class */ (function (_super) {
  109737. __extends(ParticlesOptimization, _super);
  109738. function ParticlesOptimization() {
  109739. return _super !== null && _super.apply(this, arguments) || this;
  109740. }
  109741. /**
  109742. * Gets a string describing the action executed by the current optimization
  109743. * @return description string
  109744. */
  109745. ParticlesOptimization.prototype.getDescription = function () {
  109746. return "Turning particles on/off";
  109747. };
  109748. /**
  109749. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109750. * @param scene defines the current scene where to apply this optimization
  109751. * @param optimizer defines the current optimizer
  109752. * @returns true if everything that can be done was applied
  109753. */
  109754. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  109755. scene.particlesEnabled = optimizer.isInImprovementMode;
  109756. return true;
  109757. };
  109758. return ParticlesOptimization;
  109759. }(SceneOptimization));
  109760. BABYLON.ParticlesOptimization = ParticlesOptimization;
  109761. /**
  109762. * Defines an optimization used to turn render targets off
  109763. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109764. */
  109765. var RenderTargetsOptimization = /** @class */ (function (_super) {
  109766. __extends(RenderTargetsOptimization, _super);
  109767. function RenderTargetsOptimization() {
  109768. return _super !== null && _super.apply(this, arguments) || this;
  109769. }
  109770. /**
  109771. * Gets a string describing the action executed by the current optimization
  109772. * @return description string
  109773. */
  109774. RenderTargetsOptimization.prototype.getDescription = function () {
  109775. return "Turning render targets off";
  109776. };
  109777. /**
  109778. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109779. * @param scene defines the current scene where to apply this optimization
  109780. * @param optimizer defines the current optimizer
  109781. * @returns true if everything that can be done was applied
  109782. */
  109783. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  109784. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  109785. return true;
  109786. };
  109787. return RenderTargetsOptimization;
  109788. }(SceneOptimization));
  109789. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  109790. /**
  109791. * Defines an optimization used to merge meshes with compatible materials
  109792. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109793. */
  109794. var MergeMeshesOptimization = /** @class */ (function (_super) {
  109795. __extends(MergeMeshesOptimization, _super);
  109796. function MergeMeshesOptimization() {
  109797. var _this = _super !== null && _super.apply(this, arguments) || this;
  109798. _this._canBeMerged = function (abstractMesh) {
  109799. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  109800. return false;
  109801. }
  109802. var mesh = abstractMesh;
  109803. if (mesh.isDisposed()) {
  109804. return false;
  109805. }
  109806. if (!mesh.isVisible || !mesh.isEnabled()) {
  109807. return false;
  109808. }
  109809. if (mesh.instances.length > 0) {
  109810. return false;
  109811. }
  109812. if (mesh.skeleton || mesh.hasLODLevels) {
  109813. return false;
  109814. }
  109815. return true;
  109816. };
  109817. return _this;
  109818. }
  109819. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  109820. /**
  109821. * Gets or sets a boolean which defines if optimization octree has to be updated
  109822. */
  109823. get: function () {
  109824. return MergeMeshesOptimization._UpdateSelectionTree;
  109825. },
  109826. /**
  109827. * Gets or sets a boolean which defines if optimization octree has to be updated
  109828. */
  109829. set: function (value) {
  109830. MergeMeshesOptimization._UpdateSelectionTree = value;
  109831. },
  109832. enumerable: true,
  109833. configurable: true
  109834. });
  109835. /**
  109836. * Gets a string describing the action executed by the current optimization
  109837. * @return description string
  109838. */
  109839. MergeMeshesOptimization.prototype.getDescription = function () {
  109840. return "Merging similar meshes together";
  109841. };
  109842. /**
  109843. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109844. * @param scene defines the current scene where to apply this optimization
  109845. * @param optimizer defines the current optimizer
  109846. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  109847. * @returns true if everything that can be done was applied
  109848. */
  109849. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  109850. var globalPool = scene.meshes.slice(0);
  109851. var globalLength = globalPool.length;
  109852. for (var index = 0; index < globalLength; index++) {
  109853. var currentPool = new Array();
  109854. var current = globalPool[index];
  109855. // Checks
  109856. if (!this._canBeMerged(current)) {
  109857. continue;
  109858. }
  109859. currentPool.push(current);
  109860. // Find compatible meshes
  109861. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  109862. var otherMesh = globalPool[subIndex];
  109863. if (!this._canBeMerged(otherMesh)) {
  109864. continue;
  109865. }
  109866. if (otherMesh.material !== current.material) {
  109867. continue;
  109868. }
  109869. if (otherMesh.checkCollisions !== current.checkCollisions) {
  109870. continue;
  109871. }
  109872. currentPool.push(otherMesh);
  109873. globalLength--;
  109874. globalPool.splice(subIndex, 1);
  109875. subIndex--;
  109876. }
  109877. if (currentPool.length < 2) {
  109878. continue;
  109879. }
  109880. // Merge meshes
  109881. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  109882. }
  109883. // Call the octree system optimization if it is defined.
  109884. var sceneAsAny = scene;
  109885. if (sceneAsAny.createOrUpdateSelectionOctree) {
  109886. if (updateSelectionTree != undefined) {
  109887. if (updateSelectionTree) {
  109888. sceneAsAny.createOrUpdateSelectionOctree();
  109889. }
  109890. }
  109891. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  109892. sceneAsAny.createOrUpdateSelectionOctree();
  109893. }
  109894. }
  109895. return true;
  109896. };
  109897. MergeMeshesOptimization._UpdateSelectionTree = false;
  109898. return MergeMeshesOptimization;
  109899. }(SceneOptimization));
  109900. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  109901. /**
  109902. * Defines a list of options used by SceneOptimizer
  109903. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109904. */
  109905. var SceneOptimizerOptions = /** @class */ (function () {
  109906. /**
  109907. * Creates a new list of options used by SceneOptimizer
  109908. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  109909. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  109910. */
  109911. function SceneOptimizerOptions(
  109912. /**
  109913. * Defines the target frame rate to reach (60 by default)
  109914. */
  109915. targetFrameRate,
  109916. /**
  109917. * Defines the interval between two checkes (2000ms by default)
  109918. */
  109919. trackerDuration) {
  109920. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  109921. if (trackerDuration === void 0) { trackerDuration = 2000; }
  109922. this.targetFrameRate = targetFrameRate;
  109923. this.trackerDuration = trackerDuration;
  109924. /**
  109925. * Gets the list of optimizations to apply
  109926. */
  109927. this.optimizations = new Array();
  109928. }
  109929. /**
  109930. * Add a new optimization
  109931. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  109932. * @returns the current SceneOptimizerOptions
  109933. */
  109934. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  109935. this.optimizations.push(optimization);
  109936. return this;
  109937. };
  109938. /**
  109939. * Add a new custom optimization
  109940. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  109941. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  109942. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109943. * @returns the current SceneOptimizerOptions
  109944. */
  109945. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  109946. if (priority === void 0) { priority = 0; }
  109947. var optimization = new CustomOptimization(priority);
  109948. optimization.onApply = onApply;
  109949. optimization.onGetDescription = onGetDescription;
  109950. this.optimizations.push(optimization);
  109951. return this;
  109952. };
  109953. /**
  109954. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  109955. * @param targetFrameRate defines the target frame rate (60 by default)
  109956. * @returns a SceneOptimizerOptions object
  109957. */
  109958. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  109959. var result = new SceneOptimizerOptions(targetFrameRate);
  109960. var priority = 0;
  109961. result.addOptimization(new MergeMeshesOptimization(priority));
  109962. result.addOptimization(new ShadowsOptimization(priority));
  109963. result.addOptimization(new LensFlaresOptimization(priority));
  109964. // Next priority
  109965. priority++;
  109966. result.addOptimization(new PostProcessesOptimization(priority));
  109967. result.addOptimization(new ParticlesOptimization(priority));
  109968. // Next priority
  109969. priority++;
  109970. result.addOptimization(new TextureOptimization(priority, 1024));
  109971. return result;
  109972. };
  109973. /**
  109974. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  109975. * @param targetFrameRate defines the target frame rate (60 by default)
  109976. * @returns a SceneOptimizerOptions object
  109977. */
  109978. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  109979. var result = new SceneOptimizerOptions(targetFrameRate);
  109980. var priority = 0;
  109981. result.addOptimization(new MergeMeshesOptimization(priority));
  109982. result.addOptimization(new ShadowsOptimization(priority));
  109983. result.addOptimization(new LensFlaresOptimization(priority));
  109984. // Next priority
  109985. priority++;
  109986. result.addOptimization(new PostProcessesOptimization(priority));
  109987. result.addOptimization(new ParticlesOptimization(priority));
  109988. // Next priority
  109989. priority++;
  109990. result.addOptimization(new TextureOptimization(priority, 512));
  109991. // Next priority
  109992. priority++;
  109993. result.addOptimization(new RenderTargetsOptimization(priority));
  109994. // Next priority
  109995. priority++;
  109996. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  109997. return result;
  109998. };
  109999. /**
  110000. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  110001. * @param targetFrameRate defines the target frame rate (60 by default)
  110002. * @returns a SceneOptimizerOptions object
  110003. */
  110004. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  110005. var result = new SceneOptimizerOptions(targetFrameRate);
  110006. var priority = 0;
  110007. result.addOptimization(new MergeMeshesOptimization(priority));
  110008. result.addOptimization(new ShadowsOptimization(priority));
  110009. result.addOptimization(new LensFlaresOptimization(priority));
  110010. // Next priority
  110011. priority++;
  110012. result.addOptimization(new PostProcessesOptimization(priority));
  110013. result.addOptimization(new ParticlesOptimization(priority));
  110014. // Next priority
  110015. priority++;
  110016. result.addOptimization(new TextureOptimization(priority, 256));
  110017. // Next priority
  110018. priority++;
  110019. result.addOptimization(new RenderTargetsOptimization(priority));
  110020. // Next priority
  110021. priority++;
  110022. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  110023. return result;
  110024. };
  110025. return SceneOptimizerOptions;
  110026. }());
  110027. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  110028. /**
  110029. * Class used to run optimizations in order to reach a target frame rate
  110030. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110031. */
  110032. var SceneOptimizer = /** @class */ (function () {
  110033. /**
  110034. * Creates a new SceneOptimizer
  110035. * @param scene defines the scene to work on
  110036. * @param options defines the options to use with the SceneOptimizer
  110037. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  110038. * @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)
  110039. */
  110040. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  110041. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  110042. if (improvementMode === void 0) { improvementMode = false; }
  110043. var _this = this;
  110044. this._isRunning = false;
  110045. this._currentPriorityLevel = 0;
  110046. this._targetFrameRate = 60;
  110047. this._trackerDuration = 2000;
  110048. this._currentFrameRate = 0;
  110049. this._improvementMode = false;
  110050. /**
  110051. * Defines an observable called when the optimizer reaches the target frame rate
  110052. */
  110053. this.onSuccessObservable = new BABYLON.Observable();
  110054. /**
  110055. * Defines an observable called when the optimizer enables an optimization
  110056. */
  110057. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  110058. /**
  110059. * Defines an observable called when the optimizer is not able to reach the target frame rate
  110060. */
  110061. this.onFailureObservable = new BABYLON.Observable();
  110062. if (!options) {
  110063. this._options = new SceneOptimizerOptions();
  110064. }
  110065. else {
  110066. this._options = options;
  110067. }
  110068. if (this._options.targetFrameRate) {
  110069. this._targetFrameRate = this._options.targetFrameRate;
  110070. }
  110071. if (this._options.trackerDuration) {
  110072. this._trackerDuration = this._options.trackerDuration;
  110073. }
  110074. if (autoGeneratePriorities) {
  110075. var priority = 0;
  110076. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  110077. var optim = _a[_i];
  110078. optim.priority = priority++;
  110079. }
  110080. }
  110081. this._improvementMode = improvementMode;
  110082. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  110083. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  110084. _this._sceneDisposeObserver = null;
  110085. _this.dispose();
  110086. });
  110087. }
  110088. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  110089. /**
  110090. * Gets a boolean indicating if the optimizer is in improvement mode
  110091. */
  110092. get: function () {
  110093. return this._improvementMode;
  110094. },
  110095. enumerable: true,
  110096. configurable: true
  110097. });
  110098. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  110099. /**
  110100. * Gets the current priority level (0 at start)
  110101. */
  110102. get: function () {
  110103. return this._currentPriorityLevel;
  110104. },
  110105. enumerable: true,
  110106. configurable: true
  110107. });
  110108. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  110109. /**
  110110. * Gets the current frame rate checked by the SceneOptimizer
  110111. */
  110112. get: function () {
  110113. return this._currentFrameRate;
  110114. },
  110115. enumerable: true,
  110116. configurable: true
  110117. });
  110118. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  110119. /**
  110120. * Gets or sets the current target frame rate (60 by default)
  110121. */
  110122. get: function () {
  110123. return this._targetFrameRate;
  110124. },
  110125. /**
  110126. * Gets or sets the current target frame rate (60 by default)
  110127. */
  110128. set: function (value) {
  110129. this._targetFrameRate = value;
  110130. },
  110131. enumerable: true,
  110132. configurable: true
  110133. });
  110134. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  110135. /**
  110136. * Gets or sets the current interval between two checks (every 2000ms by default)
  110137. */
  110138. get: function () {
  110139. return this._trackerDuration;
  110140. },
  110141. /**
  110142. * Gets or sets the current interval between two checks (every 2000ms by default)
  110143. */
  110144. set: function (value) {
  110145. this._trackerDuration = value;
  110146. },
  110147. enumerable: true,
  110148. configurable: true
  110149. });
  110150. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  110151. /**
  110152. * Gets the list of active optimizations
  110153. */
  110154. get: function () {
  110155. return this._options.optimizations;
  110156. },
  110157. enumerable: true,
  110158. configurable: true
  110159. });
  110160. /**
  110161. * Stops the current optimizer
  110162. */
  110163. SceneOptimizer.prototype.stop = function () {
  110164. this._isRunning = false;
  110165. };
  110166. /**
  110167. * Reset the optimizer to initial step (current priority level = 0)
  110168. */
  110169. SceneOptimizer.prototype.reset = function () {
  110170. this._currentPriorityLevel = 0;
  110171. };
  110172. /**
  110173. * Start the optimizer. By default it will try to reach a specific framerate
  110174. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  110175. */
  110176. SceneOptimizer.prototype.start = function () {
  110177. var _this = this;
  110178. if (this._isRunning) {
  110179. return;
  110180. }
  110181. this._isRunning = true;
  110182. // Let's wait for the scene to be ready before running our check
  110183. this._scene.executeWhenReady(function () {
  110184. setTimeout(function () {
  110185. _this._checkCurrentState();
  110186. }, _this._trackerDuration);
  110187. });
  110188. };
  110189. SceneOptimizer.prototype._checkCurrentState = function () {
  110190. var _this = this;
  110191. if (!this._isRunning) {
  110192. return;
  110193. }
  110194. var scene = this._scene;
  110195. var options = this._options;
  110196. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  110197. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  110198. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  110199. this._isRunning = false;
  110200. this.onSuccessObservable.notifyObservers(this);
  110201. return;
  110202. }
  110203. // Apply current level of optimizations
  110204. var allDone = true;
  110205. var noOptimizationApplied = true;
  110206. for (var index = 0; index < options.optimizations.length; index++) {
  110207. var optimization = options.optimizations[index];
  110208. if (optimization.priority === this._currentPriorityLevel) {
  110209. noOptimizationApplied = false;
  110210. allDone = allDone && optimization.apply(scene, this);
  110211. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  110212. }
  110213. }
  110214. // If no optimization was applied, this is a failure :(
  110215. if (noOptimizationApplied) {
  110216. this._isRunning = false;
  110217. this.onFailureObservable.notifyObservers(this);
  110218. return;
  110219. }
  110220. // If all optimizations were done, move to next level
  110221. if (allDone) {
  110222. this._currentPriorityLevel++;
  110223. }
  110224. // Let's the system running for a specific amount of time before checking FPS
  110225. scene.executeWhenReady(function () {
  110226. setTimeout(function () {
  110227. _this._checkCurrentState();
  110228. }, _this._trackerDuration);
  110229. });
  110230. };
  110231. /**
  110232. * Release all resources
  110233. */
  110234. SceneOptimizer.prototype.dispose = function () {
  110235. this.stop();
  110236. this.onSuccessObservable.clear();
  110237. this.onFailureObservable.clear();
  110238. this.onNewOptimizationAppliedObservable.clear();
  110239. if (this._sceneDisposeObserver) {
  110240. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  110241. }
  110242. };
  110243. /**
  110244. * Helper function to create a SceneOptimizer with one single line of code
  110245. * @param scene defines the scene to work on
  110246. * @param options defines the options to use with the SceneOptimizer
  110247. * @param onSuccess defines a callback to call on success
  110248. * @param onFailure defines a callback to call on failure
  110249. * @returns the new SceneOptimizer object
  110250. */
  110251. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  110252. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  110253. if (onSuccess) {
  110254. optimizer.onSuccessObservable.add(function () {
  110255. onSuccess();
  110256. });
  110257. }
  110258. if (onFailure) {
  110259. optimizer.onFailureObservable.add(function () {
  110260. onFailure();
  110261. });
  110262. }
  110263. optimizer.start();
  110264. return optimizer;
  110265. };
  110266. return SceneOptimizer;
  110267. }());
  110268. BABYLON.SceneOptimizer = SceneOptimizer;
  110269. })(BABYLON || (BABYLON = {}));
  110270. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  110271. var BABYLON;
  110272. (function (BABYLON) {
  110273. /**
  110274. * Gets the outline renderer associated with the scene
  110275. * @returns a OutlineRenderer
  110276. */
  110277. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  110278. if (!this._outlineRenderer) {
  110279. this._outlineRenderer = new OutlineRenderer(this);
  110280. }
  110281. return this._outlineRenderer;
  110282. };
  110283. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  110284. get: function () {
  110285. return this._renderOutline;
  110286. },
  110287. set: function (value) {
  110288. if (value) {
  110289. // Lazy Load the component.
  110290. this.getScene().getOutlineRenderer();
  110291. }
  110292. this._renderOutline = value;
  110293. },
  110294. enumerable: true,
  110295. configurable: true
  110296. });
  110297. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  110298. get: function () {
  110299. return this._renderOverlay;
  110300. },
  110301. set: function (value) {
  110302. if (value) {
  110303. // Lazy Load the component.
  110304. this.getScene().getOutlineRenderer();
  110305. }
  110306. this._renderOverlay = value;
  110307. },
  110308. enumerable: true,
  110309. configurable: true
  110310. });
  110311. /**
  110312. * This class is responsible to draw bothe outline/overlay of meshes.
  110313. * It should not be used directly but through the available method on mesh.
  110314. */
  110315. var OutlineRenderer = /** @class */ (function () {
  110316. /**
  110317. * Instantiates a new outline renderer. (There could be only one per scene).
  110318. * @param scene Defines the scene it belongs to
  110319. */
  110320. function OutlineRenderer(scene) {
  110321. /**
  110322. * The name of the component. Each component must have a unique name.
  110323. */
  110324. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  110325. /**
  110326. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  110327. */
  110328. this.zOffset = 1;
  110329. this.scene = scene;
  110330. this._engine = scene.getEngine();
  110331. this.scene._addComponent(this);
  110332. }
  110333. /**
  110334. * Register the component to one instance of a scene.
  110335. */
  110336. OutlineRenderer.prototype.register = function () {
  110337. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  110338. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  110339. };
  110340. /**
  110341. * Rebuilds the elements related to this component in case of
  110342. * context lost for instance.
  110343. */
  110344. OutlineRenderer.prototype.rebuild = function () {
  110345. // Nothing to do here.
  110346. };
  110347. /**
  110348. * Disposes the component and the associated ressources.
  110349. */
  110350. OutlineRenderer.prototype.dispose = function () {
  110351. // Nothing to do here.
  110352. };
  110353. /**
  110354. * Renders the outline in the canvas.
  110355. * @param subMesh Defines the sumesh to render
  110356. * @param batch Defines the batch of meshes in case of instances
  110357. * @param useOverlay Defines if the rendering is for the overlay or the outline
  110358. */
  110359. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  110360. var _this = this;
  110361. if (useOverlay === void 0) { useOverlay = false; }
  110362. var scene = this.scene;
  110363. var engine = scene.getEngine();
  110364. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  110365. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  110366. return;
  110367. }
  110368. var mesh = subMesh.getRenderingMesh();
  110369. var material = subMesh.getMaterial();
  110370. if (!material || !scene.activeCamera) {
  110371. return;
  110372. }
  110373. engine.enableEffect(this._effect);
  110374. // Logarithmic depth
  110375. if (material.useLogarithmicDepth) {
  110376. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  110377. }
  110378. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  110379. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  110380. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  110381. // Bones
  110382. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  110383. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  110384. }
  110385. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  110386. // Alpha test
  110387. if (material && material.needAlphaTesting()) {
  110388. var alphaTexture = material.getAlphaTestTexture();
  110389. if (alphaTexture) {
  110390. this._effect.setTexture("diffuseSampler", alphaTexture);
  110391. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  110392. }
  110393. }
  110394. engine.setZOffset(-this.zOffset);
  110395. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  110396. engine.setZOffset(0);
  110397. };
  110398. /**
  110399. * Returns whether or not the outline renderer is ready for a given submesh.
  110400. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  110401. * @param subMesh Defines the submesh to check readyness for
  110402. * @param useInstances Defines wheter wee are trying to render instances or not
  110403. * @returns true if ready otherwise false
  110404. */
  110405. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  110406. var defines = [];
  110407. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  110408. var mesh = subMesh.getMesh();
  110409. var material = subMesh.getMaterial();
  110410. if (material) {
  110411. // Alpha test
  110412. if (material.needAlphaTesting()) {
  110413. defines.push("#define ALPHATEST");
  110414. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  110415. attribs.push(BABYLON.VertexBuffer.UVKind);
  110416. defines.push("#define UV1");
  110417. }
  110418. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  110419. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  110420. defines.push("#define UV2");
  110421. }
  110422. }
  110423. //Logarithmic depth
  110424. if (material.useLogarithmicDepth) {
  110425. defines.push("#define LOGARITHMICDEPTH");
  110426. }
  110427. }
  110428. // Bones
  110429. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  110430. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  110431. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  110432. if (mesh.numBoneInfluencers > 4) {
  110433. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  110434. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  110435. }
  110436. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  110437. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  110438. }
  110439. else {
  110440. defines.push("#define NUM_BONE_INFLUENCERS 0");
  110441. }
  110442. // Instances
  110443. if (useInstances) {
  110444. defines.push("#define INSTANCES");
  110445. attribs.push("world0");
  110446. attribs.push("world1");
  110447. attribs.push("world2");
  110448. attribs.push("world3");
  110449. }
  110450. // Get correct effect
  110451. var join = defines.join("\n");
  110452. if (this._cachedDefines !== join) {
  110453. this._cachedDefines = join;
  110454. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  110455. }
  110456. return this._effect.isReady();
  110457. };
  110458. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  110459. // Outline - step 1
  110460. this._savedDepthWrite = this._engine.getDepthWrite();
  110461. if (mesh.renderOutline) {
  110462. this._engine.setDepthWrite(false);
  110463. this.render(subMesh, batch);
  110464. this._engine.setDepthWrite(this._savedDepthWrite);
  110465. }
  110466. };
  110467. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  110468. // Outline - step 2
  110469. if (mesh.renderOutline && this._savedDepthWrite) {
  110470. this._engine.setDepthWrite(true);
  110471. this._engine.setColorWrite(false);
  110472. this.render(subMesh, batch);
  110473. this._engine.setColorWrite(true);
  110474. }
  110475. // Overlay
  110476. if (mesh.renderOverlay) {
  110477. var currentMode = this._engine.getAlphaMode();
  110478. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  110479. this.render(subMesh, batch, true);
  110480. this._engine.setAlphaMode(currentMode);
  110481. }
  110482. };
  110483. return OutlineRenderer;
  110484. }());
  110485. BABYLON.OutlineRenderer = OutlineRenderer;
  110486. })(BABYLON || (BABYLON = {}));
  110487. //# sourceMappingURL=babylon.outlineRenderer.js.map
  110488. var BABYLON;
  110489. (function (BABYLON) {
  110490. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  110491. if (this._edgesRenderer) {
  110492. this._edgesRenderer.dispose();
  110493. this._edgesRenderer = null;
  110494. }
  110495. return this;
  110496. };
  110497. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  110498. if (epsilon === void 0) { epsilon = 0.95; }
  110499. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110500. this.disableEdgesRendering();
  110501. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  110502. return this;
  110503. };
  110504. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  110505. get: function () {
  110506. return this._edgesRenderer;
  110507. },
  110508. enumerable: true,
  110509. configurable: true
  110510. });
  110511. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  110512. if (epsilon === void 0) { epsilon = 0.95; }
  110513. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110514. this.disableEdgesRendering();
  110515. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  110516. return this;
  110517. };
  110518. BABYLON.InstancedMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  110519. if (epsilon === void 0) { epsilon = 0.95; }
  110520. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110521. if (this.sourceMesh.getClassName() === 'LinesMesh') {
  110522. BABYLON.LinesMesh.prototype.enableEdgesRendering.apply(this, arguments);
  110523. }
  110524. else {
  110525. BABYLON.AbstractMesh.prototype.enableEdgesRendering.apply(this, arguments);
  110526. }
  110527. return this;
  110528. };
  110529. /**
  110530. * FaceAdjacencies Helper class to generate edges
  110531. */
  110532. var FaceAdjacencies = /** @class */ (function () {
  110533. function FaceAdjacencies() {
  110534. this.edges = new Array();
  110535. this.edgesConnectedCount = 0;
  110536. }
  110537. return FaceAdjacencies;
  110538. }());
  110539. /**
  110540. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  110541. */
  110542. var EdgesRenderer = /** @class */ (function () {
  110543. /**
  110544. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  110545. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  110546. * @param source Mesh used to create edges
  110547. * @param epsilon sum of angles in adjacency to check for edge
  110548. * @param checkVerticesInsteadOfIndices
  110549. * @param generateEdgesLines - should generate Lines or only prepare resources.
  110550. */
  110551. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  110552. if (epsilon === void 0) { epsilon = 0.95; }
  110553. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110554. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  110555. var _this = this;
  110556. /**
  110557. * Define the size of the edges with an orthographic camera
  110558. */
  110559. this.edgesWidthScalerForOrthographic = 1000.0;
  110560. /**
  110561. * Define the size of the edges with a perspective camera
  110562. */
  110563. this.edgesWidthScalerForPerspective = 50.0;
  110564. this._linesPositions = new Array();
  110565. this._linesNormals = new Array();
  110566. this._linesIndices = new Array();
  110567. this._buffers = {};
  110568. this._checkVerticesInsteadOfIndices = false;
  110569. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  110570. this.isEnabled = true;
  110571. this._source = source;
  110572. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  110573. this._epsilon = epsilon;
  110574. this._prepareRessources();
  110575. if (generateEdgesLines) {
  110576. this._generateEdgesLines();
  110577. }
  110578. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  110579. _this._rebuild();
  110580. });
  110581. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  110582. _this.dispose();
  110583. });
  110584. }
  110585. EdgesRenderer.prototype._prepareRessources = function () {
  110586. if (this._lineShader) {
  110587. return;
  110588. }
  110589. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  110590. attributes: ["position", "normal"],
  110591. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  110592. });
  110593. this._lineShader.disableDepthWrite = true;
  110594. this._lineShader.backFaceCulling = false;
  110595. };
  110596. /** @hidden */
  110597. EdgesRenderer.prototype._rebuild = function () {
  110598. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  110599. if (buffer) {
  110600. buffer._rebuild();
  110601. }
  110602. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  110603. if (buffer) {
  110604. buffer._rebuild();
  110605. }
  110606. var scene = this._source.getScene();
  110607. var engine = scene.getEngine();
  110608. this._ib = engine.createIndexBuffer(this._linesIndices);
  110609. };
  110610. /**
  110611. * Releases the required resources for the edges renderer
  110612. */
  110613. EdgesRenderer.prototype.dispose = function () {
  110614. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  110615. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  110616. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  110617. if (buffer) {
  110618. buffer.dispose();
  110619. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  110620. }
  110621. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  110622. if (buffer) {
  110623. buffer.dispose();
  110624. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  110625. }
  110626. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  110627. this._lineShader.dispose();
  110628. };
  110629. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  110630. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  110631. return 0;
  110632. }
  110633. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  110634. return 1;
  110635. }
  110636. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  110637. return 2;
  110638. }
  110639. return -1;
  110640. };
  110641. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  110642. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  110643. return 0;
  110644. }
  110645. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  110646. return 1;
  110647. }
  110648. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  110649. return 2;
  110650. }
  110651. return -1;
  110652. };
  110653. /**
  110654. * Checks if the pair of p0 and p1 is en edge
  110655. * @param faceIndex
  110656. * @param edge
  110657. * @param faceNormals
  110658. * @param p0
  110659. * @param p1
  110660. * @private
  110661. */
  110662. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  110663. var needToCreateLine;
  110664. if (edge === undefined) {
  110665. needToCreateLine = true;
  110666. }
  110667. else {
  110668. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  110669. needToCreateLine = dotProduct < this._epsilon;
  110670. }
  110671. if (needToCreateLine) {
  110672. this.createLine(p0, p1, this._linesPositions.length / 3);
  110673. }
  110674. };
  110675. /**
  110676. * push line into the position, normal and index buffer
  110677. * @protected
  110678. */
  110679. EdgesRenderer.prototype.createLine = function (p0, p1, offset) {
  110680. // Positions
  110681. 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);
  110682. // Normals
  110683. 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);
  110684. // Indices
  110685. this._linesIndices.push(offset, offset + 1, offset + 2, offset, offset + 2, offset + 3);
  110686. };
  110687. /**
  110688. * Generates lines edges from adjacencjes
  110689. * @private
  110690. */
  110691. EdgesRenderer.prototype._generateEdgesLines = function () {
  110692. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  110693. var indices = this._source.getIndices();
  110694. if (!indices || !positions) {
  110695. return;
  110696. }
  110697. // First let's find adjacencies
  110698. var adjacencies = new Array();
  110699. var faceNormals = new Array();
  110700. var index;
  110701. var faceAdjacencies;
  110702. // Prepare faces
  110703. for (index = 0; index < indices.length; index += 3) {
  110704. faceAdjacencies = new FaceAdjacencies();
  110705. var p0Index = indices[index];
  110706. var p1Index = indices[index + 1];
  110707. var p2Index = indices[index + 2];
  110708. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  110709. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  110710. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  110711. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  110712. faceNormal.normalize();
  110713. faceNormals.push(faceNormal);
  110714. adjacencies.push(faceAdjacencies);
  110715. }
  110716. // Scan
  110717. for (index = 0; index < adjacencies.length; index++) {
  110718. faceAdjacencies = adjacencies[index];
  110719. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  110720. var otherFaceAdjacencies = adjacencies[otherIndex];
  110721. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  110722. break;
  110723. }
  110724. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  110725. continue;
  110726. }
  110727. var otherP0 = indices[otherIndex * 3];
  110728. var otherP1 = indices[otherIndex * 3 + 1];
  110729. var otherP2 = indices[otherIndex * 3 + 2];
  110730. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  110731. var otherEdgeIndex = 0;
  110732. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  110733. continue;
  110734. }
  110735. switch (edgeIndex) {
  110736. case 0:
  110737. if (this._checkVerticesInsteadOfIndices) {
  110738. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110739. }
  110740. else {
  110741. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  110742. }
  110743. break;
  110744. case 1:
  110745. if (this._checkVerticesInsteadOfIndices) {
  110746. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110747. }
  110748. else {
  110749. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  110750. }
  110751. break;
  110752. case 2:
  110753. if (this._checkVerticesInsteadOfIndices) {
  110754. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110755. }
  110756. else {
  110757. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  110758. }
  110759. break;
  110760. }
  110761. if (otherEdgeIndex === -1) {
  110762. continue;
  110763. }
  110764. faceAdjacencies.edges[edgeIndex] = otherIndex;
  110765. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  110766. faceAdjacencies.edgesConnectedCount++;
  110767. otherFaceAdjacencies.edgesConnectedCount++;
  110768. if (faceAdjacencies.edgesConnectedCount === 3) {
  110769. break;
  110770. }
  110771. }
  110772. }
  110773. }
  110774. // Create lines
  110775. for (index = 0; index < adjacencies.length; index++) {
  110776. // 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
  110777. var current = adjacencies[index];
  110778. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  110779. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  110780. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  110781. }
  110782. // Merge into a single mesh
  110783. var engine = this._source.getScene().getEngine();
  110784. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  110785. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  110786. this._ib = engine.createIndexBuffer(this._linesIndices);
  110787. this._indicesCount = this._linesIndices.length;
  110788. };
  110789. /**
  110790. * Checks wether or not the edges renderer is ready to render.
  110791. * @return true if ready, otherwise false.
  110792. */
  110793. EdgesRenderer.prototype.isReady = function () {
  110794. return this._lineShader.isReady();
  110795. };
  110796. /**
  110797. * Renders the edges of the attached mesh,
  110798. */
  110799. EdgesRenderer.prototype.render = function () {
  110800. var scene = this._source.getScene();
  110801. if (!this.isReady() || !scene.activeCamera) {
  110802. return;
  110803. }
  110804. var engine = scene.getEngine();
  110805. this._lineShader._preBind();
  110806. if (this._source.edgesColor.a !== 1) {
  110807. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  110808. }
  110809. else {
  110810. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  110811. }
  110812. // VBOs
  110813. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  110814. scene.resetCachedMaterial();
  110815. this._lineShader.setColor4("color", this._source.edgesColor);
  110816. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  110817. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  110818. }
  110819. else {
  110820. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  110821. }
  110822. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  110823. this._lineShader.bind(this._source.getWorldMatrix());
  110824. // Draw order
  110825. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  110826. this._lineShader.unbind();
  110827. };
  110828. return EdgesRenderer;
  110829. }());
  110830. BABYLON.EdgesRenderer = EdgesRenderer;
  110831. })(BABYLON || (BABYLON = {}));
  110832. //# sourceMappingURL=babylon.edgesRenderer.js.map
  110833. var BABYLON;
  110834. (function (BABYLON) {
  110835. /**
  110836. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  110837. */
  110838. var LineEdgesRenderer = /** @class */ (function (_super) {
  110839. __extends(LineEdgesRenderer, _super);
  110840. /**
  110841. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  110842. * @param source LineMesh used to generate edges
  110843. * @param epsilon not important (specified angle for edge detection)
  110844. * @param checkVerticesInsteadOfIndices not important for LineMesh
  110845. */
  110846. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  110847. if (epsilon === void 0) { epsilon = 0.95; }
  110848. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110849. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  110850. _this._generateEdgesLines();
  110851. return _this;
  110852. }
  110853. /**
  110854. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  110855. */
  110856. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  110857. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  110858. var indices = this._source.getIndices();
  110859. if (!indices || !positions) {
  110860. return;
  110861. }
  110862. var p0 = BABYLON.Tmp.Vector3[0];
  110863. var p1 = BABYLON.Tmp.Vector3[1];
  110864. var len = indices.length - 1;
  110865. for (var i = 0, offset = 0; i < len; i += 2, offset += 4) {
  110866. BABYLON.Vector3.FromArrayToRef(positions, 3 * indices[i], p0);
  110867. BABYLON.Vector3.FromArrayToRef(positions, 3 * indices[i + 1], p1);
  110868. this.createLine(p0, p1, offset);
  110869. }
  110870. // Merge into a single mesh
  110871. var engine = this._source.getScene().getEngine();
  110872. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  110873. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  110874. this._ib = engine.createIndexBuffer(this._linesIndices);
  110875. this._indicesCount = this._linesIndices.length;
  110876. };
  110877. return LineEdgesRenderer;
  110878. }(BABYLON.EdgesRenderer));
  110879. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  110880. })(BABYLON || (BABYLON = {}));
  110881. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  110882. var BABYLON;
  110883. (function (BABYLON) {
  110884. // Adds the parser to the scene parsers.
  110885. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  110886. if (parsedData.effectLayers) {
  110887. if (!container.effectLayers) {
  110888. container.effectLayers = new Array();
  110889. }
  110890. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  110891. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  110892. container.effectLayers.push(effectLayer);
  110893. }
  110894. }
  110895. });
  110896. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  110897. var index = this.effectLayers.indexOf(toRemove);
  110898. if (index !== -1) {
  110899. this.effectLayers.splice(index, 1);
  110900. }
  110901. return index;
  110902. };
  110903. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  110904. this.effectLayers.push(newEffectLayer);
  110905. };
  110906. /**
  110907. * Defines the layer scene component responsible to manage any effect layers
  110908. * in a given scene.
  110909. */
  110910. var EffectLayerSceneComponent = /** @class */ (function () {
  110911. /**
  110912. * Creates a new instance of the component for the given scene
  110913. * @param scene Defines the scene to register the component in
  110914. */
  110915. function EffectLayerSceneComponent(scene) {
  110916. /**
  110917. * The component name helpfull to identify the component in the list of scene components.
  110918. */
  110919. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  110920. this._renderEffects = false;
  110921. this._needStencil = false;
  110922. this._previousStencilState = false;
  110923. this.scene = scene;
  110924. this._engine = scene.getEngine();
  110925. scene.effectLayers = new Array();
  110926. }
  110927. /**
  110928. * Registers the component in a given scene
  110929. */
  110930. EffectLayerSceneComponent.prototype.register = function () {
  110931. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  110932. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  110933. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  110934. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  110935. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  110936. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  110937. };
  110938. /**
  110939. * Rebuilds the elements related to this component in case of
  110940. * context lost for instance.
  110941. */
  110942. EffectLayerSceneComponent.prototype.rebuild = function () {
  110943. var layers = this.scene.effectLayers;
  110944. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  110945. var effectLayer = layers_1[_i];
  110946. effectLayer._rebuild();
  110947. }
  110948. };
  110949. /**
  110950. * Serializes the component data to the specified json object
  110951. * @param serializationObject The object to serialize to
  110952. */
  110953. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  110954. // Effect layers
  110955. serializationObject.effectLayers = [];
  110956. var layers = this.scene.effectLayers;
  110957. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  110958. var effectLayer = layers_2[_i];
  110959. if (effectLayer.serialize) {
  110960. serializationObject.effectLayers.push(effectLayer.serialize());
  110961. }
  110962. }
  110963. };
  110964. /**
  110965. * Adds all the element from the container to the scene
  110966. * @param container the container holding the elements
  110967. */
  110968. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  110969. var _this = this;
  110970. if (!container.effectLayers) {
  110971. return;
  110972. }
  110973. container.effectLayers.forEach(function (o) {
  110974. _this.scene.addEffectLayer(o);
  110975. });
  110976. };
  110977. /**
  110978. * Removes all the elements in the container from the scene
  110979. * @param container contains the elements to remove
  110980. */
  110981. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  110982. var _this = this;
  110983. if (!container.effectLayers) {
  110984. return;
  110985. }
  110986. container.effectLayers.forEach(function (o) {
  110987. _this.scene.removeEffectLayer(o);
  110988. });
  110989. };
  110990. /**
  110991. * Disposes the component and the associated ressources.
  110992. */
  110993. EffectLayerSceneComponent.prototype.dispose = function () {
  110994. var layers = this.scene.effectLayers;
  110995. while (layers.length) {
  110996. layers[0].dispose();
  110997. }
  110998. };
  110999. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  111000. var layers = this.scene.effectLayers;
  111001. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  111002. var layer = layers_3[_i];
  111003. if (!layer.hasMesh(mesh)) {
  111004. continue;
  111005. }
  111006. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  111007. var subMesh = _b[_a];
  111008. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  111009. return false;
  111010. }
  111011. }
  111012. }
  111013. return true;
  111014. };
  111015. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  111016. this._renderEffects = false;
  111017. this._needStencil = false;
  111018. var layers = this.scene.effectLayers;
  111019. if (layers && layers.length > 0) {
  111020. this._previousStencilState = this._engine.getStencilBuffer();
  111021. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  111022. var effectLayer = layers_4[_i];
  111023. if (effectLayer.shouldRender() &&
  111024. (!effectLayer.camera ||
  111025. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  111026. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  111027. this._renderEffects = true;
  111028. this._needStencil = this._needStencil || effectLayer.needStencil();
  111029. var renderTarget = effectLayer._mainTexture;
  111030. if (renderTarget._shouldRender()) {
  111031. this.scene.incrementRenderId();
  111032. renderTarget.render(false, false);
  111033. }
  111034. }
  111035. }
  111036. this.scene.incrementRenderId();
  111037. }
  111038. };
  111039. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  111040. // Activate effect Layer stencil
  111041. if (this._needStencil) {
  111042. this._engine.setStencilBuffer(true);
  111043. }
  111044. };
  111045. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  111046. // Restore effect Layer stencil
  111047. if (this._needStencil) {
  111048. this._engine.setStencilBuffer(this._previousStencilState);
  111049. }
  111050. };
  111051. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  111052. if (this._renderEffects) {
  111053. this._engine.setDepthBuffer(false);
  111054. var layers = this.scene.effectLayers;
  111055. for (var i = 0; i < layers.length; i++) {
  111056. var effectLayer = layers[i];
  111057. if (effectLayer.renderingGroupId === renderingGroupId) {
  111058. if (effectLayer.shouldRender()) {
  111059. effectLayer.render();
  111060. }
  111061. }
  111062. }
  111063. this._engine.setDepthBuffer(true);
  111064. }
  111065. };
  111066. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  111067. if (this._renderEffects) {
  111068. this._draw(-1);
  111069. }
  111070. };
  111071. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  111072. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  111073. this._draw(index);
  111074. }
  111075. };
  111076. return EffectLayerSceneComponent;
  111077. }());
  111078. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  111079. })(BABYLON || (BABYLON = {}));
  111080. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  111081. var __assign = (this && this.__assign) || function () {
  111082. __assign = Object.assign || function(t) {
  111083. for (var s, i = 1, n = arguments.length; i < n; i++) {
  111084. s = arguments[i];
  111085. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  111086. t[p] = s[p];
  111087. }
  111088. return t;
  111089. };
  111090. return __assign.apply(this, arguments);
  111091. };
  111092. var BABYLON;
  111093. (function (BABYLON) {
  111094. /**
  111095. * The effect layer Helps adding post process effect blended with the main pass.
  111096. *
  111097. * This can be for instance use to generate glow or higlight effects on the scene.
  111098. *
  111099. * The effect layer class can not be used directly and is intented to inherited from to be
  111100. * customized per effects.
  111101. */
  111102. var EffectLayer = /** @class */ (function () {
  111103. /**
  111104. * Instantiates a new effect Layer and references it in the scene.
  111105. * @param name The name of the layer
  111106. * @param scene The scene to use the layer in
  111107. */
  111108. function EffectLayer(
  111109. /** The Friendly of the effect in the scene */
  111110. name, scene) {
  111111. this._vertexBuffers = {};
  111112. this._maxSize = 0;
  111113. this._mainTextureDesiredSize = { width: 0, height: 0 };
  111114. this._shouldRender = true;
  111115. this._postProcesses = [];
  111116. this._textures = [];
  111117. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  111118. /**
  111119. * The clear color of the texture used to generate the glow map.
  111120. */
  111121. this.neutralColor = new BABYLON.Color4();
  111122. /**
  111123. * Specifies wether the highlight layer is enabled or not.
  111124. */
  111125. this.isEnabled = true;
  111126. /**
  111127. * An event triggered when the effect layer has been disposed.
  111128. */
  111129. this.onDisposeObservable = new BABYLON.Observable();
  111130. /**
  111131. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  111132. */
  111133. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  111134. /**
  111135. * An event triggered when the generated texture is being merged in the scene.
  111136. */
  111137. this.onBeforeComposeObservable = new BABYLON.Observable();
  111138. /**
  111139. * An event triggered when the generated texture has been merged in the scene.
  111140. */
  111141. this.onAfterComposeObservable = new BABYLON.Observable();
  111142. /**
  111143. * An event triggered when the efffect layer changes its size.
  111144. */
  111145. this.onSizeChangedObservable = new BABYLON.Observable();
  111146. this.name = name;
  111147. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  111148. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  111149. if (!component) {
  111150. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  111151. this._scene._addComponent(component);
  111152. }
  111153. this._engine = this._scene.getEngine();
  111154. this._maxSize = this._engine.getCaps().maxTextureSize;
  111155. this._scene.effectLayers.push(this);
  111156. // Generate Buffers
  111157. this._generateIndexBuffer();
  111158. this._genrateVertexBuffer();
  111159. }
  111160. Object.defineProperty(EffectLayer.prototype, "camera", {
  111161. /**
  111162. * Gets the camera attached to the layer.
  111163. */
  111164. get: function () {
  111165. return this._effectLayerOptions.camera;
  111166. },
  111167. enumerable: true,
  111168. configurable: true
  111169. });
  111170. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  111171. /**
  111172. * Gets the rendering group id the layer should render in.
  111173. */
  111174. get: function () {
  111175. return this._effectLayerOptions.renderingGroupId;
  111176. },
  111177. enumerable: true,
  111178. configurable: true
  111179. });
  111180. /**
  111181. * Initializes the effect layer with the required options.
  111182. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  111183. */
  111184. EffectLayer.prototype._init = function (options) {
  111185. // Adapt options
  111186. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  111187. this._setMainTextureSize();
  111188. this._createMainTexture();
  111189. this._createTextureAndPostProcesses();
  111190. this._mergeEffect = this._createMergeEffect();
  111191. };
  111192. /**
  111193. * Generates the index buffer of the full screen quad blending to the main canvas.
  111194. */
  111195. EffectLayer.prototype._generateIndexBuffer = function () {
  111196. // Indices
  111197. var indices = [];
  111198. indices.push(0);
  111199. indices.push(1);
  111200. indices.push(2);
  111201. indices.push(0);
  111202. indices.push(2);
  111203. indices.push(3);
  111204. this._indexBuffer = this._engine.createIndexBuffer(indices);
  111205. };
  111206. /**
  111207. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  111208. */
  111209. EffectLayer.prototype._genrateVertexBuffer = function () {
  111210. // VBO
  111211. var vertices = [];
  111212. vertices.push(1, 1);
  111213. vertices.push(-1, 1);
  111214. vertices.push(-1, -1);
  111215. vertices.push(1, -1);
  111216. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  111217. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  111218. };
  111219. /**
  111220. * Sets the main texture desired size which is the closest power of two
  111221. * of the engine canvas size.
  111222. */
  111223. EffectLayer.prototype._setMainTextureSize = function () {
  111224. if (this._effectLayerOptions.mainTextureFixedSize) {
  111225. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  111226. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  111227. }
  111228. else {
  111229. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  111230. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  111231. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  111232. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  111233. }
  111234. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  111235. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  111236. };
  111237. /**
  111238. * Creates the main texture for the effect layer.
  111239. */
  111240. EffectLayer.prototype._createMainTexture = function () {
  111241. var _this = this;
  111242. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  111243. width: this._mainTextureDesiredSize.width,
  111244. height: this._mainTextureDesiredSize.height
  111245. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  111246. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  111247. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111248. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111249. this._mainTexture.anisotropicFilteringLevel = 1;
  111250. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  111251. this._mainTexture.renderParticles = false;
  111252. this._mainTexture.renderList = null;
  111253. this._mainTexture.ignoreCameraViewport = true;
  111254. // Custom render function
  111255. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  111256. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  111257. var index;
  111258. var engine = _this._scene.getEngine();
  111259. if (depthOnlySubMeshes.length) {
  111260. engine.setColorWrite(false);
  111261. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  111262. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  111263. }
  111264. engine.setColorWrite(true);
  111265. }
  111266. for (index = 0; index < opaqueSubMeshes.length; index++) {
  111267. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  111268. }
  111269. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  111270. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  111271. }
  111272. for (index = 0; index < transparentSubMeshes.length; index++) {
  111273. _this._renderSubMesh(transparentSubMeshes.data[index]);
  111274. }
  111275. };
  111276. this._mainTexture.onClearObservable.add(function (engine) {
  111277. engine.clear(_this.neutralColor, true, true, true);
  111278. });
  111279. };
  111280. /**
  111281. * Checks for the readiness of the element composing the layer.
  111282. * @param subMesh the mesh to check for
  111283. * @param useInstances specify wether or not to use instances to render the mesh
  111284. * @param emissiveTexture the associated emissive texture used to generate the glow
  111285. * @return true if ready otherwise, false
  111286. */
  111287. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  111288. var material = subMesh.getMaterial();
  111289. if (!material) {
  111290. return false;
  111291. }
  111292. if (!material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances)) {
  111293. return false;
  111294. }
  111295. var defines = [];
  111296. var attribs = [BABYLON.VertexBuffer.PositionKind];
  111297. var mesh = subMesh.getMesh();
  111298. var uv1 = false;
  111299. var uv2 = false;
  111300. // Alpha test
  111301. if (material && material.needAlphaTesting()) {
  111302. var alphaTexture = material.getAlphaTestTexture();
  111303. if (alphaTexture) {
  111304. defines.push("#define ALPHATEST");
  111305. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  111306. alphaTexture.coordinatesIndex === 1) {
  111307. defines.push("#define DIFFUSEUV2");
  111308. uv2 = true;
  111309. }
  111310. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  111311. defines.push("#define DIFFUSEUV1");
  111312. uv1 = true;
  111313. }
  111314. }
  111315. }
  111316. // Emissive
  111317. if (emissiveTexture) {
  111318. defines.push("#define EMISSIVE");
  111319. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  111320. emissiveTexture.coordinatesIndex === 1) {
  111321. defines.push("#define EMISSIVEUV2");
  111322. uv2 = true;
  111323. }
  111324. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  111325. defines.push("#define EMISSIVEUV1");
  111326. uv1 = true;
  111327. }
  111328. }
  111329. if (uv1) {
  111330. attribs.push(BABYLON.VertexBuffer.UVKind);
  111331. defines.push("#define UV1");
  111332. }
  111333. if (uv2) {
  111334. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  111335. defines.push("#define UV2");
  111336. }
  111337. // Bones
  111338. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  111339. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  111340. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  111341. if (mesh.numBoneInfluencers > 4) {
  111342. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  111343. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  111344. }
  111345. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  111346. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  111347. }
  111348. else {
  111349. defines.push("#define NUM_BONE_INFLUENCERS 0");
  111350. }
  111351. // Morph targets
  111352. var manager = mesh.morphTargetManager;
  111353. var morphInfluencers = 0;
  111354. if (manager) {
  111355. if (manager.numInfluencers > 0) {
  111356. defines.push("#define MORPHTARGETS");
  111357. morphInfluencers = manager.numInfluencers;
  111358. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  111359. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  111360. }
  111361. }
  111362. // Instances
  111363. if (useInstances) {
  111364. defines.push("#define INSTANCES");
  111365. attribs.push("world0");
  111366. attribs.push("world1");
  111367. attribs.push("world2");
  111368. attribs.push("world3");
  111369. }
  111370. // Get correct effect
  111371. var join = defines.join("\n");
  111372. if (this._cachedDefines !== join) {
  111373. this._cachedDefines = join;
  111374. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  111375. }
  111376. return this._effectLayerMapGenerationEffect.isReady();
  111377. };
  111378. /**
  111379. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  111380. */
  111381. EffectLayer.prototype.render = function () {
  111382. var currentEffect = this._mergeEffect;
  111383. // Check
  111384. if (!currentEffect.isReady()) {
  111385. return;
  111386. }
  111387. for (var i = 0; i < this._postProcesses.length; i++) {
  111388. if (!this._postProcesses[i].isReady()) {
  111389. return;
  111390. }
  111391. }
  111392. var engine = this._scene.getEngine();
  111393. this.onBeforeComposeObservable.notifyObservers(this);
  111394. // Render
  111395. engine.enableEffect(currentEffect);
  111396. engine.setState(false);
  111397. // VBOs
  111398. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  111399. // Cache
  111400. var previousAlphaMode = engine.getAlphaMode();
  111401. // Go Blend.
  111402. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  111403. // Blends the map on the main canvas.
  111404. this._internalRender(currentEffect);
  111405. // Restore Alpha
  111406. engine.setAlphaMode(previousAlphaMode);
  111407. this.onAfterComposeObservable.notifyObservers(this);
  111408. // Handle size changes.
  111409. var size = this._mainTexture.getSize();
  111410. this._setMainTextureSize();
  111411. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  111412. // Recreate RTT and post processes on size change.
  111413. this.onSizeChangedObservable.notifyObservers(this);
  111414. this._disposeTextureAndPostProcesses();
  111415. this._createMainTexture();
  111416. this._createTextureAndPostProcesses();
  111417. }
  111418. };
  111419. /**
  111420. * Determine if a given mesh will be used in the current effect.
  111421. * @param mesh mesh to test
  111422. * @returns true if the mesh will be used
  111423. */
  111424. EffectLayer.prototype.hasMesh = function (mesh) {
  111425. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  111426. return true;
  111427. }
  111428. return false;
  111429. };
  111430. /**
  111431. * Returns true if the layer contains information to display, otherwise false.
  111432. * @returns true if the glow layer should be rendered
  111433. */
  111434. EffectLayer.prototype.shouldRender = function () {
  111435. return this.isEnabled && this._shouldRender;
  111436. };
  111437. /**
  111438. * Returns true if the mesh should render, otherwise false.
  111439. * @param mesh The mesh to render
  111440. * @returns true if it should render otherwise false
  111441. */
  111442. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  111443. return true;
  111444. };
  111445. /**
  111446. * Returns true if the mesh should render, otherwise false.
  111447. * @param mesh The mesh to render
  111448. * @returns true if it should render otherwise false
  111449. */
  111450. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  111451. return true;
  111452. };
  111453. /**
  111454. * Renders the submesh passed in parameter to the generation map.
  111455. */
  111456. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  111457. var _this = this;
  111458. if (!this.shouldRender()) {
  111459. return;
  111460. }
  111461. var material = subMesh.getMaterial();
  111462. var mesh = subMesh.getRenderingMesh();
  111463. var scene = this._scene;
  111464. var engine = scene.getEngine();
  111465. if (!material) {
  111466. return;
  111467. }
  111468. // Do not block in blend mode.
  111469. if (material.needAlphaBlendingForMesh(mesh)) {
  111470. return;
  111471. }
  111472. // Culling
  111473. engine.setState(material.backFaceCulling);
  111474. // Managing instances
  111475. var batch = mesh._getInstancesRenderList(subMesh._id);
  111476. if (batch.mustReturn) {
  111477. return;
  111478. }
  111479. // Early Exit per mesh
  111480. if (!this._shouldRenderMesh(mesh)) {
  111481. return;
  111482. }
  111483. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  111484. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  111485. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  111486. engine.enableEffect(this._effectLayerMapGenerationEffect);
  111487. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  111488. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  111489. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  111490. // Alpha test
  111491. if (material && material.needAlphaTesting()) {
  111492. var alphaTexture = material.getAlphaTestTexture();
  111493. if (alphaTexture) {
  111494. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  111495. var textureMatrix = alphaTexture.getTextureMatrix();
  111496. if (textureMatrix) {
  111497. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  111498. }
  111499. }
  111500. }
  111501. // Glow emissive only
  111502. if (this._emissiveTextureAndColor.texture) {
  111503. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  111504. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  111505. }
  111506. // Bones
  111507. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  111508. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  111509. }
  111510. // Morph targets
  111511. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  111512. // Draw
  111513. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  111514. }
  111515. else {
  111516. // Need to reset refresh rate of the main map
  111517. this._mainTexture.resetRefreshCounter();
  111518. }
  111519. };
  111520. /**
  111521. * Rebuild the required buffers.
  111522. * @hidden Internal use only.
  111523. */
  111524. EffectLayer.prototype._rebuild = function () {
  111525. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  111526. if (vb) {
  111527. vb._rebuild();
  111528. }
  111529. this._generateIndexBuffer();
  111530. };
  111531. /**
  111532. * Dispose only the render target textures and post process.
  111533. */
  111534. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  111535. this._mainTexture.dispose();
  111536. for (var i = 0; i < this._postProcesses.length; i++) {
  111537. if (this._postProcesses[i]) {
  111538. this._postProcesses[i].dispose();
  111539. }
  111540. }
  111541. this._postProcesses = [];
  111542. for (var i = 0; i < this._textures.length; i++) {
  111543. if (this._textures[i]) {
  111544. this._textures[i].dispose();
  111545. }
  111546. }
  111547. this._textures = [];
  111548. };
  111549. /**
  111550. * Dispose the highlight layer and free resources.
  111551. */
  111552. EffectLayer.prototype.dispose = function () {
  111553. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  111554. if (vertexBuffer) {
  111555. vertexBuffer.dispose();
  111556. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  111557. }
  111558. if (this._indexBuffer) {
  111559. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  111560. this._indexBuffer = null;
  111561. }
  111562. // Clean textures and post processes
  111563. this._disposeTextureAndPostProcesses();
  111564. // Remove from scene
  111565. var index = this._scene.effectLayers.indexOf(this, 0);
  111566. if (index > -1) {
  111567. this._scene.effectLayers.splice(index, 1);
  111568. }
  111569. // Callback
  111570. this.onDisposeObservable.notifyObservers(this);
  111571. this.onDisposeObservable.clear();
  111572. this.onBeforeRenderMainTextureObservable.clear();
  111573. this.onBeforeComposeObservable.clear();
  111574. this.onAfterComposeObservable.clear();
  111575. this.onSizeChangedObservable.clear();
  111576. };
  111577. /**
  111578. * Gets the class name of the effect layer
  111579. * @returns the string with the class name of the effect layer
  111580. */
  111581. EffectLayer.prototype.getClassName = function () {
  111582. return "EffectLayer";
  111583. };
  111584. /**
  111585. * Creates an effect layer from parsed effect layer data
  111586. * @param parsedEffectLayer defines effect layer data
  111587. * @param scene defines the current scene
  111588. * @param rootUrl defines the root URL containing the effect layer information
  111589. * @returns a parsed effect Layer
  111590. */
  111591. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  111592. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  111593. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  111594. };
  111595. __decorate([
  111596. BABYLON.serialize()
  111597. ], EffectLayer.prototype, "name", void 0);
  111598. __decorate([
  111599. BABYLON.serializeAsColor4()
  111600. ], EffectLayer.prototype, "neutralColor", void 0);
  111601. __decorate([
  111602. BABYLON.serialize()
  111603. ], EffectLayer.prototype, "isEnabled", void 0);
  111604. __decorate([
  111605. BABYLON.serializeAsCameraReference()
  111606. ], EffectLayer.prototype, "camera", null);
  111607. __decorate([
  111608. BABYLON.serialize()
  111609. ], EffectLayer.prototype, "renderingGroupId", null);
  111610. return EffectLayer;
  111611. }());
  111612. BABYLON.EffectLayer = EffectLayer;
  111613. })(BABYLON || (BABYLON = {}));
  111614. //# sourceMappingURL=babylon.effectLayer.js.map
  111615. var BABYLON;
  111616. (function (BABYLON) {
  111617. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  111618. for (var index = 0; index < this.effectLayers.length; index++) {
  111619. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  111620. return this.effectLayers[index];
  111621. }
  111622. }
  111623. return null;
  111624. };
  111625. /**
  111626. * Special Glow Blur post process only blurring the alpha channel
  111627. * It enforces keeping the most luminous color in the color channel.
  111628. */
  111629. var GlowBlurPostProcess = /** @class */ (function (_super) {
  111630. __extends(GlowBlurPostProcess, _super);
  111631. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  111632. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  111633. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  111634. _this.direction = direction;
  111635. _this.kernel = kernel;
  111636. _this.onApplyObservable.add(function (effect) {
  111637. effect.setFloat2("screenSize", _this.width, _this.height);
  111638. effect.setVector2("direction", _this.direction);
  111639. effect.setFloat("blurWidth", _this.kernel);
  111640. });
  111641. return _this;
  111642. }
  111643. return GlowBlurPostProcess;
  111644. }(BABYLON.PostProcess));
  111645. /**
  111646. * The highlight layer Helps adding a glow effect around a mesh.
  111647. *
  111648. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  111649. * glowy meshes to your scene.
  111650. *
  111651. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  111652. */
  111653. var HighlightLayer = /** @class */ (function (_super) {
  111654. __extends(HighlightLayer, _super);
  111655. /**
  111656. * Instantiates a new highlight Layer and references it to the scene..
  111657. * @param name The name of the layer
  111658. * @param scene The scene to use the layer in
  111659. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  111660. */
  111661. function HighlightLayer(name, scene, options) {
  111662. var _this = _super.call(this, name, scene) || this;
  111663. _this.name = name;
  111664. /**
  111665. * Specifies whether or not the inner glow is ACTIVE in the layer.
  111666. */
  111667. _this.innerGlow = true;
  111668. /**
  111669. * Specifies whether or not the outer glow is ACTIVE in the layer.
  111670. */
  111671. _this.outerGlow = true;
  111672. /**
  111673. * An event triggered when the highlight layer is being blurred.
  111674. */
  111675. _this.onBeforeBlurObservable = new BABYLON.Observable();
  111676. /**
  111677. * An event triggered when the highlight layer has been blurred.
  111678. */
  111679. _this.onAfterBlurObservable = new BABYLON.Observable();
  111680. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  111681. _this._meshes = {};
  111682. _this._excludedMeshes = {};
  111683. _this.neutralColor = HighlightLayer.NeutralColor;
  111684. // Warn on stencil
  111685. if (!_this._engine.isStencilEnable) {
  111686. 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 }");
  111687. }
  111688. // Adapt options
  111689. _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);
  111690. // Initialize the layer
  111691. _this._init({
  111692. alphaBlendingMode: _this._options.alphaBlendingMode,
  111693. camera: _this._options.camera,
  111694. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  111695. mainTextureRatio: _this._options.mainTextureRatio,
  111696. renderingGroupId: _this._options.renderingGroupId
  111697. });
  111698. // Do not render as long as no meshes have been added
  111699. _this._shouldRender = false;
  111700. return _this;
  111701. }
  111702. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  111703. /**
  111704. * Gets the horizontal size of the blur.
  111705. */
  111706. get: function () {
  111707. return this._horizontalBlurPostprocess.kernel;
  111708. },
  111709. /**
  111710. * Specifies the horizontal size of the blur.
  111711. */
  111712. set: function (value) {
  111713. this._horizontalBlurPostprocess.kernel = value;
  111714. },
  111715. enumerable: true,
  111716. configurable: true
  111717. });
  111718. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  111719. /**
  111720. * Gets the vertical size of the blur.
  111721. */
  111722. get: function () {
  111723. return this._verticalBlurPostprocess.kernel;
  111724. },
  111725. /**
  111726. * Specifies the vertical size of the blur.
  111727. */
  111728. set: function (value) {
  111729. this._verticalBlurPostprocess.kernel = value;
  111730. },
  111731. enumerable: true,
  111732. configurable: true
  111733. });
  111734. /**
  111735. * Get the effect name of the layer.
  111736. * @return The effect name
  111737. */
  111738. HighlightLayer.prototype.getEffectName = function () {
  111739. return HighlightLayer.EffectName;
  111740. };
  111741. /**
  111742. * Create the merge effect. This is the shader use to blit the information back
  111743. * to the main canvas at the end of the scene rendering.
  111744. */
  111745. HighlightLayer.prototype._createMergeEffect = function () {
  111746. // Effect
  111747. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  111748. };
  111749. /**
  111750. * Creates the render target textures and post processes used in the highlight layer.
  111751. */
  111752. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  111753. var _this = this;
  111754. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  111755. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  111756. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  111757. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  111758. var textureType = 0;
  111759. if (this._engine.getCaps().textureHalfFloatRender) {
  111760. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  111761. }
  111762. else {
  111763. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  111764. }
  111765. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  111766. width: blurTextureWidth,
  111767. height: blurTextureHeight
  111768. }, this._scene, false, true, textureType);
  111769. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111770. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111771. this._blurTexture.anisotropicFilteringLevel = 16;
  111772. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  111773. this._blurTexture.renderParticles = false;
  111774. this._blurTexture.ignoreCameraViewport = true;
  111775. this._textures = [this._blurTexture];
  111776. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  111777. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  111778. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  111779. effect.setTexture("textureSampler", _this._mainTexture);
  111780. });
  111781. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  111782. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  111783. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  111784. });
  111785. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  111786. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  111787. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  111788. });
  111789. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  111790. }
  111791. else {
  111792. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  111793. width: blurTextureWidth,
  111794. height: blurTextureHeight
  111795. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111796. this._horizontalBlurPostprocess.width = blurTextureWidth;
  111797. this._horizontalBlurPostprocess.height = blurTextureHeight;
  111798. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  111799. effect.setTexture("textureSampler", _this._mainTexture);
  111800. });
  111801. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  111802. width: blurTextureWidth,
  111803. height: blurTextureHeight
  111804. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111805. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  111806. }
  111807. this._mainTexture.onAfterUnbindObservable.add(function () {
  111808. _this.onBeforeBlurObservable.notifyObservers(_this);
  111809. var internalTexture = _this._blurTexture.getInternalTexture();
  111810. if (internalTexture) {
  111811. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  111812. }
  111813. _this.onAfterBlurObservable.notifyObservers(_this);
  111814. });
  111815. // Prevent autoClear.
  111816. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  111817. };
  111818. /**
  111819. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  111820. */
  111821. HighlightLayer.prototype.needStencil = function () {
  111822. return true;
  111823. };
  111824. /**
  111825. * Checks for the readiness of the element composing the layer.
  111826. * @param subMesh the mesh to check for
  111827. * @param useInstances specify wether or not to use instances to render the mesh
  111828. * @param emissiveTexture the associated emissive texture used to generate the glow
  111829. * @return true if ready otherwise, false
  111830. */
  111831. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  111832. var material = subMesh.getMaterial();
  111833. var mesh = subMesh.getRenderingMesh();
  111834. if (!material || !mesh || !this._meshes) {
  111835. return false;
  111836. }
  111837. var emissiveTexture = null;
  111838. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  111839. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  111840. emissiveTexture = material.emissiveTexture;
  111841. }
  111842. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  111843. };
  111844. /**
  111845. * Implementation specific of rendering the generating effect on the main canvas.
  111846. * @param effect The effect used to render through
  111847. */
  111848. HighlightLayer.prototype._internalRender = function (effect) {
  111849. // Texture
  111850. effect.setTexture("textureSampler", this._blurTexture);
  111851. // Cache
  111852. var engine = this._engine;
  111853. var previousStencilBuffer = engine.getStencilBuffer();
  111854. var previousStencilFunction = engine.getStencilFunction();
  111855. var previousStencilMask = engine.getStencilMask();
  111856. var previousStencilOperationPass = engine.getStencilOperationPass();
  111857. var previousStencilOperationFail = engine.getStencilOperationFail();
  111858. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  111859. var previousStencilReference = engine.getStencilFunctionReference();
  111860. // Stencil operations
  111861. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  111862. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  111863. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  111864. // Draw order
  111865. engine.setStencilMask(0x00);
  111866. engine.setStencilBuffer(true);
  111867. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  111868. // 2 passes inner outer
  111869. if (this.outerGlow) {
  111870. effect.setFloat("offset", 0);
  111871. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  111872. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111873. }
  111874. if (this.innerGlow) {
  111875. effect.setFloat("offset", 1);
  111876. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  111877. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111878. }
  111879. // Restore Cache
  111880. engine.setStencilFunction(previousStencilFunction);
  111881. engine.setStencilMask(previousStencilMask);
  111882. engine.setStencilBuffer(previousStencilBuffer);
  111883. engine.setStencilOperationPass(previousStencilOperationPass);
  111884. engine.setStencilOperationFail(previousStencilOperationFail);
  111885. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  111886. engine.setStencilFunctionReference(previousStencilReference);
  111887. };
  111888. /**
  111889. * Returns true if the layer contains information to display, otherwise false.
  111890. */
  111891. HighlightLayer.prototype.shouldRender = function () {
  111892. if (_super.prototype.shouldRender.call(this)) {
  111893. return this._meshes ? true : false;
  111894. }
  111895. return false;
  111896. };
  111897. /**
  111898. * Returns true if the mesh should render, otherwise false.
  111899. * @param mesh The mesh to render
  111900. * @returns true if it should render otherwise false
  111901. */
  111902. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  111903. // Excluded Mesh
  111904. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  111905. return false;
  111906. }
  111907. if (!_super.prototype.hasMesh.call(this, mesh)) {
  111908. return false;
  111909. }
  111910. return true;
  111911. };
  111912. /**
  111913. * Sets the required values for both the emissive texture and and the main color.
  111914. */
  111915. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  111916. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  111917. if (highlightLayerMesh) {
  111918. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  111919. }
  111920. else {
  111921. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  111922. }
  111923. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  111924. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  111925. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  111926. }
  111927. else {
  111928. this._emissiveTextureAndColor.texture = null;
  111929. }
  111930. };
  111931. /**
  111932. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  111933. * @param mesh The mesh to exclude from the highlight layer
  111934. */
  111935. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  111936. if (!this._excludedMeshes) {
  111937. return;
  111938. }
  111939. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  111940. if (!meshExcluded) {
  111941. this._excludedMeshes[mesh.uniqueId] = {
  111942. mesh: mesh,
  111943. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  111944. mesh.getEngine().setStencilBuffer(false);
  111945. }),
  111946. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  111947. mesh.getEngine().setStencilBuffer(true);
  111948. }),
  111949. };
  111950. }
  111951. };
  111952. /**
  111953. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  111954. * @param mesh The mesh to highlight
  111955. */
  111956. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  111957. if (!this._excludedMeshes) {
  111958. return;
  111959. }
  111960. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  111961. if (meshExcluded) {
  111962. if (meshExcluded.beforeRender) {
  111963. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  111964. }
  111965. if (meshExcluded.afterRender) {
  111966. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  111967. }
  111968. }
  111969. this._excludedMeshes[mesh.uniqueId] = null;
  111970. };
  111971. /**
  111972. * Determine if a given mesh will be highlighted by the current HighlightLayer
  111973. * @param mesh mesh to test
  111974. * @returns true if the mesh will be highlighted by the current HighlightLayer
  111975. */
  111976. HighlightLayer.prototype.hasMesh = function (mesh) {
  111977. if (!this._meshes) {
  111978. return false;
  111979. }
  111980. if (!_super.prototype.hasMesh.call(this, mesh)) {
  111981. return false;
  111982. }
  111983. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  111984. };
  111985. /**
  111986. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  111987. * @param mesh The mesh to highlight
  111988. * @param color The color of the highlight
  111989. * @param glowEmissiveOnly Extract the glow from the emissive texture
  111990. */
  111991. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  111992. var _this = this;
  111993. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  111994. if (!this._meshes) {
  111995. return;
  111996. }
  111997. var meshHighlight = this._meshes[mesh.uniqueId];
  111998. if (meshHighlight) {
  111999. meshHighlight.color = color;
  112000. }
  112001. else {
  112002. this._meshes[mesh.uniqueId] = {
  112003. mesh: mesh,
  112004. color: color,
  112005. // Lambda required for capture due to Observable this context
  112006. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  112007. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  112008. _this._defaultStencilReference(mesh);
  112009. }
  112010. else {
  112011. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  112012. }
  112013. }),
  112014. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  112015. glowEmissiveOnly: glowEmissiveOnly
  112016. };
  112017. mesh.onDisposeObservable.add(function () {
  112018. _this._disposeMesh(mesh);
  112019. });
  112020. }
  112021. this._shouldRender = true;
  112022. };
  112023. /**
  112024. * Remove a mesh from the highlight layer in order to make it stop glowing.
  112025. * @param mesh The mesh to highlight
  112026. */
  112027. HighlightLayer.prototype.removeMesh = function (mesh) {
  112028. if (!this._meshes) {
  112029. return;
  112030. }
  112031. var meshHighlight = this._meshes[mesh.uniqueId];
  112032. if (meshHighlight) {
  112033. if (meshHighlight.observerHighlight) {
  112034. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  112035. }
  112036. if (meshHighlight.observerDefault) {
  112037. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  112038. }
  112039. delete this._meshes[mesh.uniqueId];
  112040. }
  112041. this._shouldRender = false;
  112042. for (var meshHighlightToCheck in this._meshes) {
  112043. if (this._meshes[meshHighlightToCheck]) {
  112044. this._shouldRender = true;
  112045. break;
  112046. }
  112047. }
  112048. };
  112049. /**
  112050. * Force the stencil to the normal expected value for none glowing parts
  112051. */
  112052. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  112053. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  112054. };
  112055. /**
  112056. * Free any resources and references associated to a mesh.
  112057. * Internal use
  112058. * @param mesh The mesh to free.
  112059. * @hidden
  112060. */
  112061. HighlightLayer.prototype._disposeMesh = function (mesh) {
  112062. this.removeMesh(mesh);
  112063. this.removeExcludedMesh(mesh);
  112064. };
  112065. /**
  112066. * Dispose the highlight layer and free resources.
  112067. */
  112068. HighlightLayer.prototype.dispose = function () {
  112069. if (this._meshes) {
  112070. // Clean mesh references
  112071. for (var id in this._meshes) {
  112072. var meshHighlight = this._meshes[id];
  112073. if (meshHighlight && meshHighlight.mesh) {
  112074. if (meshHighlight.observerHighlight) {
  112075. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  112076. }
  112077. if (meshHighlight.observerDefault) {
  112078. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  112079. }
  112080. }
  112081. }
  112082. this._meshes = null;
  112083. }
  112084. if (this._excludedMeshes) {
  112085. for (var id in this._excludedMeshes) {
  112086. var meshHighlight = this._excludedMeshes[id];
  112087. if (meshHighlight) {
  112088. if (meshHighlight.beforeRender) {
  112089. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  112090. }
  112091. if (meshHighlight.afterRender) {
  112092. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  112093. }
  112094. }
  112095. }
  112096. this._excludedMeshes = null;
  112097. }
  112098. _super.prototype.dispose.call(this);
  112099. };
  112100. /**
  112101. * Gets the class name of the effect layer
  112102. * @returns the string with the class name of the effect layer
  112103. */
  112104. HighlightLayer.prototype.getClassName = function () {
  112105. return "HighlightLayer";
  112106. };
  112107. /**
  112108. * Serializes this Highlight layer
  112109. * @returns a serialized Highlight layer object
  112110. */
  112111. HighlightLayer.prototype.serialize = function () {
  112112. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  112113. serializationObject.customType = "BABYLON.HighlightLayer";
  112114. // Highlighted meshes
  112115. serializationObject.meshes = [];
  112116. if (this._meshes) {
  112117. for (var m in this._meshes) {
  112118. var mesh = this._meshes[m];
  112119. if (mesh) {
  112120. serializationObject.meshes.push({
  112121. glowEmissiveOnly: mesh.glowEmissiveOnly,
  112122. color: mesh.color.asArray(),
  112123. meshId: mesh.mesh.id
  112124. });
  112125. }
  112126. }
  112127. }
  112128. // Excluded meshes
  112129. serializationObject.excludedMeshes = [];
  112130. if (this._excludedMeshes) {
  112131. for (var e in this._excludedMeshes) {
  112132. var excludedMesh = this._excludedMeshes[e];
  112133. if (excludedMesh) {
  112134. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  112135. }
  112136. }
  112137. }
  112138. return serializationObject;
  112139. };
  112140. /**
  112141. * Creates a Highlight layer from parsed Highlight layer data
  112142. * @param parsedHightlightLayer defines the Highlight layer data
  112143. * @param scene defines the current scene
  112144. * @param rootUrl defines the root URL containing the Highlight layer information
  112145. * @returns a parsed Highlight layer
  112146. */
  112147. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  112148. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  112149. var index;
  112150. // Excluded meshes
  112151. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  112152. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  112153. if (mesh) {
  112154. hl.addExcludedMesh(mesh);
  112155. }
  112156. }
  112157. // Included meshes
  112158. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  112159. var highlightedMesh = parsedHightlightLayer.meshes[index];
  112160. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  112161. if (mesh) {
  112162. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  112163. }
  112164. }
  112165. return hl;
  112166. };
  112167. /**
  112168. * Effect Name of the highlight layer.
  112169. */
  112170. HighlightLayer.EffectName = "HighlightLayer";
  112171. /**
  112172. * The neutral color used during the preparation of the glow effect.
  112173. * This is black by default as the blend operation is a blend operation.
  112174. */
  112175. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  112176. /**
  112177. * Stencil value used for glowing meshes.
  112178. */
  112179. HighlightLayer.GlowingMeshStencilReference = 0x02;
  112180. /**
  112181. * Stencil value used for the other meshes in the scene.
  112182. */
  112183. HighlightLayer.NormalMeshStencilReference = 0x01;
  112184. __decorate([
  112185. BABYLON.serialize()
  112186. ], HighlightLayer.prototype, "innerGlow", void 0);
  112187. __decorate([
  112188. BABYLON.serialize()
  112189. ], HighlightLayer.prototype, "outerGlow", void 0);
  112190. __decorate([
  112191. BABYLON.serialize()
  112192. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  112193. __decorate([
  112194. BABYLON.serialize()
  112195. ], HighlightLayer.prototype, "blurVerticalSize", null);
  112196. __decorate([
  112197. BABYLON.serialize("options")
  112198. ], HighlightLayer.prototype, "_options", void 0);
  112199. return HighlightLayer;
  112200. }(BABYLON.EffectLayer));
  112201. BABYLON.HighlightLayer = HighlightLayer;
  112202. })(BABYLON || (BABYLON = {}));
  112203. //# sourceMappingURL=babylon.highlightLayer.js.map
  112204. var BABYLON;
  112205. (function (BABYLON) {
  112206. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  112207. for (var index = 0; index < this.effectLayers.length; index++) {
  112208. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  112209. return this.effectLayers[index];
  112210. }
  112211. }
  112212. return null;
  112213. };
  112214. /**
  112215. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  112216. *
  112217. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  112218. * glowy meshes to your scene.
  112219. *
  112220. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  112221. */
  112222. var GlowLayer = /** @class */ (function (_super) {
  112223. __extends(GlowLayer, _super);
  112224. /**
  112225. * Instantiates a new glow Layer and references it to the scene.
  112226. * @param name The name of the layer
  112227. * @param scene The scene to use the layer in
  112228. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  112229. */
  112230. function GlowLayer(name, scene, options) {
  112231. var _this = _super.call(this, name, scene) || this;
  112232. _this._intensity = 1.0;
  112233. _this._includedOnlyMeshes = [];
  112234. _this._excludedMeshes = [];
  112235. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  112236. // Adapt options
  112237. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  112238. // Initialize the layer
  112239. _this._init({
  112240. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  112241. camera: _this._options.camera,
  112242. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  112243. mainTextureRatio: _this._options.mainTextureRatio,
  112244. renderingGroupId: _this._options.renderingGroupId
  112245. });
  112246. return _this;
  112247. }
  112248. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  112249. /**
  112250. * Gets the kernel size of the blur.
  112251. */
  112252. get: function () {
  112253. return this._horizontalBlurPostprocess1.kernel;
  112254. },
  112255. /**
  112256. * Sets the kernel size of the blur.
  112257. */
  112258. set: function (value) {
  112259. this._horizontalBlurPostprocess1.kernel = value;
  112260. this._verticalBlurPostprocess1.kernel = value;
  112261. this._horizontalBlurPostprocess2.kernel = value;
  112262. this._verticalBlurPostprocess2.kernel = value;
  112263. },
  112264. enumerable: true,
  112265. configurable: true
  112266. });
  112267. Object.defineProperty(GlowLayer.prototype, "intensity", {
  112268. /**
  112269. * Gets the glow intensity.
  112270. */
  112271. get: function () {
  112272. return this._intensity;
  112273. },
  112274. /**
  112275. * Sets the glow intensity.
  112276. */
  112277. set: function (value) {
  112278. this._intensity = value;
  112279. },
  112280. enumerable: true,
  112281. configurable: true
  112282. });
  112283. /**
  112284. * Get the effect name of the layer.
  112285. * @return The effect name
  112286. */
  112287. GlowLayer.prototype.getEffectName = function () {
  112288. return GlowLayer.EffectName;
  112289. };
  112290. /**
  112291. * Create the merge effect. This is the shader use to blit the information back
  112292. * to the main canvas at the end of the scene rendering.
  112293. */
  112294. GlowLayer.prototype._createMergeEffect = function () {
  112295. // Effect
  112296. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  112297. };
  112298. /**
  112299. * Creates the render target textures and post processes used in the glow layer.
  112300. */
  112301. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  112302. var _this = this;
  112303. var blurTextureWidth = this._mainTextureDesiredSize.width;
  112304. var blurTextureHeight = this._mainTextureDesiredSize.height;
  112305. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  112306. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  112307. var textureType = 0;
  112308. if (this._engine.getCaps().textureHalfFloatRender) {
  112309. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  112310. }
  112311. else {
  112312. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  112313. }
  112314. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  112315. width: blurTextureWidth,
  112316. height: blurTextureHeight
  112317. }, this._scene, false, true, textureType);
  112318. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112319. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112320. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  112321. this._blurTexture1.renderParticles = false;
  112322. this._blurTexture1.ignoreCameraViewport = true;
  112323. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  112324. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  112325. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  112326. width: blurTextureWidth2,
  112327. height: blurTextureHeight2
  112328. }, this._scene, false, true, textureType);
  112329. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112330. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112331. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  112332. this._blurTexture2.renderParticles = false;
  112333. this._blurTexture2.ignoreCameraViewport = true;
  112334. this._textures = [this._blurTexture1, this._blurTexture2];
  112335. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  112336. width: blurTextureWidth,
  112337. height: blurTextureHeight
  112338. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112339. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  112340. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  112341. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  112342. effect.setTexture("textureSampler", _this._mainTexture);
  112343. });
  112344. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  112345. width: blurTextureWidth,
  112346. height: blurTextureHeight
  112347. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112348. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  112349. width: blurTextureWidth2,
  112350. height: blurTextureHeight2
  112351. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112352. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  112353. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  112354. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  112355. effect.setTexture("textureSampler", _this._blurTexture1);
  112356. });
  112357. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  112358. width: blurTextureWidth2,
  112359. height: blurTextureHeight2
  112360. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112361. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  112362. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  112363. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  112364. this._mainTexture.samples = this._options.mainTextureSamples;
  112365. this._mainTexture.onAfterUnbindObservable.add(function () {
  112366. var internalTexture = _this._blurTexture1.getInternalTexture();
  112367. if (internalTexture) {
  112368. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  112369. internalTexture = _this._blurTexture2.getInternalTexture();
  112370. if (internalTexture) {
  112371. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  112372. }
  112373. }
  112374. });
  112375. // Prevent autoClear.
  112376. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  112377. };
  112378. /**
  112379. * Checks for the readiness of the element composing the layer.
  112380. * @param subMesh the mesh to check for
  112381. * @param useInstances specify wether or not to use instances to render the mesh
  112382. * @param emissiveTexture the associated emissive texture used to generate the glow
  112383. * @return true if ready otherwise, false
  112384. */
  112385. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  112386. var material = subMesh.getMaterial();
  112387. var mesh = subMesh.getRenderingMesh();
  112388. if (!material || !mesh) {
  112389. return false;
  112390. }
  112391. var emissiveTexture = material.emissiveTexture;
  112392. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  112393. };
  112394. /**
  112395. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  112396. */
  112397. GlowLayer.prototype.needStencil = function () {
  112398. return false;
  112399. };
  112400. /**
  112401. * Implementation specific of rendering the generating effect on the main canvas.
  112402. * @param effect The effect used to render through
  112403. */
  112404. GlowLayer.prototype._internalRender = function (effect) {
  112405. // Texture
  112406. effect.setTexture("textureSampler", this._blurTexture1);
  112407. effect.setTexture("textureSampler2", this._blurTexture2);
  112408. effect.setFloat("offset", this._intensity);
  112409. // Cache
  112410. var engine = this._engine;
  112411. var previousStencilBuffer = engine.getStencilBuffer();
  112412. // Draw order
  112413. engine.setStencilBuffer(false);
  112414. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112415. // Draw order
  112416. engine.setStencilBuffer(previousStencilBuffer);
  112417. };
  112418. /**
  112419. * Sets the required values for both the emissive texture and and the main color.
  112420. */
  112421. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  112422. var textureLevel = 1.0;
  112423. if (this.customEmissiveTextureSelector) {
  112424. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  112425. }
  112426. else {
  112427. if (material) {
  112428. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  112429. if (this._emissiveTextureAndColor.texture) {
  112430. textureLevel = this._emissiveTextureAndColor.texture.level;
  112431. }
  112432. }
  112433. else {
  112434. this._emissiveTextureAndColor.texture = null;
  112435. }
  112436. }
  112437. if (this.customEmissiveColorSelector) {
  112438. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  112439. }
  112440. else {
  112441. if (material.emissiveColor) {
  112442. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  112443. }
  112444. else {
  112445. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  112446. }
  112447. }
  112448. };
  112449. /**
  112450. * Returns true if the mesh should render, otherwise false.
  112451. * @param mesh The mesh to render
  112452. * @returns true if it should render otherwise false
  112453. */
  112454. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  112455. return this.hasMesh(mesh);
  112456. };
  112457. /**
  112458. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  112459. * @param mesh The mesh to exclude from the glow layer
  112460. */
  112461. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  112462. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  112463. this._excludedMeshes.push(mesh.uniqueId);
  112464. }
  112465. };
  112466. /**
  112467. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  112468. * @param mesh The mesh to remove
  112469. */
  112470. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  112471. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  112472. if (index !== -1) {
  112473. this._excludedMeshes.splice(index, 1);
  112474. }
  112475. };
  112476. /**
  112477. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  112478. * @param mesh The mesh to include in the glow layer
  112479. */
  112480. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  112481. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  112482. this._includedOnlyMeshes.push(mesh.uniqueId);
  112483. }
  112484. };
  112485. /**
  112486. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  112487. * @param mesh The mesh to remove
  112488. */
  112489. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  112490. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  112491. if (index !== -1) {
  112492. this._includedOnlyMeshes.splice(index, 1);
  112493. }
  112494. };
  112495. /**
  112496. * Determine if a given mesh will be used in the glow layer
  112497. * @param mesh The mesh to test
  112498. * @returns true if the mesh will be highlighted by the current glow layer
  112499. */
  112500. GlowLayer.prototype.hasMesh = function (mesh) {
  112501. if (!_super.prototype.hasMesh.call(this, mesh)) {
  112502. return false;
  112503. }
  112504. // Included Mesh
  112505. if (this._includedOnlyMeshes.length) {
  112506. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  112507. }
  112508. // Excluded Mesh
  112509. if (this._excludedMeshes.length) {
  112510. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  112511. }
  112512. return true;
  112513. };
  112514. /**
  112515. * Free any resources and references associated to a mesh.
  112516. * Internal use
  112517. * @param mesh The mesh to free.
  112518. * @hidden
  112519. */
  112520. GlowLayer.prototype._disposeMesh = function (mesh) {
  112521. this.removeIncludedOnlyMesh(mesh);
  112522. this.removeExcludedMesh(mesh);
  112523. };
  112524. /**
  112525. * Gets the class name of the effect layer
  112526. * @returns the string with the class name of the effect layer
  112527. */
  112528. GlowLayer.prototype.getClassName = function () {
  112529. return "GlowLayer";
  112530. };
  112531. /**
  112532. * Serializes this glow layer
  112533. * @returns a serialized glow layer object
  112534. */
  112535. GlowLayer.prototype.serialize = function () {
  112536. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  112537. serializationObject.customType = "BABYLON.GlowLayer";
  112538. var index;
  112539. // Included meshes
  112540. serializationObject.includedMeshes = [];
  112541. if (this._includedOnlyMeshes.length) {
  112542. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  112543. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  112544. if (mesh) {
  112545. serializationObject.includedMeshes.push(mesh.id);
  112546. }
  112547. }
  112548. }
  112549. // Excluded meshes
  112550. serializationObject.excludedMeshes = [];
  112551. if (this._excludedMeshes.length) {
  112552. for (index = 0; index < this._excludedMeshes.length; index++) {
  112553. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  112554. if (mesh) {
  112555. serializationObject.excludedMeshes.push(mesh.id);
  112556. }
  112557. }
  112558. }
  112559. return serializationObject;
  112560. };
  112561. /**
  112562. * Creates a Glow Layer from parsed glow layer data
  112563. * @param parsedGlowLayer defines glow layer data
  112564. * @param scene defines the current scene
  112565. * @param rootUrl defines the root URL containing the glow layer information
  112566. * @returns a parsed Glow Layer
  112567. */
  112568. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  112569. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  112570. var index;
  112571. // Excluded meshes
  112572. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  112573. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  112574. if (mesh) {
  112575. gl.addExcludedMesh(mesh);
  112576. }
  112577. }
  112578. // Included meshes
  112579. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  112580. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  112581. if (mesh) {
  112582. gl.addIncludedOnlyMesh(mesh);
  112583. }
  112584. }
  112585. return gl;
  112586. };
  112587. /**
  112588. * Effect Name of the layer.
  112589. */
  112590. GlowLayer.EffectName = "GlowLayer";
  112591. /**
  112592. * The default blur kernel size used for the glow.
  112593. */
  112594. GlowLayer.DefaultBlurKernelSize = 32;
  112595. /**
  112596. * The default texture size ratio used for the glow.
  112597. */
  112598. GlowLayer.DefaultTextureRatio = 0.5;
  112599. __decorate([
  112600. BABYLON.serialize()
  112601. ], GlowLayer.prototype, "blurKernelSize", null);
  112602. __decorate([
  112603. BABYLON.serialize()
  112604. ], GlowLayer.prototype, "intensity", null);
  112605. __decorate([
  112606. BABYLON.serialize("options")
  112607. ], GlowLayer.prototype, "_options", void 0);
  112608. return GlowLayer;
  112609. }(BABYLON.EffectLayer));
  112610. BABYLON.GlowLayer = GlowLayer;
  112611. })(BABYLON || (BABYLON = {}));
  112612. //# sourceMappingURL=babylon.glowLayer.js.map
  112613. var BABYLON;
  112614. (function (BABYLON) {
  112615. /**
  112616. * Defines the list of states available for a task inside a AssetsManager
  112617. */
  112618. var AssetTaskState;
  112619. (function (AssetTaskState) {
  112620. /**
  112621. * Initialization
  112622. */
  112623. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  112624. /**
  112625. * Running
  112626. */
  112627. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  112628. /**
  112629. * Done
  112630. */
  112631. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  112632. /**
  112633. * Error
  112634. */
  112635. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  112636. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  112637. /**
  112638. * Define an abstract asset task used with a AssetsManager class to load assets into a scene
  112639. */
  112640. var AbstractAssetTask = /** @class */ (function () {
  112641. /**
  112642. * Creates a new AssetsManager
  112643. * @param name defines the name of the task
  112644. */
  112645. function AbstractAssetTask(
  112646. /**
  112647. * Task name
  112648. */ name) {
  112649. this.name = name;
  112650. this._isCompleted = false;
  112651. this._taskState = AssetTaskState.INIT;
  112652. }
  112653. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  112654. /**
  112655. * Get if the task is completed
  112656. */
  112657. get: function () {
  112658. return this._isCompleted;
  112659. },
  112660. enumerable: true,
  112661. configurable: true
  112662. });
  112663. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  112664. /**
  112665. * Gets the current state of the task
  112666. */
  112667. get: function () {
  112668. return this._taskState;
  112669. },
  112670. enumerable: true,
  112671. configurable: true
  112672. });
  112673. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  112674. /**
  112675. * Gets the current error object (if task is in error)
  112676. */
  112677. get: function () {
  112678. return this._errorObject;
  112679. },
  112680. enumerable: true,
  112681. configurable: true
  112682. });
  112683. /**
  112684. * Internal only
  112685. * @hidden
  112686. */
  112687. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  112688. if (this._errorObject) {
  112689. return;
  112690. }
  112691. this._errorObject = {
  112692. message: message,
  112693. exception: exception
  112694. };
  112695. };
  112696. /**
  112697. * Execute the current task
  112698. * @param scene defines the scene where you want your assets to be loaded
  112699. * @param onSuccess is a callback called when the task is successfully executed
  112700. * @param onError is a callback called if an error occurs
  112701. */
  112702. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  112703. var _this = this;
  112704. this._taskState = AssetTaskState.RUNNING;
  112705. this.runTask(scene, function () {
  112706. _this.onDoneCallback(onSuccess, onError);
  112707. }, function (msg, exception) {
  112708. _this.onErrorCallback(onError, msg, exception);
  112709. });
  112710. };
  112711. /**
  112712. * Execute the current task
  112713. * @param scene defines the scene where you want your assets to be loaded
  112714. * @param onSuccess is a callback called when the task is successfully executed
  112715. * @param onError is a callback called if an error occurs
  112716. */
  112717. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112718. throw new Error("runTask is not implemented");
  112719. };
  112720. /**
  112721. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  112722. * This can be used with failed tasks that have the reason for failure fixed.
  112723. */
  112724. AbstractAssetTask.prototype.reset = function () {
  112725. this._taskState = AssetTaskState.INIT;
  112726. };
  112727. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  112728. this._taskState = AssetTaskState.ERROR;
  112729. this._errorObject = {
  112730. message: message,
  112731. exception: exception
  112732. };
  112733. if (this.onError) {
  112734. this.onError(this, message, exception);
  112735. }
  112736. onError();
  112737. };
  112738. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  112739. try {
  112740. this._taskState = AssetTaskState.DONE;
  112741. this._isCompleted = true;
  112742. if (this.onSuccess) {
  112743. this.onSuccess(this);
  112744. }
  112745. onSuccess();
  112746. }
  112747. catch (e) {
  112748. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  112749. }
  112750. };
  112751. return AbstractAssetTask;
  112752. }());
  112753. BABYLON.AbstractAssetTask = AbstractAssetTask;
  112754. /**
  112755. * Class used to share progress information about assets loading
  112756. */
  112757. var AssetsProgressEvent = /** @class */ (function () {
  112758. /**
  112759. * Creates a AssetsProgressEvent
  112760. * @param remainingCount defines the number of remaining tasks to process
  112761. * @param totalCount defines the total number of tasks
  112762. * @param task defines the task that was just processed
  112763. */
  112764. function AssetsProgressEvent(remainingCount, totalCount, task) {
  112765. this.remainingCount = remainingCount;
  112766. this.totalCount = totalCount;
  112767. this.task = task;
  112768. }
  112769. return AssetsProgressEvent;
  112770. }());
  112771. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  112772. /**
  112773. * Define a task used by AssetsManager to load meshes
  112774. */
  112775. var MeshAssetTask = /** @class */ (function (_super) {
  112776. __extends(MeshAssetTask, _super);
  112777. /**
  112778. * Creates a new MeshAssetTask
  112779. * @param name defines the name of the task
  112780. * @param meshesNames defines the list of mesh's names you want to load
  112781. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  112782. * @param sceneFilename defines the filename of the scene to load from
  112783. */
  112784. function MeshAssetTask(
  112785. /**
  112786. * Defines the name of the task
  112787. */
  112788. name,
  112789. /**
  112790. * Defines the list of mesh's names you want to load
  112791. */
  112792. meshesNames,
  112793. /**
  112794. * Defines the root url to use as a base to load your meshes and associated resources
  112795. */
  112796. rootUrl,
  112797. /**
  112798. * Defines the filename of the scene to load from
  112799. */
  112800. sceneFilename) {
  112801. var _this = _super.call(this, name) || this;
  112802. _this.name = name;
  112803. _this.meshesNames = meshesNames;
  112804. _this.rootUrl = rootUrl;
  112805. _this.sceneFilename = sceneFilename;
  112806. return _this;
  112807. }
  112808. /**
  112809. * Execute the current task
  112810. * @param scene defines the scene where you want your assets to be loaded
  112811. * @param onSuccess is a callback called when the task is successfully executed
  112812. * @param onError is a callback called if an error occurs
  112813. */
  112814. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112815. var _this = this;
  112816. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  112817. _this.loadedMeshes = meshes;
  112818. _this.loadedParticleSystems = particleSystems;
  112819. _this.loadedSkeletons = skeletons;
  112820. onSuccess();
  112821. }, null, function (scene, message, exception) {
  112822. onError(message, exception);
  112823. });
  112824. };
  112825. return MeshAssetTask;
  112826. }(AbstractAssetTask));
  112827. BABYLON.MeshAssetTask = MeshAssetTask;
  112828. /**
  112829. * Define a task used by AssetsManager to load text content
  112830. */
  112831. var TextFileAssetTask = /** @class */ (function (_super) {
  112832. __extends(TextFileAssetTask, _super);
  112833. /**
  112834. * Creates a new TextFileAssetTask object
  112835. * @param name defines the name of the task
  112836. * @param url defines the location of the file to load
  112837. */
  112838. function TextFileAssetTask(
  112839. /**
  112840. * Defines the name of the task
  112841. */
  112842. name,
  112843. /**
  112844. * Defines the location of the file to load
  112845. */
  112846. url) {
  112847. var _this = _super.call(this, name) || this;
  112848. _this.name = name;
  112849. _this.url = url;
  112850. return _this;
  112851. }
  112852. /**
  112853. * Execute the current task
  112854. * @param scene defines the scene where you want your assets to be loaded
  112855. * @param onSuccess is a callback called when the task is successfully executed
  112856. * @param onError is a callback called if an error occurs
  112857. */
  112858. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112859. var _this = this;
  112860. scene._loadFile(this.url, function (data) {
  112861. _this.text = data;
  112862. onSuccess();
  112863. }, undefined, false, false, function (request, exception) {
  112864. if (request) {
  112865. onError(request.status + " " + request.statusText, exception);
  112866. }
  112867. });
  112868. };
  112869. return TextFileAssetTask;
  112870. }(AbstractAssetTask));
  112871. BABYLON.TextFileAssetTask = TextFileAssetTask;
  112872. /**
  112873. * Define a task used by AssetsManager to load binary data
  112874. */
  112875. var BinaryFileAssetTask = /** @class */ (function (_super) {
  112876. __extends(BinaryFileAssetTask, _super);
  112877. /**
  112878. * Creates a new BinaryFileAssetTask object
  112879. * @param name defines the name of the new task
  112880. * @param url defines the location of the file to load
  112881. */
  112882. function BinaryFileAssetTask(
  112883. /**
  112884. * Defines the name of the task
  112885. */
  112886. name,
  112887. /**
  112888. * Defines the location of the file to load
  112889. */
  112890. url) {
  112891. var _this = _super.call(this, name) || this;
  112892. _this.name = name;
  112893. _this.url = url;
  112894. return _this;
  112895. }
  112896. /**
  112897. * Execute the current task
  112898. * @param scene defines the scene where you want your assets to be loaded
  112899. * @param onSuccess is a callback called when the task is successfully executed
  112900. * @param onError is a callback called if an error occurs
  112901. */
  112902. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112903. var _this = this;
  112904. scene._loadFile(this.url, function (data) {
  112905. _this.data = data;
  112906. onSuccess();
  112907. }, undefined, true, true, function (request, exception) {
  112908. if (request) {
  112909. onError(request.status + " " + request.statusText, exception);
  112910. }
  112911. });
  112912. };
  112913. return BinaryFileAssetTask;
  112914. }(AbstractAssetTask));
  112915. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  112916. /**
  112917. * Define a task used by AssetsManager to load images
  112918. */
  112919. var ImageAssetTask = /** @class */ (function (_super) {
  112920. __extends(ImageAssetTask, _super);
  112921. /**
  112922. * Creates a new ImageAssetTask
  112923. * @param name defines the name of the task
  112924. * @param url defines the location of the image to load
  112925. */
  112926. function ImageAssetTask(
  112927. /**
  112928. * Defines the name of the task
  112929. */
  112930. name,
  112931. /**
  112932. * Defines the location of the image to load
  112933. */
  112934. url) {
  112935. var _this = _super.call(this, name) || this;
  112936. _this.name = name;
  112937. _this.url = url;
  112938. return _this;
  112939. }
  112940. /**
  112941. * Execute the current task
  112942. * @param scene defines the scene where you want your assets to be loaded
  112943. * @param onSuccess is a callback called when the task is successfully executed
  112944. * @param onError is a callback called if an error occurs
  112945. */
  112946. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112947. var _this = this;
  112948. var img = new Image();
  112949. BABYLON.Tools.SetCorsBehavior(this.url, img);
  112950. img.onload = function () {
  112951. _this.image = img;
  112952. onSuccess();
  112953. };
  112954. img.onerror = function (err) {
  112955. onError("Error loading image", err);
  112956. };
  112957. img.src = this.url;
  112958. };
  112959. return ImageAssetTask;
  112960. }(AbstractAssetTask));
  112961. BABYLON.ImageAssetTask = ImageAssetTask;
  112962. /**
  112963. * Define a task used by AssetsManager to load 2D textures
  112964. */
  112965. var TextureAssetTask = /** @class */ (function (_super) {
  112966. __extends(TextureAssetTask, _super);
  112967. /**
  112968. * Creates a new TextureAssetTask object
  112969. * @param name defines the name of the task
  112970. * @param url defines the location of the file to load
  112971. * @param noMipmap defines if mipmap should not be generated (default is false)
  112972. * @param invertY defines if texture must be inverted on Y axis (default is false)
  112973. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  112974. */
  112975. function TextureAssetTask(
  112976. /**
  112977. * Defines the name of the task
  112978. */
  112979. name,
  112980. /**
  112981. * Defines the location of the file to load
  112982. */
  112983. url,
  112984. /**
  112985. * Defines if mipmap should not be generated (default is false)
  112986. */
  112987. noMipmap,
  112988. /**
  112989. * Defines if texture must be inverted on Y axis (default is false)
  112990. */
  112991. invertY,
  112992. /**
  112993. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  112994. */
  112995. samplingMode) {
  112996. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  112997. var _this = _super.call(this, name) || this;
  112998. _this.name = name;
  112999. _this.url = url;
  113000. _this.noMipmap = noMipmap;
  113001. _this.invertY = invertY;
  113002. _this.samplingMode = samplingMode;
  113003. return _this;
  113004. }
  113005. /**
  113006. * Execute the current task
  113007. * @param scene defines the scene where you want your assets to be loaded
  113008. * @param onSuccess is a callback called when the task is successfully executed
  113009. * @param onError is a callback called if an error occurs
  113010. */
  113011. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113012. var onload = function () {
  113013. onSuccess();
  113014. };
  113015. var onerror = function (message, exception) {
  113016. onError(message, exception);
  113017. };
  113018. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  113019. };
  113020. return TextureAssetTask;
  113021. }(AbstractAssetTask));
  113022. BABYLON.TextureAssetTask = TextureAssetTask;
  113023. /**
  113024. * Define a task used by AssetsManager to load cube textures
  113025. */
  113026. var CubeTextureAssetTask = /** @class */ (function (_super) {
  113027. __extends(CubeTextureAssetTask, _super);
  113028. /**
  113029. * Creates a new CubeTextureAssetTask
  113030. * @param name defines the name of the task
  113031. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  113032. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  113033. * @param noMipmap defines if mipmaps should not be generated (default is false)
  113034. * @param files defines the explicit list of files (undefined by default)
  113035. */
  113036. function CubeTextureAssetTask(
  113037. /**
  113038. * Defines the name of the task
  113039. */
  113040. name,
  113041. /**
  113042. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  113043. */
  113044. url,
  113045. /**
  113046. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  113047. */
  113048. extensions,
  113049. /**
  113050. * Defines if mipmaps should not be generated (default is false)
  113051. */
  113052. noMipmap,
  113053. /**
  113054. * Defines the explicit list of files (undefined by default)
  113055. */
  113056. files) {
  113057. var _this = _super.call(this, name) || this;
  113058. _this.name = name;
  113059. _this.url = url;
  113060. _this.extensions = extensions;
  113061. _this.noMipmap = noMipmap;
  113062. _this.files = files;
  113063. return _this;
  113064. }
  113065. /**
  113066. * Execute the current task
  113067. * @param scene defines the scene where you want your assets to be loaded
  113068. * @param onSuccess is a callback called when the task is successfully executed
  113069. * @param onError is a callback called if an error occurs
  113070. */
  113071. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113072. var onload = function () {
  113073. onSuccess();
  113074. };
  113075. var onerror = function (message, exception) {
  113076. onError(message, exception);
  113077. };
  113078. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  113079. };
  113080. return CubeTextureAssetTask;
  113081. }(AbstractAssetTask));
  113082. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  113083. /**
  113084. * Define a task used by AssetsManager to load HDR cube textures
  113085. */
  113086. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  113087. __extends(HDRCubeTextureAssetTask, _super);
  113088. /**
  113089. * Creates a new HDRCubeTextureAssetTask object
  113090. * @param name defines the name of the task
  113091. * @param url defines the location of the file to load
  113092. * @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.
  113093. * @param noMipmap defines if mipmaps should not be generated (default is false)
  113094. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  113095. * @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)
  113096. * @param reserved Internal use only
  113097. */
  113098. function HDRCubeTextureAssetTask(
  113099. /**
  113100. * Defines the name of the task
  113101. */
  113102. name,
  113103. /**
  113104. * Defines the location of the file to load
  113105. */
  113106. url,
  113107. /**
  113108. * Defines the desired size (the more it increases the longer the generation will be)
  113109. */
  113110. size,
  113111. /**
  113112. * Defines if mipmaps should not be generated (default is false)
  113113. */
  113114. noMipmap,
  113115. /**
  113116. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  113117. */
  113118. generateHarmonics,
  113119. /**
  113120. * 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)
  113121. */
  113122. gammaSpace,
  113123. /**
  113124. * Internal Use Only
  113125. */
  113126. reserved) {
  113127. if (noMipmap === void 0) { noMipmap = false; }
  113128. if (generateHarmonics === void 0) { generateHarmonics = true; }
  113129. if (gammaSpace === void 0) { gammaSpace = false; }
  113130. if (reserved === void 0) { reserved = false; }
  113131. var _this = _super.call(this, name) || this;
  113132. _this.name = name;
  113133. _this.url = url;
  113134. _this.size = size;
  113135. _this.noMipmap = noMipmap;
  113136. _this.generateHarmonics = generateHarmonics;
  113137. _this.gammaSpace = gammaSpace;
  113138. _this.reserved = reserved;
  113139. return _this;
  113140. }
  113141. /**
  113142. * Execute the current task
  113143. * @param scene defines the scene where you want your assets to be loaded
  113144. * @param onSuccess is a callback called when the task is successfully executed
  113145. * @param onError is a callback called if an error occurs
  113146. */
  113147. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  113148. var onload = function () {
  113149. onSuccess();
  113150. };
  113151. var onerror = function (message, exception) {
  113152. onError(message, exception);
  113153. };
  113154. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  113155. };
  113156. return HDRCubeTextureAssetTask;
  113157. }(AbstractAssetTask));
  113158. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  113159. /**
  113160. * This class can be used to easily import assets into a scene
  113161. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  113162. */
  113163. var AssetsManager = /** @class */ (function () {
  113164. /**
  113165. * Creates a new AssetsManager
  113166. * @param scene defines the scene to work on
  113167. */
  113168. function AssetsManager(scene) {
  113169. this._isLoading = false;
  113170. this._tasks = new Array();
  113171. this._waitingTasksCount = 0;
  113172. this._totalTasksCount = 0;
  113173. /**
  113174. * Observable called when all tasks are processed
  113175. */
  113176. this.onTaskSuccessObservable = new BABYLON.Observable();
  113177. /**
  113178. * Observable called when a task had an error
  113179. */
  113180. this.onTaskErrorObservable = new BABYLON.Observable();
  113181. /**
  113182. * Observable called when a task is successful
  113183. */
  113184. this.onTasksDoneObservable = new BABYLON.Observable();
  113185. /**
  113186. * Observable called when a task is done (whatever the result is)
  113187. */
  113188. this.onProgressObservable = new BABYLON.Observable();
  113189. /**
  113190. * Gets or sets a boolean defining if the AssetsManager should use the default loading screen
  113191. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  113192. */
  113193. this.useDefaultLoadingScreen = true;
  113194. this._scene = scene;
  113195. }
  113196. /**
  113197. * Add a MeshAssetTask to the list of active tasks
  113198. * @param taskName defines the name of the new task
  113199. * @param meshesNames defines the name of meshes to load
  113200. * @param rootUrl defines the root url to use to locate files
  113201. * @param sceneFilename defines the filename of the scene file
  113202. * @returns a new MeshAssetTask object
  113203. */
  113204. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  113205. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  113206. this._tasks.push(task);
  113207. return task;
  113208. };
  113209. /**
  113210. * Add a TextFileAssetTask to the list of active tasks
  113211. * @param taskName defines the name of the new task
  113212. * @param url defines the url of the file to load
  113213. * @returns a new TextFileAssetTask object
  113214. */
  113215. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  113216. var task = new TextFileAssetTask(taskName, url);
  113217. this._tasks.push(task);
  113218. return task;
  113219. };
  113220. /**
  113221. * Add a BinaryFileAssetTask to the list of active tasks
  113222. * @param taskName defines the name of the new task
  113223. * @param url defines the url of the file to load
  113224. * @returns a new BinaryFileAssetTask object
  113225. */
  113226. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  113227. var task = new BinaryFileAssetTask(taskName, url);
  113228. this._tasks.push(task);
  113229. return task;
  113230. };
  113231. /**
  113232. * Add a ImageAssetTask to the list of active tasks
  113233. * @param taskName defines the name of the new task
  113234. * @param url defines the url of the file to load
  113235. * @returns a new ImageAssetTask object
  113236. */
  113237. AssetsManager.prototype.addImageTask = function (taskName, url) {
  113238. var task = new ImageAssetTask(taskName, url);
  113239. this._tasks.push(task);
  113240. return task;
  113241. };
  113242. /**
  113243. * Add a TextureAssetTask to the list of active tasks
  113244. * @param taskName defines the name of the new task
  113245. * @param url defines the url of the file to load
  113246. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  113247. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  113248. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  113249. * @returns a new TextureAssetTask object
  113250. */
  113251. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  113252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  113253. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  113254. this._tasks.push(task);
  113255. return task;
  113256. };
  113257. /**
  113258. * Add a CubeTextureAssetTask to the list of active tasks
  113259. * @param taskName defines the name of the new task
  113260. * @param url defines the url of the file to load
  113261. * @param extensions defines the extension to use to load the cube map (can be null)
  113262. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  113263. * @param files defines the list of files to load (can be null)
  113264. * @returns a new CubeTextureAssetTask object
  113265. */
  113266. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  113267. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  113268. this._tasks.push(task);
  113269. return task;
  113270. };
  113271. /**
  113272. *
  113273. * Add a HDRCubeTextureAssetTask to the list of active tasks
  113274. * @param taskName defines the name of the new task
  113275. * @param url defines the url of the file to load
  113276. * @param size defines the size you want for the cubemap (can be null)
  113277. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  113278. * @param generateHarmonics defines if you want to automatically generate (true by default)
  113279. * @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)
  113280. * @param reserved Internal use only
  113281. * @returns a new HDRCubeTextureAssetTask object
  113282. */
  113283. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  113284. if (noMipmap === void 0) { noMipmap = false; }
  113285. if (generateHarmonics === void 0) { generateHarmonics = true; }
  113286. if (gammaSpace === void 0) { gammaSpace = false; }
  113287. if (reserved === void 0) { reserved = false; }
  113288. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  113289. this._tasks.push(task);
  113290. return task;
  113291. };
  113292. /**
  113293. * Remove a task from the assets manager.
  113294. * @param task the task to remove
  113295. */
  113296. AssetsManager.prototype.removeTask = function (task) {
  113297. var index = this._tasks.indexOf(task);
  113298. if (index > -1) {
  113299. this._tasks.splice(index, 1);
  113300. }
  113301. };
  113302. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  113303. this._waitingTasksCount--;
  113304. try {
  113305. if (this.onProgress) {
  113306. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  113307. }
  113308. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  113309. }
  113310. catch (e) {
  113311. BABYLON.Tools.Error("Error running progress callbacks.");
  113312. console.log(e);
  113313. }
  113314. if (this._waitingTasksCount === 0) {
  113315. try {
  113316. if (this.onFinish) {
  113317. this.onFinish(this._tasks);
  113318. }
  113319. // Let's remove successfull tasks
  113320. var currentTasks = this._tasks.slice();
  113321. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  113322. var task = currentTasks_1[_i];
  113323. if (task.taskState === AssetTaskState.DONE) {
  113324. var index = this._tasks.indexOf(task);
  113325. if (index > -1) {
  113326. this._tasks.splice(index, 1);
  113327. }
  113328. }
  113329. }
  113330. this.onTasksDoneObservable.notifyObservers(this._tasks);
  113331. }
  113332. catch (e) {
  113333. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  113334. console.log(e);
  113335. }
  113336. this._isLoading = false;
  113337. this._scene.getEngine().hideLoadingUI();
  113338. }
  113339. };
  113340. AssetsManager.prototype._runTask = function (task) {
  113341. var _this = this;
  113342. var done = function () {
  113343. try {
  113344. if (_this.onTaskSuccess) {
  113345. _this.onTaskSuccess(task);
  113346. }
  113347. _this.onTaskSuccessObservable.notifyObservers(task);
  113348. _this._decreaseWaitingTasksCount(task);
  113349. }
  113350. catch (e) {
  113351. error("Error executing task success callbacks", e);
  113352. }
  113353. };
  113354. var error = function (message, exception) {
  113355. task._setErrorObject(message, exception);
  113356. if (_this.onTaskError) {
  113357. _this.onTaskError(task);
  113358. }
  113359. _this.onTaskErrorObservable.notifyObservers(task);
  113360. _this._decreaseWaitingTasksCount(task);
  113361. };
  113362. task.run(this._scene, done, error);
  113363. };
  113364. /**
  113365. * Reset the AssetsManager and remove all tasks
  113366. * @return the current instance of the AssetsManager
  113367. */
  113368. AssetsManager.prototype.reset = function () {
  113369. this._isLoading = false;
  113370. this._tasks = new Array();
  113371. return this;
  113372. };
  113373. /**
  113374. * Start the loading process
  113375. * @return the current instance of the AssetsManager
  113376. */
  113377. AssetsManager.prototype.load = function () {
  113378. if (this._isLoading) {
  113379. return this;
  113380. }
  113381. this._isLoading = true;
  113382. this._waitingTasksCount = this._tasks.length;
  113383. this._totalTasksCount = this._tasks.length;
  113384. if (this._waitingTasksCount === 0) {
  113385. this._isLoading = false;
  113386. if (this.onFinish) {
  113387. this.onFinish(this._tasks);
  113388. }
  113389. this.onTasksDoneObservable.notifyObservers(this._tasks);
  113390. return this;
  113391. }
  113392. if (this.useDefaultLoadingScreen) {
  113393. this._scene.getEngine().displayLoadingUI();
  113394. }
  113395. for (var index = 0; index < this._tasks.length; index++) {
  113396. var task = this._tasks[index];
  113397. if (task.taskState === AssetTaskState.INIT) {
  113398. this._runTask(task);
  113399. }
  113400. }
  113401. return this;
  113402. };
  113403. return AssetsManager;
  113404. }());
  113405. BABYLON.AssetsManager = AssetsManager;
  113406. })(BABYLON || (BABYLON = {}));
  113407. //# sourceMappingURL=babylon.assetsManager.js.map
  113408. var BABYLON;
  113409. (function (BABYLON) {
  113410. var serializedGeometries = [];
  113411. var serializeGeometry = function (geometry, serializationGeometries) {
  113412. if (serializedGeometries[geometry.id]) {
  113413. return;
  113414. }
  113415. if (geometry.doNotSerialize) {
  113416. return;
  113417. }
  113418. if (geometry instanceof BABYLON.BoxGeometry) {
  113419. serializationGeometries.boxes.push(geometry.serialize());
  113420. }
  113421. else if (geometry instanceof BABYLON.SphereGeometry) {
  113422. serializationGeometries.spheres.push(geometry.serialize());
  113423. }
  113424. else if (geometry instanceof BABYLON.CylinderGeometry) {
  113425. serializationGeometries.cylinders.push(geometry.serialize());
  113426. }
  113427. else if (geometry instanceof BABYLON.TorusGeometry) {
  113428. serializationGeometries.toruses.push(geometry.serialize());
  113429. }
  113430. else if (geometry instanceof BABYLON.GroundGeometry) {
  113431. serializationGeometries.grounds.push(geometry.serialize());
  113432. }
  113433. else if (geometry instanceof BABYLON.Plane) {
  113434. serializationGeometries.planes.push(geometry.serialize());
  113435. }
  113436. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  113437. serializationGeometries.torusKnots.push(geometry.serialize());
  113438. }
  113439. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  113440. throw new Error("Unknown primitive type");
  113441. }
  113442. else {
  113443. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  113444. }
  113445. serializedGeometries[geometry.id] = true;
  113446. };
  113447. var serializeMesh = function (mesh, serializationScene) {
  113448. var serializationObject = {};
  113449. // Geometry
  113450. var geometry = mesh._geometry;
  113451. if (geometry) {
  113452. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  113453. // 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
  113454. serializeGeometry(geometry, serializationScene.geometries);
  113455. }
  113456. }
  113457. // Custom
  113458. if (mesh.serialize) {
  113459. mesh.serialize(serializationObject);
  113460. }
  113461. return serializationObject;
  113462. };
  113463. var finalizeSingleMesh = function (mesh, serializationObject) {
  113464. //only works if the mesh is already loaded
  113465. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  113466. //serialize material
  113467. if (mesh.material) {
  113468. if (mesh.material instanceof BABYLON.MultiMaterial) {
  113469. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  113470. serializationObject.materials = serializationObject.materials || [];
  113471. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  113472. serializationObject.multiMaterials.push(mesh.material.serialize());
  113473. var _loop_1 = function (submaterial) {
  113474. if (submaterial) {
  113475. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  113476. serializationObject.materials.push(submaterial.serialize());
  113477. }
  113478. }
  113479. };
  113480. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  113481. var submaterial = _a[_i];
  113482. _loop_1(submaterial);
  113483. }
  113484. }
  113485. }
  113486. else {
  113487. serializationObject.materials = serializationObject.materials || [];
  113488. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  113489. serializationObject.materials.push(mesh.material.serialize());
  113490. }
  113491. }
  113492. }
  113493. //serialize geometry
  113494. var geometry = mesh._geometry;
  113495. if (geometry) {
  113496. if (!serializationObject.geometries) {
  113497. serializationObject.geometries = {};
  113498. serializationObject.geometries.boxes = [];
  113499. serializationObject.geometries.spheres = [];
  113500. serializationObject.geometries.cylinders = [];
  113501. serializationObject.geometries.toruses = [];
  113502. serializationObject.geometries.grounds = [];
  113503. serializationObject.geometries.planes = [];
  113504. serializationObject.geometries.torusKnots = [];
  113505. serializationObject.geometries.vertexData = [];
  113506. }
  113507. serializeGeometry(geometry, serializationObject.geometries);
  113508. }
  113509. // Skeletons
  113510. if (mesh.skeleton) {
  113511. serializationObject.skeletons = serializationObject.skeletons || [];
  113512. serializationObject.skeletons.push(mesh.skeleton.serialize());
  113513. }
  113514. //serialize the actual mesh
  113515. serializationObject.meshes = serializationObject.meshes || [];
  113516. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  113517. }
  113518. };
  113519. /**
  113520. * Class used to serialize a scene into a string
  113521. */
  113522. var SceneSerializer = /** @class */ (function () {
  113523. function SceneSerializer() {
  113524. }
  113525. /**
  113526. * Clear cache used by a previous serialization
  113527. */
  113528. SceneSerializer.ClearCache = function () {
  113529. serializedGeometries = [];
  113530. };
  113531. /**
  113532. * Serialize a scene into a JSON compatible object
  113533. * @param scene defines the scene to serialize
  113534. * @returns a JSON compatible object
  113535. */
  113536. SceneSerializer.Serialize = function (scene) {
  113537. var serializationObject = {};
  113538. SceneSerializer.ClearCache();
  113539. // Scene
  113540. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  113541. serializationObject.autoClear = scene.autoClear;
  113542. serializationObject.clearColor = scene.clearColor.asArray();
  113543. serializationObject.ambientColor = scene.ambientColor.asArray();
  113544. serializationObject.gravity = scene.gravity.asArray();
  113545. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  113546. serializationObject.workerCollisions = scene.workerCollisions;
  113547. // Fog
  113548. if (scene.fogMode && scene.fogMode !== 0) {
  113549. serializationObject.fogMode = scene.fogMode;
  113550. serializationObject.fogColor = scene.fogColor.asArray();
  113551. serializationObject.fogStart = scene.fogStart;
  113552. serializationObject.fogEnd = scene.fogEnd;
  113553. serializationObject.fogDensity = scene.fogDensity;
  113554. }
  113555. //Physics
  113556. if (scene.isPhysicsEnabled()) {
  113557. var physicEngine = scene.getPhysicsEngine();
  113558. if (physicEngine) {
  113559. serializationObject.physicsEnabled = true;
  113560. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  113561. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  113562. }
  113563. }
  113564. // Metadata
  113565. if (scene.metadata) {
  113566. serializationObject.metadata = scene.metadata;
  113567. }
  113568. // Morph targets
  113569. serializationObject.morphTargetManagers = [];
  113570. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  113571. var abstractMesh = _a[_i];
  113572. var manager = abstractMesh.morphTargetManager;
  113573. if (manager) {
  113574. serializationObject.morphTargetManagers.push(manager.serialize());
  113575. }
  113576. }
  113577. // Lights
  113578. serializationObject.lights = [];
  113579. var index;
  113580. var light;
  113581. for (index = 0; index < scene.lights.length; index++) {
  113582. light = scene.lights[index];
  113583. if (!light.doNotSerialize) {
  113584. serializationObject.lights.push(light.serialize());
  113585. }
  113586. }
  113587. // Cameras
  113588. serializationObject.cameras = [];
  113589. for (index = 0; index < scene.cameras.length; index++) {
  113590. var camera = scene.cameras[index];
  113591. if (!camera.doNotSerialize) {
  113592. serializationObject.cameras.push(camera.serialize());
  113593. }
  113594. }
  113595. if (scene.activeCamera) {
  113596. serializationObject.activeCameraID = scene.activeCamera.id;
  113597. }
  113598. // Animations
  113599. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  113600. // Materials
  113601. serializationObject.materials = [];
  113602. serializationObject.multiMaterials = [];
  113603. var material;
  113604. for (index = 0; index < scene.materials.length; index++) {
  113605. material = scene.materials[index];
  113606. if (!material.doNotSerialize) {
  113607. serializationObject.materials.push(material.serialize());
  113608. }
  113609. }
  113610. // MultiMaterials
  113611. serializationObject.multiMaterials = [];
  113612. for (index = 0; index < scene.multiMaterials.length; index++) {
  113613. var multiMaterial = scene.multiMaterials[index];
  113614. serializationObject.multiMaterials.push(multiMaterial.serialize());
  113615. }
  113616. // Environment texture
  113617. if (scene.environmentTexture) {
  113618. serializationObject.environmentTexture = scene.environmentTexture.name;
  113619. }
  113620. // Skeletons
  113621. serializationObject.skeletons = [];
  113622. for (index = 0; index < scene.skeletons.length; index++) {
  113623. var skeleton = scene.skeletons[index];
  113624. if (!skeleton.doNotSerialize) {
  113625. serializationObject.skeletons.push(skeleton.serialize());
  113626. }
  113627. }
  113628. // Transform nodes
  113629. serializationObject.transformNodes = [];
  113630. for (index = 0; index < scene.transformNodes.length; index++) {
  113631. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  113632. }
  113633. // Geometries
  113634. serializationObject.geometries = {};
  113635. serializationObject.geometries.boxes = [];
  113636. serializationObject.geometries.spheres = [];
  113637. serializationObject.geometries.cylinders = [];
  113638. serializationObject.geometries.toruses = [];
  113639. serializationObject.geometries.grounds = [];
  113640. serializationObject.geometries.planes = [];
  113641. serializationObject.geometries.torusKnots = [];
  113642. serializationObject.geometries.vertexData = [];
  113643. serializedGeometries = [];
  113644. var geometries = scene.getGeometries();
  113645. for (index = 0; index < geometries.length; index++) {
  113646. var geometry = geometries[index];
  113647. if (geometry.isReady()) {
  113648. serializeGeometry(geometry, serializationObject.geometries);
  113649. }
  113650. }
  113651. // Meshes
  113652. serializationObject.meshes = [];
  113653. for (index = 0; index < scene.meshes.length; index++) {
  113654. var abstractMesh = scene.meshes[index];
  113655. if (abstractMesh instanceof BABYLON.Mesh) {
  113656. var mesh = abstractMesh;
  113657. if (!mesh.doNotSerialize) {
  113658. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  113659. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  113660. }
  113661. }
  113662. }
  113663. }
  113664. // Particles Systems
  113665. serializationObject.particleSystems = [];
  113666. for (index = 0; index < scene.particleSystems.length; index++) {
  113667. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  113668. }
  113669. // Action Manager
  113670. if (scene.actionManager) {
  113671. serializationObject.actions = scene.actionManager.serialize("scene");
  113672. }
  113673. // Components
  113674. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  113675. var component = _c[_b];
  113676. component.serialize(serializationObject);
  113677. }
  113678. return serializationObject;
  113679. };
  113680. /**
  113681. * Serialize a mesh into a JSON compatible object
  113682. * @param toSerialize defines the mesh to serialize
  113683. * @param withParents defines if parents must be serialized as well
  113684. * @param withChildren defines if children must be serialized as well
  113685. * @returns a JSON compatible object
  113686. */
  113687. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  113688. if (withParents === void 0) { withParents = false; }
  113689. if (withChildren === void 0) { withChildren = false; }
  113690. var serializationObject = {};
  113691. SceneSerializer.ClearCache();
  113692. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  113693. if (withParents || withChildren) {
  113694. //deliberate for loop! not for each, appended should be processed as well.
  113695. for (var i = 0; i < toSerialize.length; ++i) {
  113696. if (withChildren) {
  113697. toSerialize[i].getDescendants().forEach(function (node) {
  113698. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  113699. toSerialize.push(node);
  113700. }
  113701. });
  113702. }
  113703. //make sure the array doesn't contain the object already
  113704. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  113705. toSerialize.push(toSerialize[i].parent);
  113706. }
  113707. }
  113708. }
  113709. toSerialize.forEach(function (mesh) {
  113710. finalizeSingleMesh(mesh, serializationObject);
  113711. });
  113712. return serializationObject;
  113713. };
  113714. return SceneSerializer;
  113715. }());
  113716. BABYLON.SceneSerializer = SceneSerializer;
  113717. })(BABYLON || (BABYLON = {}));
  113718. //# sourceMappingURL=babylon.sceneSerializer.js.map
  113719. var BABYLON;
  113720. (function (BABYLON) {
  113721. /**
  113722. * Class used to generate realtime reflection / refraction cube textures
  113723. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  113724. */
  113725. var ReflectionProbe = /** @class */ (function () {
  113726. /**
  113727. * Creates a new reflection probe
  113728. * @param name defines the name of the probe
  113729. * @param size defines the texture resolution (for each face)
  113730. * @param scene defines the hosting scene
  113731. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  113732. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  113733. */
  113734. function ReflectionProbe(
  113735. /** defines the name of the probe */
  113736. name, size, scene, generateMipMaps, useFloat) {
  113737. if (generateMipMaps === void 0) { generateMipMaps = true; }
  113738. if (useFloat === void 0) { useFloat = false; }
  113739. var _this = this;
  113740. this.name = name;
  113741. this._viewMatrix = BABYLON.Matrix.Identity();
  113742. this._target = BABYLON.Vector3.Zero();
  113743. this._add = BABYLON.Vector3.Zero();
  113744. this._invertYAxis = false;
  113745. /** Gets or sets probe position (center of the cube map) */
  113746. this.position = BABYLON.Vector3.Zero();
  113747. this._scene = scene;
  113748. // Create the scene field if not exist.
  113749. if (!this._scene.reflectionProbes) {
  113750. this._scene.reflectionProbes = new Array();
  113751. }
  113752. this._scene.reflectionProbes.push(this);
  113753. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  113754. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  113755. switch (faceIndex) {
  113756. case 0:
  113757. _this._add.copyFromFloats(1, 0, 0);
  113758. break;
  113759. case 1:
  113760. _this._add.copyFromFloats(-1, 0, 0);
  113761. break;
  113762. case 2:
  113763. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  113764. break;
  113765. case 3:
  113766. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  113767. break;
  113768. case 4:
  113769. _this._add.copyFromFloats(0, 0, 1);
  113770. break;
  113771. case 5:
  113772. _this._add.copyFromFloats(0, 0, -1);
  113773. break;
  113774. }
  113775. if (_this._attachedMesh) {
  113776. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  113777. }
  113778. _this.position.addToRef(_this._add, _this._target);
  113779. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  113780. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  113781. scene._forcedViewPosition = _this.position;
  113782. });
  113783. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  113784. scene._forcedViewPosition = null;
  113785. scene.updateTransformMatrix(true);
  113786. });
  113787. if (scene.activeCamera) {
  113788. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  113789. }
  113790. }
  113791. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  113792. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  113793. get: function () {
  113794. return this._renderTargetTexture.samples;
  113795. },
  113796. set: function (value) {
  113797. this._renderTargetTexture.samples = value;
  113798. },
  113799. enumerable: true,
  113800. configurable: true
  113801. });
  113802. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  113803. /** Gets or sets the refresh rate to use (on every frame by default) */
  113804. get: function () {
  113805. return this._renderTargetTexture.refreshRate;
  113806. },
  113807. set: function (value) {
  113808. this._renderTargetTexture.refreshRate = value;
  113809. },
  113810. enumerable: true,
  113811. configurable: true
  113812. });
  113813. /**
  113814. * Gets the hosting scene
  113815. * @returns a Scene
  113816. */
  113817. ReflectionProbe.prototype.getScene = function () {
  113818. return this._scene;
  113819. };
  113820. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  113821. /** Gets the internal CubeTexture used to render to */
  113822. get: function () {
  113823. return this._renderTargetTexture;
  113824. },
  113825. enumerable: true,
  113826. configurable: true
  113827. });
  113828. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  113829. /** Gets the list of meshes to render */
  113830. get: function () {
  113831. return this._renderTargetTexture.renderList;
  113832. },
  113833. enumerable: true,
  113834. configurable: true
  113835. });
  113836. /**
  113837. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  113838. * @param mesh defines the mesh to attach to
  113839. */
  113840. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  113841. this._attachedMesh = mesh;
  113842. };
  113843. /**
  113844. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  113845. * @param renderingGroupId The rendering group id corresponding to its index
  113846. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  113847. */
  113848. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  113849. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  113850. };
  113851. /**
  113852. * Clean all associated resources
  113853. */
  113854. ReflectionProbe.prototype.dispose = function () {
  113855. var index = this._scene.reflectionProbes.indexOf(this);
  113856. if (index !== -1) {
  113857. // Remove from the scene if found
  113858. this._scene.reflectionProbes.splice(index, 1);
  113859. }
  113860. if (this._renderTargetTexture) {
  113861. this._renderTargetTexture.dispose();
  113862. this._renderTargetTexture = null;
  113863. }
  113864. };
  113865. return ReflectionProbe;
  113866. }());
  113867. BABYLON.ReflectionProbe = ReflectionProbe;
  113868. })(BABYLON || (BABYLON = {}));
  113869. //# sourceMappingURL=babylon.reflectionProbe.js.map
  113870. var BABYLON;
  113871. (function (BABYLON) {
  113872. /**
  113873. * Defines the layer scene component responsible to manage any layers
  113874. * in a given scene.
  113875. */
  113876. var LayerSceneComponent = /** @class */ (function () {
  113877. /**
  113878. * Creates a new instance of the component for the given scene
  113879. * @param scene Defines the scene to register the component in
  113880. */
  113881. function LayerSceneComponent(scene) {
  113882. /**
  113883. * The component name helpfull to identify the component in the list of scene components.
  113884. */
  113885. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  113886. this.scene = scene;
  113887. this._engine = scene.getEngine();
  113888. scene.layers = new Array();
  113889. }
  113890. /**
  113891. * Registers the component in a given scene
  113892. */
  113893. LayerSceneComponent.prototype.register = function () {
  113894. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  113895. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  113896. };
  113897. /**
  113898. * Rebuilds the elements related to this component in case of
  113899. * context lost for instance.
  113900. */
  113901. LayerSceneComponent.prototype.rebuild = function () {
  113902. var layers = this.scene.layers;
  113903. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  113904. var layer = layers_1[_i];
  113905. layer._rebuild();
  113906. }
  113907. };
  113908. /**
  113909. * Disposes the component and the associated ressources.
  113910. */
  113911. LayerSceneComponent.prototype.dispose = function () {
  113912. var layers = this.scene.layers;
  113913. while (layers.length) {
  113914. layers[0].dispose();
  113915. }
  113916. };
  113917. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  113918. var layers = this.scene.layers;
  113919. if (layers.length) {
  113920. this._engine.setDepthBuffer(false);
  113921. var cameraLayerMask = camera.layerMask;
  113922. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  113923. var layer = layers_2[_i];
  113924. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  113925. layer.render();
  113926. }
  113927. }
  113928. this._engine.setDepthBuffer(true);
  113929. }
  113930. };
  113931. LayerSceneComponent.prototype._drawBackground = function (camera) {
  113932. this._draw(camera, true);
  113933. };
  113934. LayerSceneComponent.prototype._drawForeground = function (camera) {
  113935. this._draw(camera, false);
  113936. };
  113937. return LayerSceneComponent;
  113938. }());
  113939. BABYLON.LayerSceneComponent = LayerSceneComponent;
  113940. })(BABYLON || (BABYLON = {}));
  113941. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  113942. var BABYLON;
  113943. (function (BABYLON) {
  113944. /**
  113945. * This represents a full screen 2d layer.
  113946. * This can be usefull to display a picture in the background of your scene for instance.
  113947. * @see https://www.babylonjs-playground.com/#08A2BS#1
  113948. */
  113949. var Layer = /** @class */ (function () {
  113950. /**
  113951. * Instantiates a new layer.
  113952. * This represents a full screen 2d layer.
  113953. * This can be usefull to display a picture in the background of your scene for instance.
  113954. * @see https://www.babylonjs-playground.com/#08A2BS#1
  113955. * @param name Define the name of the layer in the scene
  113956. * @param imgUrl Define the url of the texture to display in the layer
  113957. * @param scene Define the scene the layer belongs to
  113958. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  113959. * @param color Defines a color for the layer
  113960. */
  113961. function Layer(
  113962. /**
  113963. * Define the name of the layer.
  113964. */
  113965. name, imgUrl, scene, isBackground, color) {
  113966. this.name = name;
  113967. /**
  113968. * Define the scale of the layer in order to zoom in out of the texture.
  113969. */
  113970. this.scale = new BABYLON.Vector2(1, 1);
  113971. /**
  113972. * Define an offset for the layer in order to shift the texture.
  113973. */
  113974. this.offset = new BABYLON.Vector2(0, 0);
  113975. /**
  113976. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  113977. */
  113978. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  113979. /**
  113980. * Define a mask to restrict the layer to only some of the scene cameras.
  113981. */
  113982. this.layerMask = 0x0FFFFFFF;
  113983. this._vertexBuffers = {};
  113984. /**
  113985. * An event triggered when the layer is disposed.
  113986. */
  113987. this.onDisposeObservable = new BABYLON.Observable();
  113988. /**
  113989. * An event triggered before rendering the scene
  113990. */
  113991. this.onBeforeRenderObservable = new BABYLON.Observable();
  113992. /**
  113993. * An event triggered after rendering the scene
  113994. */
  113995. this.onAfterRenderObservable = new BABYLON.Observable();
  113996. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  113997. this.isBackground = isBackground === undefined ? true : isBackground;
  113998. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  113999. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  114000. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  114001. if (!layerComponent) {
  114002. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  114003. this._scene._addComponent(layerComponent);
  114004. }
  114005. this._scene.layers.push(this);
  114006. var engine = this._scene.getEngine();
  114007. // VBO
  114008. var vertices = [];
  114009. vertices.push(1, 1);
  114010. vertices.push(-1, 1);
  114011. vertices.push(-1, -1);
  114012. vertices.push(1, -1);
  114013. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  114014. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  114015. this._createIndexBuffer();
  114016. // Effects
  114017. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  114018. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  114019. }
  114020. Object.defineProperty(Layer.prototype, "onDispose", {
  114021. /**
  114022. * Back compatibility with callback before the onDisposeObservable existed.
  114023. * The set callback will be triggered when the layer has been disposed.
  114024. */
  114025. set: function (callback) {
  114026. if (this._onDisposeObserver) {
  114027. this.onDisposeObservable.remove(this._onDisposeObserver);
  114028. }
  114029. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  114030. },
  114031. enumerable: true,
  114032. configurable: true
  114033. });
  114034. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  114035. /**
  114036. * Back compatibility with callback before the onBeforeRenderObservable existed.
  114037. * The set callback will be triggered just before rendering the layer.
  114038. */
  114039. set: function (callback) {
  114040. if (this._onBeforeRenderObserver) {
  114041. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  114042. }
  114043. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  114044. },
  114045. enumerable: true,
  114046. configurable: true
  114047. });
  114048. Object.defineProperty(Layer.prototype, "onAfterRender", {
  114049. /**
  114050. * Back compatibility with callback before the onAfterRenderObservable existed.
  114051. * The set callback will be triggered just after rendering the layer.
  114052. */
  114053. set: function (callback) {
  114054. if (this._onAfterRenderObserver) {
  114055. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  114056. }
  114057. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  114058. },
  114059. enumerable: true,
  114060. configurable: true
  114061. });
  114062. Layer.prototype._createIndexBuffer = function () {
  114063. var engine = this._scene.getEngine();
  114064. // Indices
  114065. var indices = [];
  114066. indices.push(0);
  114067. indices.push(1);
  114068. indices.push(2);
  114069. indices.push(0);
  114070. indices.push(2);
  114071. indices.push(3);
  114072. this._indexBuffer = engine.createIndexBuffer(indices);
  114073. };
  114074. /** @hidden */
  114075. Layer.prototype._rebuild = function () {
  114076. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  114077. if (vb) {
  114078. vb._rebuild();
  114079. }
  114080. this._createIndexBuffer();
  114081. };
  114082. /**
  114083. * Renders the layer in the scene.
  114084. */
  114085. Layer.prototype.render = function () {
  114086. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  114087. // Check
  114088. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
  114089. return;
  114090. }
  114091. var engine = this._scene.getEngine();
  114092. this.onBeforeRenderObservable.notifyObservers(this);
  114093. // Render
  114094. engine.enableEffect(currentEffect);
  114095. engine.setState(false);
  114096. // Texture
  114097. currentEffect.setTexture("textureSampler", this.texture);
  114098. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  114099. // Color
  114100. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  114101. // Scale / offset
  114102. currentEffect.setVector2("offset", this.offset);
  114103. currentEffect.setVector2("scale", this.scale);
  114104. // VBOs
  114105. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  114106. // Draw order
  114107. if (!this.alphaTest) {
  114108. engine.setAlphaMode(this.alphaBlendingMode);
  114109. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  114110. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  114111. }
  114112. else {
  114113. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  114114. }
  114115. this.onAfterRenderObservable.notifyObservers(this);
  114116. };
  114117. /**
  114118. * Disposes and releases the associated ressources.
  114119. */
  114120. Layer.prototype.dispose = function () {
  114121. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  114122. if (vertexBuffer) {
  114123. vertexBuffer.dispose();
  114124. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  114125. }
  114126. if (this._indexBuffer) {
  114127. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  114128. this._indexBuffer = null;
  114129. }
  114130. if (this.texture) {
  114131. this.texture.dispose();
  114132. this.texture = null;
  114133. }
  114134. // Remove from scene
  114135. var index = this._scene.layers.indexOf(this);
  114136. this._scene.layers.splice(index, 1);
  114137. // Callback
  114138. this.onDisposeObservable.notifyObservers(this);
  114139. this.onDisposeObservable.clear();
  114140. this.onAfterRenderObservable.clear();
  114141. this.onBeforeRenderObservable.clear();
  114142. };
  114143. return Layer;
  114144. }());
  114145. BABYLON.Layer = Layer;
  114146. })(BABYLON || (BABYLON = {}));
  114147. //# sourceMappingURL=babylon.layer.js.map
  114148. var BABYLON;
  114149. (function (BABYLON) {
  114150. /**
  114151. * Class used to host texture specific utilities
  114152. */
  114153. var TextureTools = /** @class */ (function () {
  114154. function TextureTools() {
  114155. }
  114156. /**
  114157. * Uses the GPU to create a copy texture rescaled at a given size
  114158. * @param texture Texture to copy from
  114159. * @param width defines the desired width
  114160. * @param height defines the desired height
  114161. * @param useBilinearMode defines if bilinear mode has to be used
  114162. * @return the generated texture
  114163. */
  114164. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  114165. if (useBilinearMode === void 0) { useBilinearMode = true; }
  114166. var scene = texture.getScene();
  114167. var engine = scene.getEngine();
  114168. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  114169. rtt.wrapU = texture.wrapU;
  114170. rtt.wrapV = texture.wrapV;
  114171. rtt.uOffset = texture.uOffset;
  114172. rtt.vOffset = texture.vOffset;
  114173. rtt.uScale = texture.uScale;
  114174. rtt.vScale = texture.vScale;
  114175. rtt.uAng = texture.uAng;
  114176. rtt.vAng = texture.vAng;
  114177. rtt.wAng = texture.wAng;
  114178. rtt.coordinatesIndex = texture.coordinatesIndex;
  114179. rtt.level = texture.level;
  114180. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  114181. rtt._texture.isReady = false;
  114182. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114183. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114184. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  114185. passPostProcess.getEffect().executeWhenCompiled(function () {
  114186. passPostProcess.onApply = function (effect) {
  114187. effect.setTexture("textureSampler", texture);
  114188. };
  114189. var internalTexture = rtt.getInternalTexture();
  114190. if (internalTexture) {
  114191. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  114192. engine.unBindFramebuffer(internalTexture);
  114193. rtt.disposeFramebufferObjects();
  114194. passPostProcess.dispose();
  114195. internalTexture.isReady = true;
  114196. }
  114197. });
  114198. return rtt;
  114199. };
  114200. /**
  114201. * Gets an environment BRDF texture for a given scene
  114202. * @param scene defines the hosting scene
  114203. * @returns the environment BRDF texture
  114204. */
  114205. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  114206. if (!scene._environmentBRDFTexture) {
  114207. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  114208. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114209. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114210. scene._environmentBRDFTexture = texture;
  114211. }
  114212. return scene._environmentBRDFTexture;
  114213. };
  114214. 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=";
  114215. return TextureTools;
  114216. }());
  114217. BABYLON.TextureTools = TextureTools;
  114218. })(BABYLON || (BABYLON = {}));
  114219. //# sourceMappingURL=babylon.textureTools.js.map
  114220. var BABYLON;
  114221. (function (BABYLON) {
  114222. /**
  114223. * 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.
  114224. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  114225. */
  114226. var FramingBehavior = /** @class */ (function () {
  114227. function FramingBehavior() {
  114228. this._mode = FramingBehavior.FitFrustumSidesMode;
  114229. this._radiusScale = 1.0;
  114230. this._positionScale = 0.5;
  114231. this._defaultElevation = 0.3;
  114232. this._elevationReturnTime = 1500;
  114233. this._elevationReturnWaitTime = 1000;
  114234. this._zoomStopsAnimation = false;
  114235. this._framingTime = 1500;
  114236. /**
  114237. * Define if the behavior should automatically change the configured
  114238. * camera limits and sensibilities.
  114239. */
  114240. this.autoCorrectCameraLimitsAndSensibility = true;
  114241. this._isPointerDown = false;
  114242. this._lastInteractionTime = -Infinity;
  114243. // Framing control
  114244. this._animatables = new Array();
  114245. this._betaIsAnimating = false;
  114246. }
  114247. Object.defineProperty(FramingBehavior.prototype, "name", {
  114248. /**
  114249. * Gets the name of the behavior.
  114250. */
  114251. get: function () {
  114252. return "Framing";
  114253. },
  114254. enumerable: true,
  114255. configurable: true
  114256. });
  114257. Object.defineProperty(FramingBehavior.prototype, "mode", {
  114258. /**
  114259. * Gets current mode used by the behavior.
  114260. */
  114261. get: function () {
  114262. return this._mode;
  114263. },
  114264. /**
  114265. * Sets the current mode used by the behavior
  114266. */
  114267. set: function (mode) {
  114268. this._mode = mode;
  114269. },
  114270. enumerable: true,
  114271. configurable: true
  114272. });
  114273. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  114274. /**
  114275. * Gets the scale applied to the radius
  114276. */
  114277. get: function () {
  114278. return this._radiusScale;
  114279. },
  114280. /**
  114281. * Sets the scale applied to the radius (1 by default)
  114282. */
  114283. set: function (radius) {
  114284. this._radiusScale = radius;
  114285. },
  114286. enumerable: true,
  114287. configurable: true
  114288. });
  114289. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  114290. /**
  114291. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  114292. */
  114293. get: function () {
  114294. return this._positionScale;
  114295. },
  114296. /**
  114297. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  114298. */
  114299. set: function (scale) {
  114300. this._positionScale = scale;
  114301. },
  114302. enumerable: true,
  114303. configurable: true
  114304. });
  114305. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  114306. /**
  114307. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  114308. * behaviour is triggered, in radians.
  114309. */
  114310. get: function () {
  114311. return this._defaultElevation;
  114312. },
  114313. /**
  114314. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  114315. * behaviour is triggered, in radians.
  114316. */
  114317. set: function (elevation) {
  114318. this._defaultElevation = elevation;
  114319. },
  114320. enumerable: true,
  114321. configurable: true
  114322. });
  114323. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  114324. /**
  114325. * Gets the time (in milliseconds) taken to return to the default beta position.
  114326. * Negative value indicates camera should not return to default.
  114327. */
  114328. get: function () {
  114329. return this._elevationReturnTime;
  114330. },
  114331. /**
  114332. * Sets the time (in milliseconds) taken to return to the default beta position.
  114333. * Negative value indicates camera should not return to default.
  114334. */
  114335. set: function (speed) {
  114336. this._elevationReturnTime = speed;
  114337. },
  114338. enumerable: true,
  114339. configurable: true
  114340. });
  114341. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  114342. /**
  114343. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  114344. */
  114345. get: function () {
  114346. return this._elevationReturnWaitTime;
  114347. },
  114348. /**
  114349. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  114350. */
  114351. set: function (time) {
  114352. this._elevationReturnWaitTime = time;
  114353. },
  114354. enumerable: true,
  114355. configurable: true
  114356. });
  114357. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  114358. /**
  114359. * Gets the flag that indicates if user zooming should stop animation.
  114360. */
  114361. get: function () {
  114362. return this._zoomStopsAnimation;
  114363. },
  114364. /**
  114365. * Sets the flag that indicates if user zooming should stop animation.
  114366. */
  114367. set: function (flag) {
  114368. this._zoomStopsAnimation = flag;
  114369. },
  114370. enumerable: true,
  114371. configurable: true
  114372. });
  114373. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  114374. /**
  114375. * Gets the transition time when framing the mesh, in milliseconds
  114376. */
  114377. get: function () {
  114378. return this._framingTime;
  114379. },
  114380. /**
  114381. * Sets the transition time when framing the mesh, in milliseconds
  114382. */
  114383. set: function (time) {
  114384. this._framingTime = time;
  114385. },
  114386. enumerable: true,
  114387. configurable: true
  114388. });
  114389. /**
  114390. * Initializes the behavior.
  114391. */
  114392. FramingBehavior.prototype.init = function () {
  114393. // Do notihng
  114394. };
  114395. /**
  114396. * Attaches the behavior to its arc rotate camera.
  114397. * @param camera Defines the camera to attach the behavior to
  114398. */
  114399. FramingBehavior.prototype.attach = function (camera) {
  114400. var _this = this;
  114401. this._attachedCamera = camera;
  114402. var scene = this._attachedCamera.getScene();
  114403. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  114404. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  114405. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  114406. _this._isPointerDown = true;
  114407. return;
  114408. }
  114409. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  114410. _this._isPointerDown = false;
  114411. }
  114412. });
  114413. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  114414. if (mesh) {
  114415. _this.zoomOnMesh(mesh);
  114416. }
  114417. });
  114418. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  114419. // Stop the animation if there is user interaction and the animation should stop for this interaction
  114420. _this._applyUserInteraction();
  114421. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  114422. // back to the default position after a given timeout
  114423. _this._maintainCameraAboveGround();
  114424. });
  114425. };
  114426. /**
  114427. * Detaches the behavior from its current arc rotate camera.
  114428. */
  114429. FramingBehavior.prototype.detach = function () {
  114430. if (!this._attachedCamera) {
  114431. return;
  114432. }
  114433. var scene = this._attachedCamera.getScene();
  114434. if (this._onPrePointerObservableObserver) {
  114435. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  114436. }
  114437. if (this._onAfterCheckInputsObserver) {
  114438. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  114439. }
  114440. if (this._onMeshTargetChangedObserver) {
  114441. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  114442. }
  114443. this._attachedCamera = null;
  114444. };
  114445. /**
  114446. * Targets the given mesh and updates zoom level accordingly.
  114447. * @param mesh The mesh to target.
  114448. * @param radius Optional. If a cached radius position already exists, overrides default.
  114449. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  114450. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114451. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114452. */
  114453. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  114454. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114455. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114456. mesh.computeWorldMatrix(true);
  114457. var boundingBox = mesh.getBoundingInfo().boundingBox;
  114458. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  114459. };
  114460. /**
  114461. * Targets the given mesh with its children and updates zoom level accordingly.
  114462. * @param mesh The mesh to target.
  114463. * @param radius Optional. If a cached radius position already exists, overrides default.
  114464. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  114465. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114466. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114467. */
  114468. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  114469. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114470. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114471. mesh.computeWorldMatrix(true);
  114472. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  114473. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  114474. };
  114475. /**
  114476. * Targets the given meshes with their children and updates zoom level accordingly.
  114477. * @param meshes The mesh to target.
  114478. * @param radius Optional. If a cached radius position already exists, overrides default.
  114479. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  114480. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114481. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114482. */
  114483. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  114484. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114485. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114486. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  114487. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  114488. for (var i = 0; i < meshes.length; i++) {
  114489. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  114490. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  114491. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  114492. }
  114493. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  114494. };
  114495. /**
  114496. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  114497. * @param minimumWorld Determines the smaller position of the bounding box extend
  114498. * @param maximumWorld Determines the bigger position of the bounding box extend
  114499. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114500. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114501. */
  114502. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  114503. var _this = this;
  114504. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114505. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114506. var zoomTarget;
  114507. if (!this._attachedCamera) {
  114508. return;
  114509. }
  114510. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  114511. var bottom = minimumWorld.y;
  114512. var top = maximumWorld.y;
  114513. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  114514. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  114515. if (focusOnOriginXZ) {
  114516. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  114517. }
  114518. else {
  114519. var centerWorld = minimumWorld.add(radiusWorld);
  114520. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  114521. }
  114522. if (!this._vectorTransition) {
  114523. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  114524. }
  114525. this._betaIsAnimating = true;
  114526. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  114527. if (animatable) {
  114528. this._animatables.push(animatable);
  114529. }
  114530. // sets the radius and lower radius bounds
  114531. // Small delta ensures camera is not always at lower zoom limit.
  114532. var radius = 0;
  114533. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  114534. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  114535. if (this.autoCorrectCameraLimitsAndSensibility) {
  114536. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  114537. }
  114538. radius = position;
  114539. }
  114540. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  114541. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  114542. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  114543. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  114544. }
  114545. }
  114546. // Set sensibilities
  114547. if (this.autoCorrectCameraLimitsAndSensibility) {
  114548. var extend = maximumWorld.subtract(minimumWorld).length();
  114549. this._attachedCamera.panningSensibility = 5000 / extend;
  114550. this._attachedCamera.wheelPrecision = 100 / radius;
  114551. }
  114552. // transition to new radius
  114553. if (!this._radiusTransition) {
  114554. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  114555. }
  114556. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  114557. _this.stopAllAnimations();
  114558. if (onAnimationEnd) {
  114559. onAnimationEnd();
  114560. }
  114561. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  114562. _this._attachedCamera.storeState();
  114563. }
  114564. });
  114565. if (animatable) {
  114566. this._animatables.push(animatable);
  114567. }
  114568. };
  114569. /**
  114570. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  114571. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  114572. * frustum width.
  114573. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  114574. * to fully enclose the mesh in the viewing frustum.
  114575. */
  114576. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  114577. var size = maximumWorld.subtract(minimumWorld);
  114578. var boxVectorGlobalDiagonal = size.length();
  114579. var frustumSlope = this._getFrustumSlope();
  114580. // Formula for setting distance
  114581. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  114582. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  114583. // Horizon distance
  114584. var radius = radiusWithoutFraming * this._radiusScale;
  114585. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  114586. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  114587. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  114588. var camera = this._attachedCamera;
  114589. if (!camera) {
  114590. return 0;
  114591. }
  114592. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  114593. // Don't exceed the requested limit
  114594. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  114595. }
  114596. // Don't exceed the upper radius limit
  114597. if (camera.upperRadiusLimit) {
  114598. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  114599. }
  114600. return distance;
  114601. };
  114602. /**
  114603. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  114604. * is automatically returned to its default position (expected to be above ground plane).
  114605. */
  114606. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  114607. var _this = this;
  114608. if (this._elevationReturnTime < 0) {
  114609. return;
  114610. }
  114611. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  114612. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  114613. var limitBeta = Math.PI * 0.5;
  114614. // Bring the camera back up if below the ground plane
  114615. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  114616. this._betaIsAnimating = true;
  114617. //Transition to new position
  114618. this.stopAllAnimations();
  114619. if (!this._betaTransition) {
  114620. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  114621. }
  114622. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  114623. _this._clearAnimationLocks();
  114624. _this.stopAllAnimations();
  114625. });
  114626. if (animatabe) {
  114627. this._animatables.push(animatabe);
  114628. }
  114629. }
  114630. };
  114631. /**
  114632. * Returns the frustum slope based on the canvas ratio and camera FOV
  114633. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  114634. */
  114635. FramingBehavior.prototype._getFrustumSlope = function () {
  114636. // Calculate the viewport ratio
  114637. // Aspect Ratio is Height/Width.
  114638. var camera = this._attachedCamera;
  114639. if (!camera) {
  114640. return BABYLON.Vector2.Zero();
  114641. }
  114642. var engine = camera.getScene().getEngine();
  114643. var aspectRatio = engine.getAspectRatio(camera);
  114644. // Camera FOV is the vertical field of view (top-bottom) in radians.
  114645. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  114646. var frustumSlopeY = Math.tan(camera.fov / 2);
  114647. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  114648. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  114649. // along the forward vector.
  114650. var frustumSlopeX = frustumSlopeY * aspectRatio;
  114651. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  114652. };
  114653. /**
  114654. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  114655. */
  114656. FramingBehavior.prototype._clearAnimationLocks = function () {
  114657. this._betaIsAnimating = false;
  114658. };
  114659. /**
  114660. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  114661. */
  114662. FramingBehavior.prototype._applyUserInteraction = function () {
  114663. if (this.isUserIsMoving) {
  114664. this._lastInteractionTime = BABYLON.Tools.Now;
  114665. this.stopAllAnimations();
  114666. this._clearAnimationLocks();
  114667. }
  114668. };
  114669. /**
  114670. * Stops and removes all animations that have been applied to the camera
  114671. */
  114672. FramingBehavior.prototype.stopAllAnimations = function () {
  114673. if (this._attachedCamera) {
  114674. this._attachedCamera.animations = [];
  114675. }
  114676. while (this._animatables.length) {
  114677. if (this._animatables[0]) {
  114678. this._animatables[0].onAnimationEnd = null;
  114679. this._animatables[0].stop();
  114680. }
  114681. this._animatables.shift();
  114682. }
  114683. };
  114684. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  114685. /**
  114686. * Gets a value indicating if the user is moving the camera
  114687. */
  114688. get: function () {
  114689. if (!this._attachedCamera) {
  114690. return false;
  114691. }
  114692. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  114693. this._attachedCamera.inertialBetaOffset !== 0 ||
  114694. this._attachedCamera.inertialRadiusOffset !== 0 ||
  114695. this._attachedCamera.inertialPanningX !== 0 ||
  114696. this._attachedCamera.inertialPanningY !== 0 ||
  114697. this._isPointerDown;
  114698. },
  114699. enumerable: true,
  114700. configurable: true
  114701. });
  114702. /**
  114703. * The easing function used by animations
  114704. */
  114705. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  114706. /**
  114707. * The easing mode used by animations
  114708. */
  114709. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  114710. // Statics
  114711. /**
  114712. * The camera can move all the way towards the mesh.
  114713. */
  114714. FramingBehavior.IgnoreBoundsSizeMode = 0;
  114715. /**
  114716. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  114717. */
  114718. FramingBehavior.FitFrustumSidesMode = 1;
  114719. return FramingBehavior;
  114720. }());
  114721. BABYLON.FramingBehavior = FramingBehavior;
  114722. })(BABYLON || (BABYLON = {}));
  114723. //# sourceMappingURL=babylon.framingBehavior.js.map
  114724. var BABYLON;
  114725. (function (BABYLON) {
  114726. /**
  114727. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  114728. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  114729. */
  114730. var BouncingBehavior = /** @class */ (function () {
  114731. function BouncingBehavior() {
  114732. /**
  114733. * The duration of the animation, in milliseconds
  114734. */
  114735. this.transitionDuration = 450;
  114736. /**
  114737. * Length of the distance animated by the transition when lower radius is reached
  114738. */
  114739. this.lowerRadiusTransitionRange = 2;
  114740. /**
  114741. * Length of the distance animated by the transition when upper radius is reached
  114742. */
  114743. this.upperRadiusTransitionRange = -2;
  114744. this._autoTransitionRange = false;
  114745. // Animations
  114746. this._radiusIsAnimating = false;
  114747. this._radiusBounceTransition = null;
  114748. this._animatables = new Array();
  114749. }
  114750. Object.defineProperty(BouncingBehavior.prototype, "name", {
  114751. /**
  114752. * Gets the name of the behavior.
  114753. */
  114754. get: function () {
  114755. return "Bouncing";
  114756. },
  114757. enumerable: true,
  114758. configurable: true
  114759. });
  114760. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  114761. /**
  114762. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  114763. */
  114764. get: function () {
  114765. return this._autoTransitionRange;
  114766. },
  114767. /**
  114768. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  114769. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  114770. */
  114771. set: function (value) {
  114772. var _this = this;
  114773. if (this._autoTransitionRange === value) {
  114774. return;
  114775. }
  114776. this._autoTransitionRange = value;
  114777. var camera = this._attachedCamera;
  114778. if (!camera) {
  114779. return;
  114780. }
  114781. if (value) {
  114782. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  114783. if (!mesh) {
  114784. return;
  114785. }
  114786. mesh.computeWorldMatrix(true);
  114787. var diagonal = mesh.getBoundingInfo().diagonalLength;
  114788. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  114789. _this.upperRadiusTransitionRange = diagonal * 0.05;
  114790. });
  114791. }
  114792. else if (this._onMeshTargetChangedObserver) {
  114793. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  114794. }
  114795. },
  114796. enumerable: true,
  114797. configurable: true
  114798. });
  114799. /**
  114800. * Initializes the behavior.
  114801. */
  114802. BouncingBehavior.prototype.init = function () {
  114803. // Do notihng
  114804. };
  114805. /**
  114806. * Attaches the behavior to its arc rotate camera.
  114807. * @param camera Defines the camera to attach the behavior to
  114808. */
  114809. BouncingBehavior.prototype.attach = function (camera) {
  114810. var _this = this;
  114811. this._attachedCamera = camera;
  114812. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  114813. if (!_this._attachedCamera) {
  114814. return;
  114815. }
  114816. // Add the bounce animation to the lower radius limit
  114817. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  114818. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  114819. }
  114820. // Add the bounce animation to the upper radius limit
  114821. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  114822. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  114823. }
  114824. });
  114825. };
  114826. /**
  114827. * Detaches the behavior from its current arc rotate camera.
  114828. */
  114829. BouncingBehavior.prototype.detach = function () {
  114830. if (!this._attachedCamera) {
  114831. return;
  114832. }
  114833. if (this._onAfterCheckInputsObserver) {
  114834. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  114835. }
  114836. if (this._onMeshTargetChangedObserver) {
  114837. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  114838. }
  114839. this._attachedCamera = null;
  114840. };
  114841. /**
  114842. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  114843. * @param radiusLimit The limit to check against.
  114844. * @return Bool to indicate if at limit.
  114845. */
  114846. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  114847. if (!this._attachedCamera) {
  114848. return false;
  114849. }
  114850. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  114851. return true;
  114852. }
  114853. return false;
  114854. };
  114855. /**
  114856. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  114857. * @param radiusDelta The delta by which to animate to. Can be negative.
  114858. */
  114859. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  114860. var _this = this;
  114861. if (!this._attachedCamera) {
  114862. return;
  114863. }
  114864. if (!this._radiusBounceTransition) {
  114865. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  114866. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  114867. }
  114868. // Prevent zoom until bounce has completed
  114869. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  114870. this._attachedCamera.wheelPrecision = Infinity;
  114871. this._attachedCamera.inertialRadiusOffset = 0;
  114872. // Animate to the radius limit
  114873. this.stopAllAnimations();
  114874. this._radiusIsAnimating = true;
  114875. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  114876. if (animatable) {
  114877. this._animatables.push(animatable);
  114878. }
  114879. };
  114880. /**
  114881. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  114882. */
  114883. BouncingBehavior.prototype._clearAnimationLocks = function () {
  114884. this._radiusIsAnimating = false;
  114885. if (this._attachedCamera) {
  114886. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  114887. }
  114888. };
  114889. /**
  114890. * Stops and removes all animations that have been applied to the camera
  114891. */
  114892. BouncingBehavior.prototype.stopAllAnimations = function () {
  114893. if (this._attachedCamera) {
  114894. this._attachedCamera.animations = [];
  114895. }
  114896. while (this._animatables.length) {
  114897. this._animatables[0].onAnimationEnd = null;
  114898. this._animatables[0].stop();
  114899. this._animatables.shift();
  114900. }
  114901. };
  114902. /**
  114903. * The easing function used by animations
  114904. */
  114905. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  114906. /**
  114907. * The easing mode used by animations
  114908. */
  114909. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  114910. return BouncingBehavior;
  114911. }());
  114912. BABYLON.BouncingBehavior = BouncingBehavior;
  114913. })(BABYLON || (BABYLON = {}));
  114914. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  114915. var BABYLON;
  114916. (function (BABYLON) {
  114917. /**
  114918. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  114919. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  114920. */
  114921. var AutoRotationBehavior = /** @class */ (function () {
  114922. function AutoRotationBehavior() {
  114923. this._zoomStopsAnimation = false;
  114924. this._idleRotationSpeed = 0.05;
  114925. this._idleRotationWaitTime = 2000;
  114926. this._idleRotationSpinupTime = 2000;
  114927. this._isPointerDown = false;
  114928. this._lastFrameTime = null;
  114929. this._lastInteractionTime = -Infinity;
  114930. this._cameraRotationSpeed = 0;
  114931. this._lastFrameRadius = 0;
  114932. }
  114933. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  114934. /**
  114935. * Gets the name of the behavior.
  114936. */
  114937. get: function () {
  114938. return "AutoRotation";
  114939. },
  114940. enumerable: true,
  114941. configurable: true
  114942. });
  114943. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  114944. /**
  114945. * Gets the flag that indicates if user zooming should stop animation.
  114946. */
  114947. get: function () {
  114948. return this._zoomStopsAnimation;
  114949. },
  114950. /**
  114951. * Sets the flag that indicates if user zooming should stop animation.
  114952. */
  114953. set: function (flag) {
  114954. this._zoomStopsAnimation = flag;
  114955. },
  114956. enumerable: true,
  114957. configurable: true
  114958. });
  114959. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  114960. /**
  114961. * Gets the default speed at which the camera rotates around the model.
  114962. */
  114963. get: function () {
  114964. return this._idleRotationSpeed;
  114965. },
  114966. /**
  114967. * Sets the default speed at which the camera rotates around the model.
  114968. */
  114969. set: function (speed) {
  114970. this._idleRotationSpeed = speed;
  114971. },
  114972. enumerable: true,
  114973. configurable: true
  114974. });
  114975. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  114976. /**
  114977. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  114978. */
  114979. get: function () {
  114980. return this._idleRotationWaitTime;
  114981. },
  114982. /**
  114983. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  114984. */
  114985. set: function (time) {
  114986. this._idleRotationWaitTime = time;
  114987. },
  114988. enumerable: true,
  114989. configurable: true
  114990. });
  114991. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  114992. /**
  114993. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  114994. */
  114995. get: function () {
  114996. return this._idleRotationSpinupTime;
  114997. },
  114998. /**
  114999. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  115000. */
  115001. set: function (time) {
  115002. this._idleRotationSpinupTime = time;
  115003. },
  115004. enumerable: true,
  115005. configurable: true
  115006. });
  115007. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  115008. /**
  115009. * Gets a value indicating if the camera is currently rotating because of this behavior
  115010. */
  115011. get: function () {
  115012. return Math.abs(this._cameraRotationSpeed) > 0;
  115013. },
  115014. enumerable: true,
  115015. configurable: true
  115016. });
  115017. /**
  115018. * Initializes the behavior.
  115019. */
  115020. AutoRotationBehavior.prototype.init = function () {
  115021. // Do notihng
  115022. };
  115023. /**
  115024. * Attaches the behavior to its arc rotate camera.
  115025. * @param camera Defines the camera to attach the behavior to
  115026. */
  115027. AutoRotationBehavior.prototype.attach = function (camera) {
  115028. var _this = this;
  115029. this._attachedCamera = camera;
  115030. var scene = this._attachedCamera.getScene();
  115031. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  115032. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  115033. _this._isPointerDown = true;
  115034. return;
  115035. }
  115036. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  115037. _this._isPointerDown = false;
  115038. }
  115039. });
  115040. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  115041. var now = BABYLON.Tools.Now;
  115042. var dt = 0;
  115043. if (_this._lastFrameTime != null) {
  115044. dt = now - _this._lastFrameTime;
  115045. }
  115046. _this._lastFrameTime = now;
  115047. // Stop the animation if there is user interaction and the animation should stop for this interaction
  115048. _this._applyUserInteraction();
  115049. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  115050. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  115051. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  115052. // Step camera rotation by rotation speed
  115053. if (_this._attachedCamera) {
  115054. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  115055. }
  115056. });
  115057. };
  115058. /**
  115059. * Detaches the behavior from its current arc rotate camera.
  115060. */
  115061. AutoRotationBehavior.prototype.detach = function () {
  115062. if (!this._attachedCamera) {
  115063. return;
  115064. }
  115065. var scene = this._attachedCamera.getScene();
  115066. if (this._onPrePointerObservableObserver) {
  115067. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  115068. }
  115069. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  115070. this._attachedCamera = null;
  115071. };
  115072. /**
  115073. * Returns true if user is scrolling.
  115074. * @return true if user is scrolling.
  115075. */
  115076. AutoRotationBehavior.prototype._userIsZooming = function () {
  115077. if (!this._attachedCamera) {
  115078. return false;
  115079. }
  115080. return this._attachedCamera.inertialRadiusOffset !== 0;
  115081. };
  115082. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  115083. if (!this._attachedCamera) {
  115084. return false;
  115085. }
  115086. var zoomHasHitLimit = false;
  115087. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  115088. zoomHasHitLimit = true;
  115089. }
  115090. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  115091. this._lastFrameRadius = this._attachedCamera.radius;
  115092. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  115093. };
  115094. /**
  115095. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  115096. */
  115097. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  115098. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  115099. this._lastInteractionTime = BABYLON.Tools.Now;
  115100. }
  115101. };
  115102. // Tools
  115103. AutoRotationBehavior.prototype._userIsMoving = function () {
  115104. if (!this._attachedCamera) {
  115105. return false;
  115106. }
  115107. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  115108. this._attachedCamera.inertialBetaOffset !== 0 ||
  115109. this._attachedCamera.inertialRadiusOffset !== 0 ||
  115110. this._attachedCamera.inertialPanningX !== 0 ||
  115111. this._attachedCamera.inertialPanningY !== 0 ||
  115112. this._isPointerDown;
  115113. };
  115114. return AutoRotationBehavior;
  115115. }());
  115116. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  115117. })(BABYLON || (BABYLON = {}));
  115118. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  115119. var BABYLON;
  115120. (function (BABYLON) {
  115121. /**
  115122. * Options to create the null engine
  115123. */
  115124. var NullEngineOptions = /** @class */ (function () {
  115125. function NullEngineOptions() {
  115126. /**
  115127. * Render width (Default: 512)
  115128. */
  115129. this.renderWidth = 512;
  115130. /**
  115131. * Render height (Default: 256)
  115132. */
  115133. this.renderHeight = 256;
  115134. /**
  115135. * Texture size (Default: 512)
  115136. */
  115137. this.textureSize = 512;
  115138. /**
  115139. * If delta time between frames should be constant
  115140. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  115141. */
  115142. this.deterministicLockstep = false;
  115143. /**
  115144. * Maximum about of steps between frames (Default: 4)
  115145. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  115146. */
  115147. this.lockstepMaxSteps = 4;
  115148. }
  115149. return NullEngineOptions;
  115150. }());
  115151. BABYLON.NullEngineOptions = NullEngineOptions;
  115152. /**
  115153. * The null engine class provides support for headless version of babylon.js.
  115154. * This can be used in server side scenario or for testing purposes
  115155. */
  115156. var NullEngine = /** @class */ (function (_super) {
  115157. __extends(NullEngine, _super);
  115158. function NullEngine(options) {
  115159. if (options === void 0) { options = new NullEngineOptions(); }
  115160. var _this = _super.call(this, null) || this;
  115161. if (options.deterministicLockstep === undefined) {
  115162. options.deterministicLockstep = false;
  115163. }
  115164. if (options.lockstepMaxSteps === undefined) {
  115165. options.lockstepMaxSteps = 4;
  115166. }
  115167. _this._options = options;
  115168. // Init caps
  115169. // We consider we are on a webgl1 capable device
  115170. _this._caps = new BABYLON.EngineCapabilities();
  115171. _this._caps.maxTexturesImageUnits = 16;
  115172. _this._caps.maxVertexTextureImageUnits = 16;
  115173. _this._caps.maxTextureSize = 512;
  115174. _this._caps.maxCubemapTextureSize = 512;
  115175. _this._caps.maxRenderTextureSize = 512;
  115176. _this._caps.maxVertexAttribs = 16;
  115177. _this._caps.maxVaryingVectors = 16;
  115178. _this._caps.maxFragmentUniformVectors = 16;
  115179. _this._caps.maxVertexUniformVectors = 16;
  115180. // Extensions
  115181. _this._caps.standardDerivatives = false;
  115182. _this._caps.astc = null;
  115183. _this._caps.s3tc = null;
  115184. _this._caps.pvrtc = null;
  115185. _this._caps.etc1 = null;
  115186. _this._caps.etc2 = null;
  115187. _this._caps.textureAnisotropicFilterExtension = null;
  115188. _this._caps.maxAnisotropy = 0;
  115189. _this._caps.uintIndices = false;
  115190. _this._caps.fragmentDepthSupported = false;
  115191. _this._caps.highPrecisionShaderSupported = true;
  115192. _this._caps.colorBufferFloat = false;
  115193. _this._caps.textureFloat = false;
  115194. _this._caps.textureFloatLinearFiltering = false;
  115195. _this._caps.textureFloatRender = false;
  115196. _this._caps.textureHalfFloat = false;
  115197. _this._caps.textureHalfFloatLinearFiltering = false;
  115198. _this._caps.textureHalfFloatRender = false;
  115199. _this._caps.textureLOD = false;
  115200. _this._caps.drawBuffersExtension = false;
  115201. _this._caps.depthTextureExtension = false;
  115202. _this._caps.vertexArrayObject = false;
  115203. _this._caps.instancedArrays = false;
  115204. BABYLON.Tools.Log("Babylon.js v" + BABYLON.Engine.Version + " - Null engine");
  115205. // Wrappers
  115206. if (typeof URL === "undefined") {
  115207. URL = {
  115208. createObjectURL: function () { },
  115209. revokeObjectURL: function () { }
  115210. };
  115211. }
  115212. if (typeof Blob === "undefined") {
  115213. Blob = function () { };
  115214. }
  115215. return _this;
  115216. }
  115217. /**
  115218. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  115219. */
  115220. NullEngine.prototype.isDeterministicLockStep = function () {
  115221. return this._options.deterministicLockstep;
  115222. };
  115223. /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
  115224. NullEngine.prototype.getLockstepMaxSteps = function () {
  115225. return this._options.lockstepMaxSteps;
  115226. };
  115227. /**
  115228. * Sets hardware scaling, used to save performance if needed
  115229. * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  115230. */
  115231. NullEngine.prototype.getHardwareScalingLevel = function () {
  115232. return 1.0;
  115233. };
  115234. NullEngine.prototype.createVertexBuffer = function (vertices) {
  115235. return {
  115236. capacity: 0,
  115237. references: 1,
  115238. is32Bits: false
  115239. };
  115240. };
  115241. NullEngine.prototype.createIndexBuffer = function (indices) {
  115242. return {
  115243. capacity: 0,
  115244. references: 1,
  115245. is32Bits: false
  115246. };
  115247. };
  115248. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  115249. if (stencil === void 0) { stencil = false; }
  115250. };
  115251. NullEngine.prototype.getRenderWidth = function (useScreen) {
  115252. if (useScreen === void 0) { useScreen = false; }
  115253. if (!useScreen && this._currentRenderTarget) {
  115254. return this._currentRenderTarget.width;
  115255. }
  115256. return this._options.renderWidth;
  115257. };
  115258. NullEngine.prototype.getRenderHeight = function (useScreen) {
  115259. if (useScreen === void 0) { useScreen = false; }
  115260. if (!useScreen && this._currentRenderTarget) {
  115261. return this._currentRenderTarget.height;
  115262. }
  115263. return this._options.renderHeight;
  115264. };
  115265. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  115266. this._cachedViewport = viewport;
  115267. };
  115268. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  115269. return {
  115270. transformFeedback: null,
  115271. __SPECTOR_rebuildProgram: null,
  115272. isParallelCompiled: false
  115273. };
  115274. };
  115275. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  115276. return [];
  115277. };
  115278. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  115279. return [];
  115280. };
  115281. NullEngine.prototype.bindSamplers = function (effect) {
  115282. this._currentEffect = null;
  115283. };
  115284. NullEngine.prototype.enableEffect = function (effect) {
  115285. this._currentEffect = effect;
  115286. if (effect.onBind) {
  115287. effect.onBind(effect);
  115288. }
  115289. if (effect._onBindObservable) {
  115290. effect._onBindObservable.notifyObservers(effect);
  115291. }
  115292. };
  115293. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  115294. if (zOffset === void 0) { zOffset = 0; }
  115295. if (reverseSide === void 0) { reverseSide = false; }
  115296. };
  115297. NullEngine.prototype.setIntArray = function (uniform, array) {
  115298. };
  115299. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  115300. };
  115301. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  115302. };
  115303. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  115304. };
  115305. NullEngine.prototype.setFloatArray = function (uniform, array) {
  115306. };
  115307. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  115308. };
  115309. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  115310. };
  115311. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  115312. };
  115313. NullEngine.prototype.setArray = function (uniform, array) {
  115314. };
  115315. NullEngine.prototype.setArray2 = function (uniform, array) {
  115316. };
  115317. NullEngine.prototype.setArray3 = function (uniform, array) {
  115318. };
  115319. NullEngine.prototype.setArray4 = function (uniform, array) {
  115320. };
  115321. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  115322. };
  115323. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  115324. };
  115325. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  115326. };
  115327. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  115328. };
  115329. NullEngine.prototype.setFloat = function (uniform, value) {
  115330. };
  115331. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  115332. };
  115333. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  115334. };
  115335. NullEngine.prototype.setBool = function (uniform, bool) {
  115336. };
  115337. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  115338. };
  115339. NullEngine.prototype.setColor3 = function (uniform, color3) {
  115340. };
  115341. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  115342. };
  115343. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  115344. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  115345. if (this._alphaMode === mode) {
  115346. return;
  115347. }
  115348. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  115349. if (!noDepthWriteChange) {
  115350. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  115351. }
  115352. this._alphaMode = mode;
  115353. };
  115354. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  115355. };
  115356. NullEngine.prototype.wipeCaches = function (bruteForce) {
  115357. if (this.preventCacheWipeBetweenFrames) {
  115358. return;
  115359. }
  115360. this.resetTextureCache();
  115361. this._currentEffect = null;
  115362. if (bruteForce) {
  115363. this._currentProgram = null;
  115364. this._stencilState.reset();
  115365. this._depthCullingState.reset();
  115366. this._alphaState.reset();
  115367. }
  115368. this._cachedVertexBuffers = null;
  115369. this._cachedIndexBuffer = null;
  115370. this._cachedEffectForVertexBuffers = null;
  115371. };
  115372. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  115373. };
  115374. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  115375. };
  115376. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  115377. };
  115378. /** @hidden */
  115379. NullEngine.prototype._createTexture = function () {
  115380. return {};
  115381. };
  115382. /** @hidden */
  115383. NullEngine.prototype._releaseTexture = function (texture) {
  115384. };
  115385. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  115386. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  115387. if (onLoad === void 0) { onLoad = null; }
  115388. if (onError === void 0) { onError = null; }
  115389. if (buffer === void 0) { buffer = null; }
  115390. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  115391. var url = String(urlArg);
  115392. texture.url = url;
  115393. texture.generateMipMaps = !noMipmap;
  115394. texture.samplingMode = samplingMode;
  115395. texture.invertY = invertY;
  115396. texture.baseWidth = this._options.textureSize;
  115397. texture.baseHeight = this._options.textureSize;
  115398. texture.width = this._options.textureSize;
  115399. texture.height = this._options.textureSize;
  115400. if (format) {
  115401. texture.format = format;
  115402. }
  115403. texture.isReady = true;
  115404. if (onLoad) {
  115405. onLoad();
  115406. }
  115407. this._internalTexturesCache.push(texture);
  115408. return texture;
  115409. };
  115410. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  115411. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  115412. if (options !== undefined && typeof options === "object") {
  115413. fullOptions.generateMipMaps = options.generateMipMaps;
  115414. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  115415. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  115416. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  115417. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  115418. }
  115419. else {
  115420. fullOptions.generateMipMaps = options;
  115421. fullOptions.generateDepthBuffer = true;
  115422. fullOptions.generateStencilBuffer = false;
  115423. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  115424. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  115425. }
  115426. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  115427. var width = size.width || size;
  115428. var height = size.height || size;
  115429. texture._depthStencilBuffer = {};
  115430. texture._framebuffer = {};
  115431. texture.baseWidth = width;
  115432. texture.baseHeight = height;
  115433. texture.width = width;
  115434. texture.height = height;
  115435. texture.isReady = true;
  115436. texture.samples = 1;
  115437. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  115438. texture.samplingMode = fullOptions.samplingMode;
  115439. texture.type = fullOptions.type;
  115440. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  115441. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  115442. this._internalTexturesCache.push(texture);
  115443. return texture;
  115444. };
  115445. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  115446. texture.samplingMode = samplingMode;
  115447. };
  115448. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  115449. if (this._currentRenderTarget) {
  115450. this.unBindFramebuffer(this._currentRenderTarget);
  115451. }
  115452. this._currentRenderTarget = texture;
  115453. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  115454. if (this._cachedViewport && !forceFullscreenViewport) {
  115455. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  115456. }
  115457. };
  115458. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  115459. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  115460. this._currentRenderTarget = null;
  115461. if (onBeforeUnbind) {
  115462. if (texture._MSAAFramebuffer) {
  115463. this._currentFramebuffer = texture._framebuffer;
  115464. }
  115465. onBeforeUnbind();
  115466. }
  115467. this._currentFramebuffer = null;
  115468. };
  115469. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  115470. var vbo = {
  115471. capacity: 1,
  115472. references: 1,
  115473. is32Bits: false
  115474. };
  115475. return vbo;
  115476. };
  115477. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  115478. if (premulAlpha === void 0) { premulAlpha = false; }
  115479. };
  115480. NullEngine.prototype.areAllEffectsReady = function () {
  115481. return true;
  115482. };
  115483. /**
  115484. * @hidden
  115485. * Get the current error code of the webGL context
  115486. * @returns the error code
  115487. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  115488. */
  115489. NullEngine.prototype.getError = function () {
  115490. return 0;
  115491. };
  115492. /** @hidden */
  115493. NullEngine.prototype._getUnpackAlignement = function () {
  115494. return 1;
  115495. };
  115496. /** @hidden */
  115497. NullEngine.prototype._unpackFlipY = function (value) {
  115498. };
  115499. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  115500. if (offset === void 0) { offset = 0; }
  115501. };
  115502. /**
  115503. * Updates a dynamic vertex buffer.
  115504. * @param vertexBuffer the vertex buffer to update
  115505. * @param data the data used to update the vertex buffer
  115506. * @param byteOffset the byte offset of the data (optional)
  115507. * @param byteLength the byte length of the data (optional)
  115508. */
  115509. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  115510. };
  115511. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  115512. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  115513. this._boundTexturesCache[this._activeChannel] = texture;
  115514. return true;
  115515. }
  115516. return false;
  115517. };
  115518. /** @hidden */
  115519. NullEngine.prototype._bindTexture = function (channel, texture) {
  115520. if (channel < 0) {
  115521. return;
  115522. }
  115523. this._bindTextureDirectly(0, texture);
  115524. };
  115525. /** @hidden */
  115526. NullEngine.prototype._releaseBuffer = function (buffer) {
  115527. buffer.references--;
  115528. if (buffer.references === 0) {
  115529. return true;
  115530. }
  115531. return false;
  115532. };
  115533. NullEngine.prototype.releaseEffects = function () {
  115534. };
  115535. NullEngine.prototype.displayLoadingUI = function () {
  115536. };
  115537. NullEngine.prototype.hideLoadingUI = function () {
  115538. };
  115539. /** @hidden */
  115540. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  115541. if (faceIndex === void 0) { faceIndex = 0; }
  115542. if (lod === void 0) { lod = 0; }
  115543. };
  115544. /** @hidden */
  115545. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  115546. if (faceIndex === void 0) { faceIndex = 0; }
  115547. if (lod === void 0) { lod = 0; }
  115548. };
  115549. /** @hidden */
  115550. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  115551. if (faceIndex === void 0) { faceIndex = 0; }
  115552. if (lod === void 0) { lod = 0; }
  115553. };
  115554. /** @hidden */
  115555. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  115556. if (faceIndex === void 0) { faceIndex = 0; }
  115557. if (lod === void 0) { lod = 0; }
  115558. };
  115559. return NullEngine;
  115560. }(BABYLON.Engine));
  115561. BABYLON.NullEngine = NullEngine;
  115562. })(BABYLON || (BABYLON = {}));
  115563. //# sourceMappingURL=babylon.nullEngine.js.map
  115564. var BABYLON;
  115565. (function (BABYLON) {
  115566. /**
  115567. * This class can be used to get instrumentation data from a Babylon engine
  115568. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  115569. */
  115570. var EngineInstrumentation = /** @class */ (function () {
  115571. /**
  115572. * Instantiates a new engine instrumentation.
  115573. * This class can be used to get instrumentation data from a Babylon engine
  115574. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  115575. * @param engine Defines the engine to instrument
  115576. */
  115577. function EngineInstrumentation(
  115578. /**
  115579. * Define the instrumented engine.
  115580. */
  115581. engine) {
  115582. this.engine = engine;
  115583. this._captureGPUFrameTime = false;
  115584. this._gpuFrameTime = new BABYLON.PerfCounter();
  115585. this._captureShaderCompilationTime = false;
  115586. this._shaderCompilationTime = new BABYLON.PerfCounter();
  115587. // Observers
  115588. this._onBeginFrameObserver = null;
  115589. this._onEndFrameObserver = null;
  115590. this._onBeforeShaderCompilationObserver = null;
  115591. this._onAfterShaderCompilationObserver = null;
  115592. }
  115593. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  115594. // Properties
  115595. /**
  115596. * Gets the perf counter used for GPU frame time
  115597. */
  115598. get: function () {
  115599. return this._gpuFrameTime;
  115600. },
  115601. enumerable: true,
  115602. configurable: true
  115603. });
  115604. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  115605. /**
  115606. * Gets the GPU frame time capture status
  115607. */
  115608. get: function () {
  115609. return this._captureGPUFrameTime;
  115610. },
  115611. /**
  115612. * Enable or disable the GPU frame time capture
  115613. */
  115614. set: function (value) {
  115615. var _this = this;
  115616. if (value === this._captureGPUFrameTime) {
  115617. return;
  115618. }
  115619. this._captureGPUFrameTime = value;
  115620. if (value) {
  115621. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  115622. if (!_this._gpuFrameTimeToken) {
  115623. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  115624. }
  115625. });
  115626. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  115627. if (!_this._gpuFrameTimeToken) {
  115628. return;
  115629. }
  115630. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  115631. if (time > -1) {
  115632. _this._gpuFrameTimeToken = null;
  115633. _this._gpuFrameTime.fetchNewFrame();
  115634. _this._gpuFrameTime.addCount(time, true);
  115635. }
  115636. });
  115637. }
  115638. else {
  115639. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  115640. this._onBeginFrameObserver = null;
  115641. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  115642. this._onEndFrameObserver = null;
  115643. }
  115644. },
  115645. enumerable: true,
  115646. configurable: true
  115647. });
  115648. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  115649. /**
  115650. * Gets the perf counter used for shader compilation time
  115651. */
  115652. get: function () {
  115653. return this._shaderCompilationTime;
  115654. },
  115655. enumerable: true,
  115656. configurable: true
  115657. });
  115658. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  115659. /**
  115660. * Gets the shader compilation time capture status
  115661. */
  115662. get: function () {
  115663. return this._captureShaderCompilationTime;
  115664. },
  115665. /**
  115666. * Enable or disable the shader compilation time capture
  115667. */
  115668. set: function (value) {
  115669. var _this = this;
  115670. if (value === this._captureShaderCompilationTime) {
  115671. return;
  115672. }
  115673. this._captureShaderCompilationTime = value;
  115674. if (value) {
  115675. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  115676. _this._shaderCompilationTime.fetchNewFrame();
  115677. _this._shaderCompilationTime.beginMonitoring();
  115678. });
  115679. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  115680. _this._shaderCompilationTime.endMonitoring();
  115681. });
  115682. }
  115683. else {
  115684. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  115685. this._onBeforeShaderCompilationObserver = null;
  115686. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  115687. this._onAfterShaderCompilationObserver = null;
  115688. }
  115689. },
  115690. enumerable: true,
  115691. configurable: true
  115692. });
  115693. /**
  115694. * Dispose and release associated resources.
  115695. */
  115696. EngineInstrumentation.prototype.dispose = function () {
  115697. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  115698. this._onBeginFrameObserver = null;
  115699. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  115700. this._onEndFrameObserver = null;
  115701. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  115702. this._onBeforeShaderCompilationObserver = null;
  115703. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  115704. this._onAfterShaderCompilationObserver = null;
  115705. this.engine = null;
  115706. };
  115707. return EngineInstrumentation;
  115708. }());
  115709. BABYLON.EngineInstrumentation = EngineInstrumentation;
  115710. })(BABYLON || (BABYLON = {}));
  115711. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  115712. var BABYLON;
  115713. (function (BABYLON) {
  115714. /**
  115715. * This class can be used to get instrumentation data from a Babylon engine
  115716. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  115717. */
  115718. var SceneInstrumentation = /** @class */ (function () {
  115719. /**
  115720. * Instantiates a new scene instrumentation.
  115721. * This class can be used to get instrumentation data from a Babylon engine
  115722. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  115723. * @param scene Defines the scene to instrument
  115724. */
  115725. function SceneInstrumentation(
  115726. /**
  115727. * Defines the scene to instrument
  115728. */
  115729. scene) {
  115730. var _this = this;
  115731. this.scene = scene;
  115732. this._captureActiveMeshesEvaluationTime = false;
  115733. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  115734. this._captureRenderTargetsRenderTime = false;
  115735. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  115736. this._captureFrameTime = false;
  115737. this._frameTime = new BABYLON.PerfCounter();
  115738. this._captureRenderTime = false;
  115739. this._renderTime = new BABYLON.PerfCounter();
  115740. this._captureInterFrameTime = false;
  115741. this._interFrameTime = new BABYLON.PerfCounter();
  115742. this._captureParticlesRenderTime = false;
  115743. this._particlesRenderTime = new BABYLON.PerfCounter();
  115744. this._captureSpritesRenderTime = false;
  115745. this._spritesRenderTime = new BABYLON.PerfCounter();
  115746. this._capturePhysicsTime = false;
  115747. this._physicsTime = new BABYLON.PerfCounter();
  115748. this._captureAnimationsTime = false;
  115749. this._animationsTime = new BABYLON.PerfCounter();
  115750. this._captureCameraRenderTime = false;
  115751. this._cameraRenderTime = new BABYLON.PerfCounter();
  115752. // Observers
  115753. this._onBeforeActiveMeshesEvaluationObserver = null;
  115754. this._onAfterActiveMeshesEvaluationObserver = null;
  115755. this._onBeforeRenderTargetsRenderObserver = null;
  115756. this._onAfterRenderTargetsRenderObserver = null;
  115757. this._onAfterRenderObserver = null;
  115758. this._onBeforeDrawPhaseObserver = null;
  115759. this._onAfterDrawPhaseObserver = null;
  115760. this._onBeforeAnimationsObserver = null;
  115761. this._onBeforeParticlesRenderingObserver = null;
  115762. this._onAfterParticlesRenderingObserver = null;
  115763. this._onBeforeSpritesRenderingObserver = null;
  115764. this._onAfterSpritesRenderingObserver = null;
  115765. this._onBeforePhysicsObserver = null;
  115766. this._onAfterPhysicsObserver = null;
  115767. this._onAfterAnimationsObserver = null;
  115768. this._onBeforeCameraRenderObserver = null;
  115769. this._onAfterCameraRenderObserver = null;
  115770. // Before render
  115771. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  115772. if (_this._captureActiveMeshesEvaluationTime) {
  115773. _this._activeMeshesEvaluationTime.fetchNewFrame();
  115774. }
  115775. if (_this._captureRenderTargetsRenderTime) {
  115776. _this._renderTargetsRenderTime.fetchNewFrame();
  115777. }
  115778. if (_this._captureFrameTime) {
  115779. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  115780. _this._frameTime.beginMonitoring();
  115781. }
  115782. if (_this._captureInterFrameTime) {
  115783. _this._interFrameTime.endMonitoring();
  115784. }
  115785. if (_this._captureParticlesRenderTime) {
  115786. _this._particlesRenderTime.fetchNewFrame();
  115787. }
  115788. if (_this._captureSpritesRenderTime) {
  115789. _this._spritesRenderTime.fetchNewFrame();
  115790. }
  115791. if (_this._captureAnimationsTime) {
  115792. _this._animationsTime.beginMonitoring();
  115793. }
  115794. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  115795. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  115796. });
  115797. // After render
  115798. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  115799. if (_this._captureFrameTime) {
  115800. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  115801. _this._frameTime.endMonitoring();
  115802. }
  115803. if (_this._captureRenderTime) {
  115804. _this._renderTime.endMonitoring(false);
  115805. }
  115806. if (_this._captureInterFrameTime) {
  115807. _this._interFrameTime.beginMonitoring();
  115808. }
  115809. });
  115810. }
  115811. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  115812. // Properties
  115813. /**
  115814. * Gets the perf counter used for active meshes evaluation time
  115815. */
  115816. get: function () {
  115817. return this._activeMeshesEvaluationTime;
  115818. },
  115819. enumerable: true,
  115820. configurable: true
  115821. });
  115822. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  115823. /**
  115824. * Gets the active meshes evaluation time capture status
  115825. */
  115826. get: function () {
  115827. return this._captureActiveMeshesEvaluationTime;
  115828. },
  115829. /**
  115830. * Enable or disable the active meshes evaluation time capture
  115831. */
  115832. set: function (value) {
  115833. var _this = this;
  115834. if (value === this._captureActiveMeshesEvaluationTime) {
  115835. return;
  115836. }
  115837. this._captureActiveMeshesEvaluationTime = value;
  115838. if (value) {
  115839. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  115840. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  115841. _this._activeMeshesEvaluationTime.beginMonitoring();
  115842. });
  115843. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  115844. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  115845. _this._activeMeshesEvaluationTime.endMonitoring();
  115846. });
  115847. }
  115848. else {
  115849. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  115850. this._onBeforeActiveMeshesEvaluationObserver = null;
  115851. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  115852. this._onAfterActiveMeshesEvaluationObserver = null;
  115853. }
  115854. },
  115855. enumerable: true,
  115856. configurable: true
  115857. });
  115858. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  115859. /**
  115860. * Gets the perf counter used for render targets render time
  115861. */
  115862. get: function () {
  115863. return this._renderTargetsRenderTime;
  115864. },
  115865. enumerable: true,
  115866. configurable: true
  115867. });
  115868. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  115869. /**
  115870. * Gets the render targets render time capture status
  115871. */
  115872. get: function () {
  115873. return this._captureRenderTargetsRenderTime;
  115874. },
  115875. /**
  115876. * Enable or disable the render targets render time capture
  115877. */
  115878. set: function (value) {
  115879. var _this = this;
  115880. if (value === this._captureRenderTargetsRenderTime) {
  115881. return;
  115882. }
  115883. this._captureRenderTargetsRenderTime = value;
  115884. if (value) {
  115885. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  115886. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  115887. _this._renderTargetsRenderTime.beginMonitoring();
  115888. });
  115889. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  115890. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  115891. _this._renderTargetsRenderTime.endMonitoring(false);
  115892. });
  115893. }
  115894. else {
  115895. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  115896. this._onBeforeRenderTargetsRenderObserver = null;
  115897. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  115898. this._onAfterRenderTargetsRenderObserver = null;
  115899. }
  115900. },
  115901. enumerable: true,
  115902. configurable: true
  115903. });
  115904. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  115905. /**
  115906. * Gets the perf counter used for particles render time
  115907. */
  115908. get: function () {
  115909. return this._particlesRenderTime;
  115910. },
  115911. enumerable: true,
  115912. configurable: true
  115913. });
  115914. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  115915. /**
  115916. * Gets the particles render time capture status
  115917. */
  115918. get: function () {
  115919. return this._captureParticlesRenderTime;
  115920. },
  115921. /**
  115922. * Enable or disable the particles render time capture
  115923. */
  115924. set: function (value) {
  115925. var _this = this;
  115926. if (value === this._captureParticlesRenderTime) {
  115927. return;
  115928. }
  115929. this._captureParticlesRenderTime = value;
  115930. if (value) {
  115931. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  115932. BABYLON.Tools.StartPerformanceCounter("Particles");
  115933. _this._particlesRenderTime.beginMonitoring();
  115934. });
  115935. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  115936. BABYLON.Tools.EndPerformanceCounter("Particles");
  115937. _this._particlesRenderTime.endMonitoring(false);
  115938. });
  115939. }
  115940. else {
  115941. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  115942. this._onBeforeParticlesRenderingObserver = null;
  115943. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  115944. this._onAfterParticlesRenderingObserver = null;
  115945. }
  115946. },
  115947. enumerable: true,
  115948. configurable: true
  115949. });
  115950. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  115951. /**
  115952. * Gets the perf counter used for sprites render time
  115953. */
  115954. get: function () {
  115955. return this._spritesRenderTime;
  115956. },
  115957. enumerable: true,
  115958. configurable: true
  115959. });
  115960. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  115961. /**
  115962. * Gets the sprites render time capture status
  115963. */
  115964. get: function () {
  115965. return this._captureSpritesRenderTime;
  115966. },
  115967. /**
  115968. * Enable or disable the sprites render time capture
  115969. */
  115970. set: function (value) {
  115971. var _this = this;
  115972. if (value === this._captureSpritesRenderTime) {
  115973. return;
  115974. }
  115975. this._captureSpritesRenderTime = value;
  115976. if (!this.scene.spriteManagers) {
  115977. return;
  115978. }
  115979. if (value) {
  115980. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  115981. BABYLON.Tools.StartPerformanceCounter("Sprites");
  115982. _this._spritesRenderTime.beginMonitoring();
  115983. });
  115984. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  115985. BABYLON.Tools.EndPerformanceCounter("Sprites");
  115986. _this._spritesRenderTime.endMonitoring(false);
  115987. });
  115988. }
  115989. else {
  115990. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  115991. this._onBeforeSpritesRenderingObserver = null;
  115992. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  115993. this._onAfterSpritesRenderingObserver = null;
  115994. }
  115995. },
  115996. enumerable: true,
  115997. configurable: true
  115998. });
  115999. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  116000. /**
  116001. * Gets the perf counter used for physics time
  116002. */
  116003. get: function () {
  116004. return this._physicsTime;
  116005. },
  116006. enumerable: true,
  116007. configurable: true
  116008. });
  116009. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  116010. /**
  116011. * Gets the physics time capture status
  116012. */
  116013. get: function () {
  116014. return this._capturePhysicsTime;
  116015. },
  116016. /**
  116017. * Enable or disable the physics time capture
  116018. */
  116019. set: function (value) {
  116020. var _this = this;
  116021. if (value === this._capturePhysicsTime) {
  116022. return;
  116023. }
  116024. if (!this.scene.onBeforePhysicsObservable) {
  116025. return;
  116026. }
  116027. this._capturePhysicsTime = value;
  116028. if (value) {
  116029. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  116030. BABYLON.Tools.StartPerformanceCounter("Physics");
  116031. _this._physicsTime.beginMonitoring();
  116032. });
  116033. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  116034. BABYLON.Tools.EndPerformanceCounter("Physics");
  116035. _this._physicsTime.endMonitoring();
  116036. });
  116037. }
  116038. else {
  116039. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  116040. this._onBeforePhysicsObserver = null;
  116041. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  116042. this._onAfterPhysicsObserver = null;
  116043. }
  116044. },
  116045. enumerable: true,
  116046. configurable: true
  116047. });
  116048. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  116049. /**
  116050. * Gets the perf counter used for animations time
  116051. */
  116052. get: function () {
  116053. return this._animationsTime;
  116054. },
  116055. enumerable: true,
  116056. configurable: true
  116057. });
  116058. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  116059. /**
  116060. * Gets the animations time capture status
  116061. */
  116062. get: function () {
  116063. return this._captureAnimationsTime;
  116064. },
  116065. /**
  116066. * Enable or disable the animations time capture
  116067. */
  116068. set: function (value) {
  116069. var _this = this;
  116070. if (value === this._captureAnimationsTime) {
  116071. return;
  116072. }
  116073. this._captureAnimationsTime = value;
  116074. if (value) {
  116075. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  116076. _this._animationsTime.endMonitoring();
  116077. });
  116078. }
  116079. else {
  116080. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  116081. this._onAfterAnimationsObserver = null;
  116082. }
  116083. },
  116084. enumerable: true,
  116085. configurable: true
  116086. });
  116087. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  116088. /**
  116089. * Gets the perf counter used for frame time capture
  116090. */
  116091. get: function () {
  116092. return this._frameTime;
  116093. },
  116094. enumerable: true,
  116095. configurable: true
  116096. });
  116097. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  116098. /**
  116099. * Gets the frame time capture status
  116100. */
  116101. get: function () {
  116102. return this._captureFrameTime;
  116103. },
  116104. /**
  116105. * Enable or disable the frame time capture
  116106. */
  116107. set: function (value) {
  116108. this._captureFrameTime = value;
  116109. },
  116110. enumerable: true,
  116111. configurable: true
  116112. });
  116113. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  116114. /**
  116115. * Gets the perf counter used for inter-frames time capture
  116116. */
  116117. get: function () {
  116118. return this._interFrameTime;
  116119. },
  116120. enumerable: true,
  116121. configurable: true
  116122. });
  116123. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  116124. /**
  116125. * Gets the inter-frames time capture status
  116126. */
  116127. get: function () {
  116128. return this._captureInterFrameTime;
  116129. },
  116130. /**
  116131. * Enable or disable the inter-frames time capture
  116132. */
  116133. set: function (value) {
  116134. this._captureInterFrameTime = value;
  116135. },
  116136. enumerable: true,
  116137. configurable: true
  116138. });
  116139. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  116140. /**
  116141. * Gets the perf counter used for render time capture
  116142. */
  116143. get: function () {
  116144. return this._renderTime;
  116145. },
  116146. enumerable: true,
  116147. configurable: true
  116148. });
  116149. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  116150. /**
  116151. * Gets the render time capture status
  116152. */
  116153. get: function () {
  116154. return this._captureRenderTime;
  116155. },
  116156. /**
  116157. * Enable or disable the render time capture
  116158. */
  116159. set: function (value) {
  116160. var _this = this;
  116161. if (value === this._captureRenderTime) {
  116162. return;
  116163. }
  116164. this._captureRenderTime = value;
  116165. if (value) {
  116166. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  116167. _this._renderTime.beginMonitoring();
  116168. BABYLON.Tools.StartPerformanceCounter("Main render");
  116169. });
  116170. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  116171. _this._renderTime.endMonitoring(false);
  116172. BABYLON.Tools.EndPerformanceCounter("Main render");
  116173. });
  116174. }
  116175. else {
  116176. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  116177. this._onBeforeDrawPhaseObserver = null;
  116178. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  116179. this._onAfterDrawPhaseObserver = null;
  116180. }
  116181. },
  116182. enumerable: true,
  116183. configurable: true
  116184. });
  116185. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  116186. /**
  116187. * Gets the perf counter used for camera render time capture
  116188. */
  116189. get: function () {
  116190. return this._cameraRenderTime;
  116191. },
  116192. enumerable: true,
  116193. configurable: true
  116194. });
  116195. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  116196. /**
  116197. * Gets the camera render time capture status
  116198. */
  116199. get: function () {
  116200. return this._captureCameraRenderTime;
  116201. },
  116202. /**
  116203. * Enable or disable the camera render time capture
  116204. */
  116205. set: function (value) {
  116206. var _this = this;
  116207. if (value === this._captureCameraRenderTime) {
  116208. return;
  116209. }
  116210. this._captureCameraRenderTime = value;
  116211. if (value) {
  116212. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  116213. _this._cameraRenderTime.beginMonitoring();
  116214. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  116215. });
  116216. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  116217. _this._cameraRenderTime.endMonitoring(false);
  116218. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  116219. });
  116220. }
  116221. else {
  116222. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  116223. this._onBeforeCameraRenderObserver = null;
  116224. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  116225. this._onAfterCameraRenderObserver = null;
  116226. }
  116227. },
  116228. enumerable: true,
  116229. configurable: true
  116230. });
  116231. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  116232. /**
  116233. * Gets the perf counter used for draw calls
  116234. */
  116235. get: function () {
  116236. return this.scene.getEngine()._drawCalls;
  116237. },
  116238. enumerable: true,
  116239. configurable: true
  116240. });
  116241. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  116242. /**
  116243. * Gets the perf counter used for texture collisions
  116244. */
  116245. get: function () {
  116246. return this.scene.getEngine()._textureCollisions;
  116247. },
  116248. enumerable: true,
  116249. configurable: true
  116250. });
  116251. /**
  116252. * Dispose and release associated resources.
  116253. */
  116254. SceneInstrumentation.prototype.dispose = function () {
  116255. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  116256. this._onAfterRenderObserver = null;
  116257. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  116258. this._onBeforeActiveMeshesEvaluationObserver = null;
  116259. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  116260. this._onAfterActiveMeshesEvaluationObserver = null;
  116261. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  116262. this._onBeforeRenderTargetsRenderObserver = null;
  116263. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  116264. this._onAfterRenderTargetsRenderObserver = null;
  116265. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  116266. this._onBeforeAnimationsObserver = null;
  116267. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  116268. this._onBeforeParticlesRenderingObserver = null;
  116269. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  116270. this._onAfterParticlesRenderingObserver = null;
  116271. if (this._onBeforeSpritesRenderingObserver) {
  116272. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  116273. this._onBeforeSpritesRenderingObserver = null;
  116274. }
  116275. if (this._onAfterSpritesRenderingObserver) {
  116276. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  116277. this._onAfterSpritesRenderingObserver = null;
  116278. }
  116279. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  116280. this._onBeforeDrawPhaseObserver = null;
  116281. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  116282. this._onAfterDrawPhaseObserver = null;
  116283. if (this._onBeforePhysicsObserver) {
  116284. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  116285. this._onBeforePhysicsObserver = null;
  116286. }
  116287. if (this._onAfterPhysicsObserver) {
  116288. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  116289. this._onAfterPhysicsObserver = null;
  116290. }
  116291. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  116292. this._onAfterAnimationsObserver = null;
  116293. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  116294. this._onBeforeCameraRenderObserver = null;
  116295. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  116296. this._onAfterCameraRenderObserver = null;
  116297. this.scene = null;
  116298. };
  116299. return SceneInstrumentation;
  116300. }());
  116301. BABYLON.SceneInstrumentation = SceneInstrumentation;
  116302. })(BABYLON || (BABYLON = {}));
  116303. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  116304. var BABYLON;
  116305. (function (BABYLON) {
  116306. /**
  116307. * @hidden
  116308. **/
  116309. var _TimeToken = /** @class */ (function () {
  116310. function _TimeToken() {
  116311. this._timeElapsedQueryEnded = false;
  116312. }
  116313. return _TimeToken;
  116314. }());
  116315. BABYLON._TimeToken = _TimeToken;
  116316. })(BABYLON || (BABYLON = {}));
  116317. //# sourceMappingURL=babylon.timeToken.js.map
  116318. var BABYLON;
  116319. (function (BABYLON) {
  116320. /**
  116321. * Background material defines definition.
  116322. * @hidden Mainly internal Use
  116323. */
  116324. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  116325. __extends(BackgroundMaterialDefines, _super);
  116326. /**
  116327. * Constructor of the defines.
  116328. */
  116329. function BackgroundMaterialDefines() {
  116330. var _this = _super.call(this) || this;
  116331. /**
  116332. * True if the diffuse texture is in use.
  116333. */
  116334. _this.DIFFUSE = false;
  116335. /**
  116336. * The direct UV channel to use.
  116337. */
  116338. _this.DIFFUSEDIRECTUV = 0;
  116339. /**
  116340. * True if the diffuse texture is in gamma space.
  116341. */
  116342. _this.GAMMADIFFUSE = false;
  116343. /**
  116344. * True if the diffuse texture has opacity in the alpha channel.
  116345. */
  116346. _this.DIFFUSEHASALPHA = false;
  116347. /**
  116348. * True if you want the material to fade to transparent at grazing angle.
  116349. */
  116350. _this.OPACITYFRESNEL = false;
  116351. /**
  116352. * True if an extra blur needs to be added in the reflection.
  116353. */
  116354. _this.REFLECTIONBLUR = false;
  116355. /**
  116356. * True if you want the material to fade to reflection at grazing angle.
  116357. */
  116358. _this.REFLECTIONFRESNEL = false;
  116359. /**
  116360. * True if you want the material to falloff as far as you move away from the scene center.
  116361. */
  116362. _this.REFLECTIONFALLOFF = false;
  116363. /**
  116364. * False if the current Webgl implementation does not support the texture lod extension.
  116365. */
  116366. _this.TEXTURELODSUPPORT = false;
  116367. /**
  116368. * True to ensure the data are premultiplied.
  116369. */
  116370. _this.PREMULTIPLYALPHA = false;
  116371. /**
  116372. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  116373. */
  116374. _this.USERGBCOLOR = false;
  116375. /**
  116376. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  116377. * stays aligned with the desired configuration.
  116378. */
  116379. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  116380. /**
  116381. * True to add noise in order to reduce the banding effect.
  116382. */
  116383. _this.NOISE = false;
  116384. /**
  116385. * is the reflection texture in BGR color scheme?
  116386. * Mainly used to solve a bug in ios10 video tag
  116387. */
  116388. _this.REFLECTIONBGR = false;
  116389. _this.IMAGEPROCESSING = false;
  116390. _this.VIGNETTE = false;
  116391. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  116392. _this.VIGNETTEBLENDMODEOPAQUE = false;
  116393. _this.TONEMAPPING = false;
  116394. _this.TONEMAPPING_ACES = false;
  116395. _this.CONTRAST = false;
  116396. _this.COLORCURVES = false;
  116397. _this.COLORGRADING = false;
  116398. _this.COLORGRADING3D = false;
  116399. _this.SAMPLER3DGREENDEPTH = false;
  116400. _this.SAMPLER3DBGRMAP = false;
  116401. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  116402. _this.EXPOSURE = false;
  116403. // Reflection.
  116404. _this.REFLECTION = false;
  116405. _this.REFLECTIONMAP_3D = false;
  116406. _this.REFLECTIONMAP_SPHERICAL = false;
  116407. _this.REFLECTIONMAP_PLANAR = false;
  116408. _this.REFLECTIONMAP_CUBIC = false;
  116409. _this.REFLECTIONMAP_PROJECTION = false;
  116410. _this.REFLECTIONMAP_SKYBOX = false;
  116411. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  116412. _this.REFLECTIONMAP_EXPLICIT = false;
  116413. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  116414. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  116415. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  116416. _this.INVERTCUBICMAP = false;
  116417. _this.REFLECTIONMAP_OPPOSITEZ = false;
  116418. _this.LODINREFLECTIONALPHA = false;
  116419. _this.GAMMAREFLECTION = false;
  116420. _this.RGBDREFLECTION = false;
  116421. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  116422. // Default BJS.
  116423. _this.MAINUV1 = false;
  116424. _this.MAINUV2 = false;
  116425. _this.UV1 = false;
  116426. _this.UV2 = false;
  116427. _this.CLIPPLANE = false;
  116428. _this.CLIPPLANE2 = false;
  116429. _this.CLIPPLANE3 = false;
  116430. _this.CLIPPLANE4 = false;
  116431. _this.POINTSIZE = false;
  116432. _this.FOG = false;
  116433. _this.NORMAL = false;
  116434. _this.NUM_BONE_INFLUENCERS = 0;
  116435. _this.BonesPerMesh = 0;
  116436. _this.INSTANCES = false;
  116437. _this.SHADOWFLOAT = false;
  116438. _this.rebuild();
  116439. return _this;
  116440. }
  116441. return BackgroundMaterialDefines;
  116442. }(BABYLON.MaterialDefines));
  116443. /**
  116444. * Background material used to create an efficient environement around your scene.
  116445. */
  116446. var BackgroundMaterial = /** @class */ (function (_super) {
  116447. __extends(BackgroundMaterial, _super);
  116448. /**
  116449. * Instantiates a Background Material in the given scene
  116450. * @param name The friendly name of the material
  116451. * @param scene The scene to add the material to
  116452. */
  116453. function BackgroundMaterial(name, scene) {
  116454. var _this = _super.call(this, name, scene) || this;
  116455. /**
  116456. * Key light Color (multiply against the environement texture)
  116457. */
  116458. _this.primaryColor = BABYLON.Color3.White();
  116459. _this._primaryColorShadowLevel = 0;
  116460. _this._primaryColorHighlightLevel = 0;
  116461. /**
  116462. * Reflection Texture used in the material.
  116463. * Should be author in a specific way for the best result (refer to the documentation).
  116464. */
  116465. _this.reflectionTexture = null;
  116466. /**
  116467. * Reflection Texture level of blur.
  116468. *
  116469. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  116470. * texture twice.
  116471. */
  116472. _this.reflectionBlur = 0;
  116473. /**
  116474. * Diffuse Texture used in the material.
  116475. * Should be author in a specific way for the best result (refer to the documentation).
  116476. */
  116477. _this.diffuseTexture = null;
  116478. _this._shadowLights = null;
  116479. /**
  116480. * Specify the list of lights casting shadow on the material.
  116481. * All scene shadow lights will be included if null.
  116482. */
  116483. _this.shadowLights = null;
  116484. /**
  116485. * Helps adjusting the shadow to a softer level if required.
  116486. * 0 means black shadows and 1 means no shadows.
  116487. */
  116488. _this.shadowLevel = 0;
  116489. /**
  116490. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  116491. * It is usually zero but might be interesting to modify according to your setup.
  116492. */
  116493. _this.sceneCenter = BABYLON.Vector3.Zero();
  116494. /**
  116495. * This helps specifying that the material is falling off to the sky box at grazing angle.
  116496. * This helps ensuring a nice transition when the camera goes under the ground.
  116497. */
  116498. _this.opacityFresnel = true;
  116499. /**
  116500. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  116501. * This helps adding a mirror texture on the ground.
  116502. */
  116503. _this.reflectionFresnel = false;
  116504. /**
  116505. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  116506. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  116507. */
  116508. _this.reflectionFalloffDistance = 0.0;
  116509. /**
  116510. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  116511. */
  116512. _this.reflectionAmount = 1.0;
  116513. /**
  116514. * This specifies the weight of the reflection at grazing angle.
  116515. */
  116516. _this.reflectionReflectance0 = 0.05;
  116517. /**
  116518. * This specifies the weight of the reflection at a perpendicular point of view.
  116519. */
  116520. _this.reflectionReflectance90 = 0.5;
  116521. /**
  116522. * Helps to directly use the maps channels instead of their level.
  116523. */
  116524. _this.useRGBColor = true;
  116525. /**
  116526. * This helps reducing the banding effect that could occur on the background.
  116527. */
  116528. _this.enableNoise = false;
  116529. _this._fovMultiplier = 1.0;
  116530. /**
  116531. * Enable the FOV adjustment feature controlled by fovMultiplier.
  116532. */
  116533. _this.useEquirectangularFOV = false;
  116534. _this._maxSimultaneousLights = 4;
  116535. /**
  116536. * Number of Simultaneous lights allowed on the material.
  116537. */
  116538. _this.maxSimultaneousLights = 4;
  116539. /**
  116540. * Keep track of the image processing observer to allow dispose and replace.
  116541. */
  116542. _this._imageProcessingObserver = null;
  116543. /**
  116544. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  116545. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  116546. */
  116547. _this.switchToBGR = false;
  116548. // Temp values kept as cache in the material.
  116549. _this._renderTargets = new BABYLON.SmartArray(16);
  116550. _this._reflectionControls = BABYLON.Vector4.Zero();
  116551. _this._white = BABYLON.Color3.White();
  116552. _this._primaryShadowColor = BABYLON.Color3.Black();
  116553. _this._primaryHighlightColor = BABYLON.Color3.Black();
  116554. // Setup the default processing configuration to the scene.
  116555. _this._attachImageProcessingConfiguration(null);
  116556. _this.getRenderTargetTextures = function () {
  116557. _this._renderTargets.reset();
  116558. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  116559. _this._renderTargets.push(_this._diffuseTexture);
  116560. }
  116561. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  116562. _this._renderTargets.push(_this._reflectionTexture);
  116563. }
  116564. return _this._renderTargets;
  116565. };
  116566. return _this;
  116567. }
  116568. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  116569. /**
  116570. * Experimental Internal Use Only.
  116571. *
  116572. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  116573. * This acts as a helper to set the primary color to a more "human friendly" value.
  116574. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  116575. * output color as close as possible from the chosen value.
  116576. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  116577. * part of lighting setup.)
  116578. */
  116579. get: function () {
  116580. return this.__perceptualColor;
  116581. },
  116582. set: function (value) {
  116583. this.__perceptualColor = value;
  116584. this._computePrimaryColorFromPerceptualColor();
  116585. this._markAllSubMeshesAsLightsDirty();
  116586. },
  116587. enumerable: true,
  116588. configurable: true
  116589. });
  116590. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  116591. /**
  116592. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  116593. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  116594. */
  116595. get: function () {
  116596. return this._primaryColorShadowLevel;
  116597. },
  116598. set: function (value) {
  116599. this._primaryColorShadowLevel = value;
  116600. this._computePrimaryColors();
  116601. this._markAllSubMeshesAsLightsDirty();
  116602. },
  116603. enumerable: true,
  116604. configurable: true
  116605. });
  116606. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  116607. /**
  116608. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  116609. * The primary color is used at the level chosen to define what the white area would look.
  116610. */
  116611. get: function () {
  116612. return this._primaryColorHighlightLevel;
  116613. },
  116614. set: function (value) {
  116615. this._primaryColorHighlightLevel = value;
  116616. this._computePrimaryColors();
  116617. this._markAllSubMeshesAsLightsDirty();
  116618. },
  116619. enumerable: true,
  116620. configurable: true
  116621. });
  116622. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  116623. /**
  116624. * Sets the reflection reflectance fresnel values according to the default standard
  116625. * empirically know to work well :-)
  116626. */
  116627. set: function (value) {
  116628. var reflectionWeight = value;
  116629. if (reflectionWeight < 0.5) {
  116630. reflectionWeight = reflectionWeight * 2.0;
  116631. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  116632. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  116633. }
  116634. else {
  116635. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  116636. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  116637. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  116638. }
  116639. },
  116640. enumerable: true,
  116641. configurable: true
  116642. });
  116643. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  116644. /**
  116645. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116646. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  116647. * Recommended to be keep at 1.0 except for special cases.
  116648. */
  116649. get: function () {
  116650. return this._fovMultiplier;
  116651. },
  116652. set: function (value) {
  116653. if (isNaN(value)) {
  116654. value = 1.0;
  116655. }
  116656. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  116657. },
  116658. enumerable: true,
  116659. configurable: true
  116660. });
  116661. /**
  116662. * Attaches a new image processing configuration to the PBR Material.
  116663. * @param configuration (if null the scene configuration will be use)
  116664. */
  116665. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  116666. var _this = this;
  116667. if (configuration === this._imageProcessingConfiguration) {
  116668. return;
  116669. }
  116670. // Detaches observer.
  116671. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  116672. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  116673. }
  116674. // Pick the scene configuration if needed.
  116675. if (!configuration) {
  116676. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  116677. }
  116678. else {
  116679. this._imageProcessingConfiguration = configuration;
  116680. }
  116681. // Attaches observer.
  116682. if (this._imageProcessingConfiguration) {
  116683. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  116684. _this._computePrimaryColorFromPerceptualColor();
  116685. _this._markAllSubMeshesAsImageProcessingDirty();
  116686. });
  116687. }
  116688. };
  116689. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  116690. /**
  116691. * Gets the image processing configuration used either in this material.
  116692. */
  116693. get: function () {
  116694. return this._imageProcessingConfiguration;
  116695. },
  116696. /**
  116697. * Sets the Default image processing configuration used either in the this material.
  116698. *
  116699. * If sets to null, the scene one is in use.
  116700. */
  116701. set: function (value) {
  116702. this._attachImageProcessingConfiguration(value);
  116703. // Ensure the effect will be rebuilt.
  116704. this._markAllSubMeshesAsTexturesDirty();
  116705. },
  116706. enumerable: true,
  116707. configurable: true
  116708. });
  116709. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  116710. /**
  116711. * Gets wether the color curves effect is enabled.
  116712. */
  116713. get: function () {
  116714. return this.imageProcessingConfiguration.colorCurvesEnabled;
  116715. },
  116716. /**
  116717. * Sets wether the color curves effect is enabled.
  116718. */
  116719. set: function (value) {
  116720. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  116721. },
  116722. enumerable: true,
  116723. configurable: true
  116724. });
  116725. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  116726. /**
  116727. * Gets wether the color grading effect is enabled.
  116728. */
  116729. get: function () {
  116730. return this.imageProcessingConfiguration.colorGradingEnabled;
  116731. },
  116732. /**
  116733. * Gets wether the color grading effect is enabled.
  116734. */
  116735. set: function (value) {
  116736. this.imageProcessingConfiguration.colorGradingEnabled = value;
  116737. },
  116738. enumerable: true,
  116739. configurable: true
  116740. });
  116741. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  116742. /**
  116743. * Gets wether tonemapping is enabled or not.
  116744. */
  116745. get: function () {
  116746. return this._imageProcessingConfiguration.toneMappingEnabled;
  116747. },
  116748. /**
  116749. * Sets wether tonemapping is enabled or not
  116750. */
  116751. set: function (value) {
  116752. this._imageProcessingConfiguration.toneMappingEnabled = value;
  116753. },
  116754. enumerable: true,
  116755. configurable: true
  116756. });
  116757. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  116758. /**
  116759. * The camera exposure used on this material.
  116760. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  116761. * This corresponds to a photographic exposure.
  116762. */
  116763. get: function () {
  116764. return this._imageProcessingConfiguration.exposure;
  116765. },
  116766. /**
  116767. * The camera exposure used on this material.
  116768. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  116769. * This corresponds to a photographic exposure.
  116770. */
  116771. set: function (value) {
  116772. this._imageProcessingConfiguration.exposure = value;
  116773. },
  116774. enumerable: true,
  116775. configurable: true
  116776. });
  116777. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  116778. /**
  116779. * Gets The camera contrast used on this material.
  116780. */
  116781. get: function () {
  116782. return this._imageProcessingConfiguration.contrast;
  116783. },
  116784. /**
  116785. * Sets The camera contrast used on this material.
  116786. */
  116787. set: function (value) {
  116788. this._imageProcessingConfiguration.contrast = value;
  116789. },
  116790. enumerable: true,
  116791. configurable: true
  116792. });
  116793. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  116794. /**
  116795. * Gets the Color Grading 2D Lookup Texture.
  116796. */
  116797. get: function () {
  116798. return this._imageProcessingConfiguration.colorGradingTexture;
  116799. },
  116800. /**
  116801. * Sets the Color Grading 2D Lookup Texture.
  116802. */
  116803. set: function (value) {
  116804. this.imageProcessingConfiguration.colorGradingTexture = value;
  116805. },
  116806. enumerable: true,
  116807. configurable: true
  116808. });
  116809. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  116810. /**
  116811. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  116812. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  116813. * 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;
  116814. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  116815. */
  116816. get: function () {
  116817. return this.imageProcessingConfiguration.colorCurves;
  116818. },
  116819. /**
  116820. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  116821. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  116822. * 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;
  116823. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  116824. */
  116825. set: function (value) {
  116826. this.imageProcessingConfiguration.colorCurves = value;
  116827. },
  116828. enumerable: true,
  116829. configurable: true
  116830. });
  116831. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  116832. /**
  116833. * Gets a boolean indicating that current material needs to register RTT
  116834. */
  116835. get: function () {
  116836. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  116837. return true;
  116838. }
  116839. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  116840. return true;
  116841. }
  116842. return false;
  116843. },
  116844. enumerable: true,
  116845. configurable: true
  116846. });
  116847. /**
  116848. * The entire material has been created in order to prevent overdraw.
  116849. * @returns false
  116850. */
  116851. BackgroundMaterial.prototype.needAlphaTesting = function () {
  116852. return true;
  116853. };
  116854. /**
  116855. * The entire material has been created in order to prevent overdraw.
  116856. * @returns true if blending is enable
  116857. */
  116858. BackgroundMaterial.prototype.needAlphaBlending = function () {
  116859. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  116860. };
  116861. /**
  116862. * Checks wether the material is ready to be rendered for a given mesh.
  116863. * @param mesh The mesh to render
  116864. * @param subMesh The submesh to check against
  116865. * @param useInstances Specify wether or not the material is used with instances
  116866. * @returns true if all the dependencies are ready (Textures, Effects...)
  116867. */
  116868. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  116869. var _this = this;
  116870. if (useInstances === void 0) { useInstances = false; }
  116871. if (subMesh.effect && this.isFrozen) {
  116872. if (this._wasPreviouslyReady) {
  116873. return true;
  116874. }
  116875. }
  116876. if (!subMesh._materialDefines) {
  116877. subMesh._materialDefines = new BackgroundMaterialDefines();
  116878. }
  116879. var scene = this.getScene();
  116880. var defines = subMesh._materialDefines;
  116881. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  116882. if (defines._renderId === scene.getRenderId()) {
  116883. return true;
  116884. }
  116885. }
  116886. var engine = scene.getEngine();
  116887. // Lights
  116888. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  116889. defines._needNormals = true;
  116890. // Textures
  116891. if (defines._areTexturesDirty) {
  116892. defines._needUVs = false;
  116893. if (scene.texturesEnabled) {
  116894. if (scene.getEngine().getCaps().textureLOD) {
  116895. defines.TEXTURELODSUPPORT = true;
  116896. }
  116897. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  116898. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  116899. return false;
  116900. }
  116901. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  116902. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  116903. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  116904. defines.OPACITYFRESNEL = this._opacityFresnel;
  116905. }
  116906. else {
  116907. defines.DIFFUSE = false;
  116908. defines.DIFFUSEHASALPHA = false;
  116909. defines.GAMMADIFFUSE = false;
  116910. defines.OPACITYFRESNEL = false;
  116911. }
  116912. var reflectionTexture = this._reflectionTexture;
  116913. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  116914. if (!reflectionTexture.isReadyOrNotBlocking()) {
  116915. return false;
  116916. }
  116917. defines.REFLECTION = true;
  116918. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  116919. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  116920. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  116921. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  116922. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  116923. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  116924. defines.REFLECTIONBGR = this.switchToBGR;
  116925. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  116926. defines.INVERTCUBICMAP = true;
  116927. }
  116928. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  116929. switch (reflectionTexture.coordinatesMode) {
  116930. case BABYLON.Texture.EXPLICIT_MODE:
  116931. defines.REFLECTIONMAP_EXPLICIT = true;
  116932. break;
  116933. case BABYLON.Texture.PLANAR_MODE:
  116934. defines.REFLECTIONMAP_PLANAR = true;
  116935. break;
  116936. case BABYLON.Texture.PROJECTION_MODE:
  116937. defines.REFLECTIONMAP_PROJECTION = true;
  116938. break;
  116939. case BABYLON.Texture.SKYBOX_MODE:
  116940. defines.REFLECTIONMAP_SKYBOX = true;
  116941. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  116942. break;
  116943. case BABYLON.Texture.SPHERICAL_MODE:
  116944. defines.REFLECTIONMAP_SPHERICAL = true;
  116945. break;
  116946. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  116947. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  116948. break;
  116949. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  116950. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  116951. break;
  116952. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  116953. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  116954. break;
  116955. case BABYLON.Texture.CUBIC_MODE:
  116956. case BABYLON.Texture.INVCUBIC_MODE:
  116957. default:
  116958. defines.REFLECTIONMAP_CUBIC = true;
  116959. break;
  116960. }
  116961. if (this.reflectionFresnel) {
  116962. defines.REFLECTIONFRESNEL = true;
  116963. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  116964. this._reflectionControls.x = this.reflectionAmount;
  116965. this._reflectionControls.y = this.reflectionReflectance0;
  116966. this._reflectionControls.z = this.reflectionReflectance90;
  116967. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  116968. }
  116969. else {
  116970. defines.REFLECTIONFRESNEL = false;
  116971. defines.REFLECTIONFALLOFF = false;
  116972. }
  116973. }
  116974. else {
  116975. defines.REFLECTION = false;
  116976. defines.REFLECTIONFRESNEL = false;
  116977. defines.REFLECTIONFALLOFF = false;
  116978. defines.REFLECTIONBLUR = false;
  116979. defines.REFLECTIONMAP_3D = false;
  116980. defines.REFLECTIONMAP_SPHERICAL = false;
  116981. defines.REFLECTIONMAP_PLANAR = false;
  116982. defines.REFLECTIONMAP_CUBIC = false;
  116983. defines.REFLECTIONMAP_PROJECTION = false;
  116984. defines.REFLECTIONMAP_SKYBOX = false;
  116985. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  116986. defines.REFLECTIONMAP_EXPLICIT = false;
  116987. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  116988. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  116989. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  116990. defines.INVERTCUBICMAP = false;
  116991. defines.REFLECTIONMAP_OPPOSITEZ = false;
  116992. defines.LODINREFLECTIONALPHA = false;
  116993. defines.GAMMAREFLECTION = false;
  116994. defines.RGBDREFLECTION = false;
  116995. }
  116996. }
  116997. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  116998. defines.USERGBCOLOR = this._useRGBColor;
  116999. defines.NOISE = this._enableNoise;
  117000. }
  117001. if (defines._areLightsDirty) {
  117002. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  117003. }
  117004. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  117005. if (!this._imageProcessingConfiguration.isReady()) {
  117006. return false;
  117007. }
  117008. this._imageProcessingConfiguration.prepareDefines(defines);
  117009. }
  117010. // Misc.
  117011. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  117012. // Values that need to be evaluated on every frame
  117013. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  117014. // Attribs
  117015. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  117016. if (mesh) {
  117017. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  117018. mesh.createNormals(true);
  117019. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  117020. }
  117021. }
  117022. }
  117023. // Get correct effect
  117024. if (defines.isDirty) {
  117025. defines.markAsProcessed();
  117026. scene.resetCachedMaterial();
  117027. // Fallbacks
  117028. var fallbacks = new BABYLON.EffectFallbacks();
  117029. if (defines.FOG) {
  117030. fallbacks.addFallback(0, "FOG");
  117031. }
  117032. if (defines.POINTSIZE) {
  117033. fallbacks.addFallback(1, "POINTSIZE");
  117034. }
  117035. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  117036. if (defines.NUM_BONE_INFLUENCERS > 0) {
  117037. fallbacks.addCPUSkinningFallback(0, mesh);
  117038. }
  117039. //Attributes
  117040. var attribs = [BABYLON.VertexBuffer.PositionKind];
  117041. if (defines.NORMAL) {
  117042. attribs.push(BABYLON.VertexBuffer.NormalKind);
  117043. }
  117044. if (defines.UV1) {
  117045. attribs.push(BABYLON.VertexBuffer.UVKind);
  117046. }
  117047. if (defines.UV2) {
  117048. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  117049. }
  117050. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  117051. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  117052. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  117053. "vFogInfos", "vFogColor", "pointSize",
  117054. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  117055. "vPrimaryColor", "vPrimaryColorShadow",
  117056. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  117057. "shadowLevel", "alpha",
  117058. "vBackgroundCenter", "vReflectionControl",
  117059. "vDiffuseInfos", "diffuseMatrix",
  117060. ];
  117061. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  117062. var uniformBuffers = ["Material", "Scene"];
  117063. if (BABYLON.ImageProcessingConfiguration) {
  117064. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  117065. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  117066. }
  117067. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  117068. uniformsNames: uniforms,
  117069. uniformBuffersNames: uniformBuffers,
  117070. samplers: samplers,
  117071. defines: defines,
  117072. maxSimultaneousLights: this._maxSimultaneousLights
  117073. });
  117074. var onCompiled = function (effect) {
  117075. if (_this.onCompiled) {
  117076. _this.onCompiled(effect);
  117077. }
  117078. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  117079. };
  117080. var join = defines.toString();
  117081. subMesh.setEffect(scene.getEngine().createEffect("background", {
  117082. attributes: attribs,
  117083. uniformsNames: uniforms,
  117084. uniformBuffersNames: uniformBuffers,
  117085. samplers: samplers,
  117086. defines: join,
  117087. fallbacks: fallbacks,
  117088. onCompiled: onCompiled,
  117089. onError: this.onError,
  117090. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  117091. }, engine), defines);
  117092. this.buildUniformLayout();
  117093. }
  117094. if (!subMesh.effect || !subMesh.effect.isReady()) {
  117095. return false;
  117096. }
  117097. defines._renderId = scene.getRenderId();
  117098. this._wasPreviouslyReady = true;
  117099. return true;
  117100. };
  117101. /**
  117102. * Compute the primary color according to the chosen perceptual color.
  117103. */
  117104. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  117105. if (!this.__perceptualColor) {
  117106. return;
  117107. }
  117108. this._primaryColor.copyFrom(this.__perceptualColor);
  117109. // Revert gamma space.
  117110. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  117111. // Revert image processing configuration.
  117112. if (this._imageProcessingConfiguration) {
  117113. // Revert Exposure.
  117114. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  117115. }
  117116. this._computePrimaryColors();
  117117. };
  117118. /**
  117119. * Compute the highlights and shadow colors according to their chosen levels.
  117120. */
  117121. BackgroundMaterial.prototype._computePrimaryColors = function () {
  117122. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  117123. return;
  117124. }
  117125. // Find the highlight color based on the configuration.
  117126. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  117127. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  117128. // Find the shadow color based on the configuration.
  117129. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  117130. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  117131. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  117132. };
  117133. /**
  117134. * Build the uniform buffer used in the material.
  117135. */
  117136. BackgroundMaterial.prototype.buildUniformLayout = function () {
  117137. // Order is important !
  117138. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  117139. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  117140. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  117141. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  117142. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  117143. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  117144. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  117145. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  117146. this._uniformBuffer.addUniform("pointSize", 1);
  117147. this._uniformBuffer.addUniform("shadowLevel", 1);
  117148. this._uniformBuffer.addUniform("alpha", 1);
  117149. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  117150. this._uniformBuffer.addUniform("vReflectionControl", 4);
  117151. this._uniformBuffer.create();
  117152. };
  117153. /**
  117154. * Unbind the material.
  117155. */
  117156. BackgroundMaterial.prototype.unbind = function () {
  117157. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  117158. this._uniformBuffer.setTexture("diffuseSampler", null);
  117159. }
  117160. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  117161. this._uniformBuffer.setTexture("reflectionSampler", null);
  117162. }
  117163. _super.prototype.unbind.call(this);
  117164. };
  117165. /**
  117166. * Bind only the world matrix to the material.
  117167. * @param world The world matrix to bind.
  117168. */
  117169. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  117170. this._activeEffect.setMatrix("world", world);
  117171. };
  117172. /**
  117173. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  117174. * @param world The world matrix to bind.
  117175. * @param subMesh The submesh to bind for.
  117176. */
  117177. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  117178. var scene = this.getScene();
  117179. var defines = subMesh._materialDefines;
  117180. if (!defines) {
  117181. return;
  117182. }
  117183. var effect = subMesh.effect;
  117184. if (!effect) {
  117185. return;
  117186. }
  117187. this._activeEffect = effect;
  117188. // Matrices
  117189. this.bindOnlyWorldMatrix(world);
  117190. // Bones
  117191. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  117192. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  117193. if (mustRebind) {
  117194. this._uniformBuffer.bindToEffect(effect, "Material");
  117195. this.bindViewProjection(effect);
  117196. var reflectionTexture = this._reflectionTexture;
  117197. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  117198. // Texture uniforms
  117199. if (scene.texturesEnabled) {
  117200. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  117201. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  117202. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  117203. }
  117204. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  117205. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  117206. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  117207. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  117208. }
  117209. }
  117210. if (this.shadowLevel > 0) {
  117211. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  117212. }
  117213. this._uniformBuffer.updateFloat("alpha", this.alpha);
  117214. // Point size
  117215. if (this.pointsCloud) {
  117216. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  117217. }
  117218. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  117219. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  117220. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  117221. }
  117222. else {
  117223. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  117224. }
  117225. }
  117226. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  117227. // Textures
  117228. if (scene.texturesEnabled) {
  117229. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  117230. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  117231. }
  117232. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  117233. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  117234. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  117235. }
  117236. else if (!defines.REFLECTIONBLUR) {
  117237. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  117238. }
  117239. else {
  117240. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  117241. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  117242. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  117243. }
  117244. if (defines.REFLECTIONFRESNEL) {
  117245. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  117246. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  117247. }
  117248. }
  117249. }
  117250. // Clip plane
  117251. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  117252. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  117253. }
  117254. if (mustRebind || !this.isFrozen) {
  117255. if (scene.lightsEnabled) {
  117256. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  117257. }
  117258. // View
  117259. this.bindView(effect);
  117260. // Fog
  117261. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  117262. // image processing
  117263. if (this._imageProcessingConfiguration) {
  117264. this._imageProcessingConfiguration.bind(this._activeEffect);
  117265. }
  117266. }
  117267. this._uniformBuffer.update();
  117268. this._afterBind(mesh, this._activeEffect);
  117269. };
  117270. /**
  117271. * Dispose the material.
  117272. * @param forceDisposeEffect Force disposal of the associated effect.
  117273. * @param forceDisposeTextures Force disposal of the associated textures.
  117274. */
  117275. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  117276. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  117277. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  117278. if (forceDisposeTextures) {
  117279. if (this.diffuseTexture) {
  117280. this.diffuseTexture.dispose();
  117281. }
  117282. if (this.reflectionTexture) {
  117283. this.reflectionTexture.dispose();
  117284. }
  117285. }
  117286. this._renderTargets.dispose();
  117287. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  117288. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  117289. }
  117290. _super.prototype.dispose.call(this, forceDisposeEffect);
  117291. };
  117292. /**
  117293. * Clones the material.
  117294. * @param name The cloned name.
  117295. * @returns The cloned material.
  117296. */
  117297. BackgroundMaterial.prototype.clone = function (name) {
  117298. var _this = this;
  117299. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  117300. };
  117301. /**
  117302. * Serializes the current material to its JSON representation.
  117303. * @returns The JSON representation.
  117304. */
  117305. BackgroundMaterial.prototype.serialize = function () {
  117306. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  117307. serializationObject.customType = "BABYLON.BackgroundMaterial";
  117308. return serializationObject;
  117309. };
  117310. /**
  117311. * Gets the class name of the material
  117312. * @returns "BackgroundMaterial"
  117313. */
  117314. BackgroundMaterial.prototype.getClassName = function () {
  117315. return "BackgroundMaterial";
  117316. };
  117317. /**
  117318. * Parse a JSON input to create back a background material.
  117319. * @param source The JSON data to parse
  117320. * @param scene The scene to create the parsed material in
  117321. * @param rootUrl The root url of the assets the material depends upon
  117322. * @returns the instantiated BackgroundMaterial.
  117323. */
  117324. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  117325. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  117326. };
  117327. /**
  117328. * Standard reflectance value at parallel view angle.
  117329. */
  117330. BackgroundMaterial.StandardReflectance0 = 0.05;
  117331. /**
  117332. * Standard reflectance value at grazing angle.
  117333. */
  117334. BackgroundMaterial.StandardReflectance90 = 0.5;
  117335. __decorate([
  117336. BABYLON.serializeAsColor3()
  117337. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  117338. __decorate([
  117339. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  117340. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  117341. __decorate([
  117342. BABYLON.serializeAsColor3()
  117343. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  117344. __decorate([
  117345. BABYLON.serialize()
  117346. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  117347. __decorate([
  117348. BABYLON.serialize()
  117349. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  117350. __decorate([
  117351. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  117352. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  117353. __decorate([
  117354. BABYLON.serializeAsTexture()
  117355. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  117356. __decorate([
  117357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117358. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  117359. __decorate([
  117360. BABYLON.serialize()
  117361. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  117362. __decorate([
  117363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117364. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  117365. __decorate([
  117366. BABYLON.serializeAsTexture()
  117367. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  117368. __decorate([
  117369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117370. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  117371. __decorate([
  117372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117373. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  117374. __decorate([
  117375. BABYLON.serialize()
  117376. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  117377. __decorate([
  117378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117379. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  117380. __decorate([
  117381. BABYLON.serializeAsVector3()
  117382. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  117383. __decorate([
  117384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117385. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  117386. __decorate([
  117387. BABYLON.serialize()
  117388. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  117389. __decorate([
  117390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117391. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  117392. __decorate([
  117393. BABYLON.serialize()
  117394. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  117395. __decorate([
  117396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117397. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  117398. __decorate([
  117399. BABYLON.serialize()
  117400. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  117401. __decorate([
  117402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117403. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  117404. __decorate([
  117405. BABYLON.serialize()
  117406. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  117407. __decorate([
  117408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117409. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  117410. __decorate([
  117411. BABYLON.serialize()
  117412. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  117413. __decorate([
  117414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117415. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  117416. __decorate([
  117417. BABYLON.serialize()
  117418. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  117419. __decorate([
  117420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117421. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  117422. __decorate([
  117423. BABYLON.serialize()
  117424. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  117425. __decorate([
  117426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117427. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  117428. __decorate([
  117429. BABYLON.serialize()
  117430. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  117431. __decorate([
  117432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117433. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  117434. __decorate([
  117435. BABYLON.serialize()
  117436. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  117437. __decorate([
  117438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117439. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  117440. __decorate([
  117441. BABYLON.serializeAsImageProcessingConfiguration()
  117442. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  117443. return BackgroundMaterial;
  117444. }(BABYLON.PushMaterial));
  117445. BABYLON.BackgroundMaterial = BackgroundMaterial;
  117446. })(BABYLON || (BABYLON = {}));
  117447. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  117448. var __assign = (this && this.__assign) || function () {
  117449. __assign = Object.assign || function(t) {
  117450. for (var s, i = 1, n = arguments.length; i < n; i++) {
  117451. s = arguments[i];
  117452. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  117453. t[p] = s[p];
  117454. }
  117455. return t;
  117456. };
  117457. return __assign.apply(this, arguments);
  117458. };
  117459. var BABYLON;
  117460. (function (BABYLON) {
  117461. /**
  117462. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  117463. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  117464. * It also helps with the default setup of your imageProcessing configuration.
  117465. */
  117466. var EnvironmentHelper = /** @class */ (function () {
  117467. /**
  117468. * constructor
  117469. * @param options
  117470. * @param scene The scene to add the material to
  117471. */
  117472. function EnvironmentHelper(options, scene) {
  117473. var _this = this;
  117474. this._errorHandler = function (message, exception) {
  117475. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  117476. };
  117477. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  117478. this._scene = scene;
  117479. this.onErrorObservable = new BABYLON.Observable();
  117480. this._setupBackground();
  117481. this._setupImageProcessing();
  117482. }
  117483. /**
  117484. * Creates the default options for the helper.
  117485. */
  117486. EnvironmentHelper._getDefaultOptions = function () {
  117487. return {
  117488. createGround: true,
  117489. groundSize: 15,
  117490. groundTexture: this._groundTextureCDNUrl,
  117491. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  117492. groundOpacity: 0.9,
  117493. enableGroundShadow: true,
  117494. groundShadowLevel: 0.5,
  117495. enableGroundMirror: false,
  117496. groundMirrorSizeRatio: 0.3,
  117497. groundMirrorBlurKernel: 64,
  117498. groundMirrorAmount: 1,
  117499. groundMirrorFresnelWeight: 1,
  117500. groundMirrorFallOffDistance: 0,
  117501. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  117502. groundYBias: 0.00001,
  117503. createSkybox: true,
  117504. skyboxSize: 20,
  117505. skyboxTexture: this._skyboxTextureCDNUrl,
  117506. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  117507. backgroundYRotation: 0,
  117508. sizeAuto: true,
  117509. rootPosition: BABYLON.Vector3.Zero(),
  117510. setupImageProcessing: true,
  117511. environmentTexture: this._environmentTextureCDNUrl,
  117512. cameraExposure: 0.8,
  117513. cameraContrast: 1.2,
  117514. toneMappingEnabled: true,
  117515. };
  117516. };
  117517. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  117518. /**
  117519. * Gets the root mesh created by the helper.
  117520. */
  117521. get: function () {
  117522. return this._rootMesh;
  117523. },
  117524. enumerable: true,
  117525. configurable: true
  117526. });
  117527. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  117528. /**
  117529. * Gets the skybox created by the helper.
  117530. */
  117531. get: function () {
  117532. return this._skybox;
  117533. },
  117534. enumerable: true,
  117535. configurable: true
  117536. });
  117537. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  117538. /**
  117539. * Gets the skybox texture created by the helper.
  117540. */
  117541. get: function () {
  117542. return this._skyboxTexture;
  117543. },
  117544. enumerable: true,
  117545. configurable: true
  117546. });
  117547. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  117548. /**
  117549. * Gets the skybox material created by the helper.
  117550. */
  117551. get: function () {
  117552. return this._skyboxMaterial;
  117553. },
  117554. enumerable: true,
  117555. configurable: true
  117556. });
  117557. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  117558. /**
  117559. * Gets the ground mesh created by the helper.
  117560. */
  117561. get: function () {
  117562. return this._ground;
  117563. },
  117564. enumerable: true,
  117565. configurable: true
  117566. });
  117567. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  117568. /**
  117569. * Gets the ground texture created by the helper.
  117570. */
  117571. get: function () {
  117572. return this._groundTexture;
  117573. },
  117574. enumerable: true,
  117575. configurable: true
  117576. });
  117577. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  117578. /**
  117579. * Gets the ground mirror created by the helper.
  117580. */
  117581. get: function () {
  117582. return this._groundMirror;
  117583. },
  117584. enumerable: true,
  117585. configurable: true
  117586. });
  117587. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  117588. /**
  117589. * Gets the ground mirror render list to helps pushing the meshes
  117590. * you wish in the ground reflection.
  117591. */
  117592. get: function () {
  117593. if (this._groundMirror) {
  117594. return this._groundMirror.renderList;
  117595. }
  117596. return null;
  117597. },
  117598. enumerable: true,
  117599. configurable: true
  117600. });
  117601. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  117602. /**
  117603. * Gets the ground material created by the helper.
  117604. */
  117605. get: function () {
  117606. return this._groundMaterial;
  117607. },
  117608. enumerable: true,
  117609. configurable: true
  117610. });
  117611. /**
  117612. * Updates the background according to the new options
  117613. * @param options
  117614. */
  117615. EnvironmentHelper.prototype.updateOptions = function (options) {
  117616. var newOptions = __assign({}, this._options, options);
  117617. if (this._ground && !newOptions.createGround) {
  117618. this._ground.dispose();
  117619. this._ground = null;
  117620. }
  117621. if (this._groundMaterial && !newOptions.createGround) {
  117622. this._groundMaterial.dispose();
  117623. this._groundMaterial = null;
  117624. }
  117625. if (this._groundTexture) {
  117626. if (this._options.groundTexture != newOptions.groundTexture) {
  117627. this._groundTexture.dispose();
  117628. this._groundTexture = null;
  117629. }
  117630. }
  117631. if (this._skybox && !newOptions.createSkybox) {
  117632. this._skybox.dispose();
  117633. this._skybox = null;
  117634. }
  117635. if (this._skyboxMaterial && !newOptions.createSkybox) {
  117636. this._skyboxMaterial.dispose();
  117637. this._skyboxMaterial = null;
  117638. }
  117639. if (this._skyboxTexture) {
  117640. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  117641. this._skyboxTexture.dispose();
  117642. this._skyboxTexture = null;
  117643. }
  117644. }
  117645. if (this._groundMirror && !newOptions.enableGroundMirror) {
  117646. this._groundMirror.dispose();
  117647. this._groundMirror = null;
  117648. }
  117649. if (this._scene.environmentTexture) {
  117650. if (this._options.environmentTexture != newOptions.environmentTexture) {
  117651. this._scene.environmentTexture.dispose();
  117652. }
  117653. }
  117654. this._options = newOptions;
  117655. this._setupBackground();
  117656. this._setupImageProcessing();
  117657. };
  117658. /**
  117659. * Sets the primary color of all the available elements.
  117660. * @param color the main color to affect to the ground and the background
  117661. */
  117662. EnvironmentHelper.prototype.setMainColor = function (color) {
  117663. if (this.groundMaterial) {
  117664. this.groundMaterial.primaryColor = color;
  117665. }
  117666. if (this.skyboxMaterial) {
  117667. this.skyboxMaterial.primaryColor = color;
  117668. }
  117669. if (this.groundMirror) {
  117670. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  117671. }
  117672. };
  117673. /**
  117674. * Setup the image processing according to the specified options.
  117675. */
  117676. EnvironmentHelper.prototype._setupImageProcessing = function () {
  117677. if (this._options.setupImageProcessing) {
  117678. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  117679. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  117680. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  117681. this._setupEnvironmentTexture();
  117682. }
  117683. };
  117684. /**
  117685. * Setup the environment texture according to the specified options.
  117686. */
  117687. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  117688. if (this._scene.environmentTexture) {
  117689. return;
  117690. }
  117691. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  117692. this._scene.environmentTexture = this._options.environmentTexture;
  117693. return;
  117694. }
  117695. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  117696. this._scene.environmentTexture = environmentTexture;
  117697. };
  117698. /**
  117699. * Setup the background according to the specified options.
  117700. */
  117701. EnvironmentHelper.prototype._setupBackground = function () {
  117702. if (!this._rootMesh) {
  117703. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  117704. }
  117705. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  117706. var sceneSize = this._getSceneSize();
  117707. if (this._options.createGround) {
  117708. this._setupGround(sceneSize);
  117709. this._setupGroundMaterial();
  117710. this._setupGroundDiffuseTexture();
  117711. if (this._options.enableGroundMirror) {
  117712. this._setupGroundMirrorTexture(sceneSize);
  117713. }
  117714. this._setupMirrorInGroundMaterial();
  117715. }
  117716. if (this._options.createSkybox) {
  117717. this._setupSkybox(sceneSize);
  117718. this._setupSkyboxMaterial();
  117719. this._setupSkyboxReflectionTexture();
  117720. }
  117721. this._rootMesh.position.x = sceneSize.rootPosition.x;
  117722. this._rootMesh.position.z = sceneSize.rootPosition.z;
  117723. this._rootMesh.position.y = sceneSize.rootPosition.y;
  117724. };
  117725. /**
  117726. * Get the scene sizes according to the setup.
  117727. */
  117728. EnvironmentHelper.prototype._getSceneSize = function () {
  117729. var _this = this;
  117730. var groundSize = this._options.groundSize;
  117731. var skyboxSize = this._options.skyboxSize;
  117732. var rootPosition = this._options.rootPosition;
  117733. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  117734. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  117735. }
  117736. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  117737. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  117738. });
  117739. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  117740. if (this._options.sizeAuto) {
  117741. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  117742. this._scene.activeCamera.upperRadiusLimit) {
  117743. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  117744. skyboxSize = groundSize;
  117745. }
  117746. var sceneDiagonalLenght = sceneDiagonal.length();
  117747. if (sceneDiagonalLenght > groundSize) {
  117748. groundSize = sceneDiagonalLenght * 2;
  117749. skyboxSize = groundSize;
  117750. }
  117751. // 10 % bigger.
  117752. groundSize *= 1.1;
  117753. skyboxSize *= 1.5;
  117754. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  117755. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  117756. }
  117757. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  117758. };
  117759. /**
  117760. * Setup the ground according to the specified options.
  117761. */
  117762. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  117763. var _this = this;
  117764. if (!this._ground || this._ground.isDisposed()) {
  117765. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  117766. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  117767. this._ground.parent = this._rootMesh;
  117768. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  117769. }
  117770. this._ground.receiveShadows = this._options.enableGroundShadow;
  117771. };
  117772. /**
  117773. * Setup the ground material according to the specified options.
  117774. */
  117775. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  117776. if (!this._groundMaterial) {
  117777. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  117778. }
  117779. this._groundMaterial.alpha = this._options.groundOpacity;
  117780. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  117781. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  117782. this._groundMaterial.primaryColor = this._options.groundColor;
  117783. this._groundMaterial.useRGBColor = false;
  117784. this._groundMaterial.enableNoise = true;
  117785. if (this._ground) {
  117786. this._ground.material = this._groundMaterial;
  117787. }
  117788. };
  117789. /**
  117790. * Setup the ground diffuse texture according to the specified options.
  117791. */
  117792. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  117793. if (!this._groundMaterial) {
  117794. return;
  117795. }
  117796. if (this._groundTexture) {
  117797. return;
  117798. }
  117799. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  117800. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  117801. return;
  117802. }
  117803. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  117804. diffuseTexture.gammaSpace = false;
  117805. diffuseTexture.hasAlpha = true;
  117806. this._groundMaterial.diffuseTexture = diffuseTexture;
  117807. };
  117808. /**
  117809. * Setup the ground mirror texture according to the specified options.
  117810. */
  117811. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  117812. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117813. if (!this._groundMirror) {
  117814. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  117815. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  117816. this._groundMirror.anisotropicFilteringLevel = 1;
  117817. this._groundMirror.wrapU = wrapping;
  117818. this._groundMirror.wrapV = wrapping;
  117819. this._groundMirror.gammaSpace = false;
  117820. if (this._groundMirror.renderList) {
  117821. for (var i = 0; i < this._scene.meshes.length; i++) {
  117822. var mesh = this._scene.meshes[i];
  117823. if (mesh !== this._ground &&
  117824. mesh !== this._skybox &&
  117825. mesh !== this._rootMesh) {
  117826. this._groundMirror.renderList.push(mesh);
  117827. }
  117828. }
  117829. }
  117830. }
  117831. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  117832. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  117833. };
  117834. /**
  117835. * Setup the ground to receive the mirror texture.
  117836. */
  117837. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  117838. if (this._groundMaterial) {
  117839. this._groundMaterial.reflectionTexture = this._groundMirror;
  117840. this._groundMaterial.reflectionFresnel = true;
  117841. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  117842. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  117843. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  117844. }
  117845. };
  117846. /**
  117847. * Setup the skybox according to the specified options.
  117848. */
  117849. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  117850. var _this = this;
  117851. if (!this._skybox || this._skybox.isDisposed()) {
  117852. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  117853. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  117854. }
  117855. this._skybox.parent = this._rootMesh;
  117856. };
  117857. /**
  117858. * Setup the skybox material according to the specified options.
  117859. */
  117860. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  117861. if (!this._skybox) {
  117862. return;
  117863. }
  117864. if (!this._skyboxMaterial) {
  117865. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  117866. }
  117867. this._skyboxMaterial.useRGBColor = false;
  117868. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  117869. this._skyboxMaterial.enableNoise = true;
  117870. this._skybox.material = this._skyboxMaterial;
  117871. };
  117872. /**
  117873. * Setup the skybox reflection texture according to the specified options.
  117874. */
  117875. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  117876. if (!this._skyboxMaterial) {
  117877. return;
  117878. }
  117879. if (this._skyboxTexture) {
  117880. return;
  117881. }
  117882. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  117883. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  117884. return;
  117885. }
  117886. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  117887. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  117888. this._skyboxTexture.gammaSpace = false;
  117889. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  117890. };
  117891. /**
  117892. * Dispose all the elements created by the Helper.
  117893. */
  117894. EnvironmentHelper.prototype.dispose = function () {
  117895. if (this._groundMaterial) {
  117896. this._groundMaterial.dispose(true, true);
  117897. }
  117898. if (this._skyboxMaterial) {
  117899. this._skyboxMaterial.dispose(true, true);
  117900. }
  117901. this._rootMesh.dispose(false);
  117902. };
  117903. /**
  117904. * Default ground texture URL.
  117905. */
  117906. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  117907. /**
  117908. * Default skybox texture URL.
  117909. */
  117910. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  117911. /**
  117912. * Default environment texture URL.
  117913. */
  117914. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  117915. return EnvironmentHelper;
  117916. }());
  117917. BABYLON.EnvironmentHelper = EnvironmentHelper;
  117918. })(BABYLON || (BABYLON = {}));
  117919. //# sourceMappingURL=babylon.environmentHelper.js.map
  117920. var BABYLON;
  117921. (function (BABYLON) {
  117922. /** Internal class used to store shapes for emitters */
  117923. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  117924. function ParticleSystemSetEmitterCreationOptions() {
  117925. }
  117926. return ParticleSystemSetEmitterCreationOptions;
  117927. }());
  117928. /**
  117929. * Represents a set of particle systems working together to create a specific effect
  117930. */
  117931. var ParticleSystemSet = /** @class */ (function () {
  117932. function ParticleSystemSet() {
  117933. /**
  117934. * Gets the particle system list
  117935. */
  117936. this.systems = new Array();
  117937. }
  117938. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  117939. /**
  117940. * Gets the emitter node used with this set
  117941. */
  117942. get: function () {
  117943. return this._emitterNode;
  117944. },
  117945. enumerable: true,
  117946. configurable: true
  117947. });
  117948. /**
  117949. * Creates a new emitter mesh as a sphere
  117950. * @param options defines the options used to create the sphere
  117951. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  117952. * @param scene defines the hosting scene
  117953. */
  117954. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  117955. if (this._emitterNode) {
  117956. this._emitterNode.dispose();
  117957. }
  117958. this._emitterCreationOptions = {
  117959. kind: "Sphere",
  117960. options: options,
  117961. renderingGroupId: renderingGroupId
  117962. };
  117963. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  117964. emitterMesh.renderingGroupId = renderingGroupId;
  117965. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  117966. material.emissiveColor = options.color;
  117967. emitterMesh.material = material;
  117968. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  117969. var system = _a[_i];
  117970. system.emitter = emitterMesh;
  117971. }
  117972. this._emitterNode = emitterMesh;
  117973. };
  117974. /**
  117975. * Starts all particle systems of the set
  117976. * @param emitter defines an optional mesh to use as emitter for the particle systems
  117977. */
  117978. ParticleSystemSet.prototype.start = function (emitter) {
  117979. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  117980. var system = _a[_i];
  117981. if (emitter) {
  117982. system.emitter = emitter;
  117983. }
  117984. system.start();
  117985. }
  117986. };
  117987. /**
  117988. * Release all associated resources
  117989. */
  117990. ParticleSystemSet.prototype.dispose = function () {
  117991. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  117992. var system = _a[_i];
  117993. system.dispose();
  117994. }
  117995. this.systems = [];
  117996. if (this._emitterNode) {
  117997. this._emitterNode.dispose();
  117998. this._emitterNode = null;
  117999. }
  118000. };
  118001. /**
  118002. * Serialize the set into a JSON compatible object
  118003. * @returns a JSON compatible representation of the set
  118004. */
  118005. ParticleSystemSet.prototype.serialize = function () {
  118006. var result = {};
  118007. result.systems = [];
  118008. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  118009. var system = _a[_i];
  118010. result.systems.push(system.serialize());
  118011. }
  118012. if (this._emitterNode) {
  118013. result.emitter = this._emitterCreationOptions;
  118014. }
  118015. return result;
  118016. };
  118017. /**
  118018. * Parse a new ParticleSystemSet from a serialized source
  118019. * @param data defines a JSON compatible representation of the set
  118020. * @param scene defines the hosting scene
  118021. * @param gpu defines if we want GPU particles or CPU particles
  118022. * @returns a new ParticleSystemSet
  118023. */
  118024. ParticleSystemSet.Parse = function (data, scene, gpu) {
  118025. if (gpu === void 0) { gpu = false; }
  118026. var result = new ParticleSystemSet();
  118027. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  118028. scene = scene || BABYLON.Engine.LastCreatedScene;
  118029. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  118030. var system = _a[_i];
  118031. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  118032. }
  118033. if (data.emitter) {
  118034. var options = data.emitter.options;
  118035. switch (data.emitter.kind) {
  118036. case "Sphere":
  118037. result.setEmitterAsSphere({
  118038. diameter: options.diameter,
  118039. segments: options.segments,
  118040. color: BABYLON.Color3.FromArray(options.color)
  118041. }, data.emitter.renderingGroupId, scene);
  118042. break;
  118043. }
  118044. }
  118045. return result;
  118046. };
  118047. return ParticleSystemSet;
  118048. }());
  118049. BABYLON.ParticleSystemSet = ParticleSystemSet;
  118050. })(BABYLON || (BABYLON = {}));
  118051. //# sourceMappingURL=babylon.particleSystemSet.js.map
  118052. var BABYLON;
  118053. (function (BABYLON) {
  118054. /**
  118055. * This class is made for on one-liner static method to help creating particle system set.
  118056. */
  118057. var ParticleHelper = /** @class */ (function () {
  118058. function ParticleHelper() {
  118059. }
  118060. /**
  118061. * Create a default particle system that you can tweak
  118062. * @param emitter defines the emitter to use
  118063. * @param capacity defines the system capacity (default is 500 particles)
  118064. * @param scene defines the hosting scene
  118065. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  118066. * @returns the new Particle system
  118067. */
  118068. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  118069. if (capacity === void 0) { capacity = 500; }
  118070. if (useGPU === void 0) { useGPU = false; }
  118071. var system;
  118072. if (useGPU) {
  118073. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  118074. }
  118075. else {
  118076. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  118077. }
  118078. system.emitter = emitter;
  118079. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  118080. system.createConeEmitter(0.1, Math.PI / 4);
  118081. // Particle color
  118082. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  118083. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  118084. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  118085. // Particle Size
  118086. system.minSize = 0.1;
  118087. system.maxSize = 0.1;
  118088. // Emission speed
  118089. system.minEmitPower = 2;
  118090. system.maxEmitPower = 2;
  118091. // Update speed
  118092. system.updateSpeed = 1 / 60;
  118093. system.emitRate = 30;
  118094. return system;
  118095. };
  118096. /**
  118097. * This is the main static method (one-liner) of this helper to create different particle systems
  118098. * @param type This string represents the type to the particle system to create
  118099. * @param scene The scene where the particle system should live
  118100. * @param gpu If the system will use gpu
  118101. * @returns the ParticleSystemSet created
  118102. */
  118103. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  118104. if (gpu === void 0) { gpu = false; }
  118105. if (!scene) {
  118106. scene = BABYLON.Engine.LastCreatedScene;
  118107. }
  118108. var token = {};
  118109. scene._addPendingData(token);
  118110. return new Promise(function (resolve, reject) {
  118111. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  118112. scene._removePendingData(token);
  118113. return reject("Particle system with GPU is not supported.");
  118114. }
  118115. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  118116. scene._removePendingData(token);
  118117. var newData = JSON.parse(data.toString());
  118118. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  118119. }, undefined, undefined, undefined, function (req, exception) {
  118120. scene._removePendingData(token);
  118121. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  118122. });
  118123. });
  118124. };
  118125. /**
  118126. * Static function used to export a particle system to a ParticleSystemSet variable.
  118127. * Please note that the emitter shape is not exported
  118128. * @param systems defines the particle systems to export
  118129. * @returns the created particle system set
  118130. */
  118131. ParticleHelper.ExportSet = function (systems) {
  118132. var set = new BABYLON.ParticleSystemSet();
  118133. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  118134. var system = systems_1[_i];
  118135. set.systems.push(system);
  118136. }
  118137. return set;
  118138. };
  118139. /**
  118140. * Gets or sets base Assets URL
  118141. */
  118142. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  118143. return ParticleHelper;
  118144. }());
  118145. BABYLON.ParticleHelper = ParticleHelper;
  118146. })(BABYLON || (BABYLON = {}));
  118147. //# sourceMappingURL=babylon.particleHelper.js.map
  118148. var BABYLON;
  118149. (function (BABYLON) {
  118150. /**
  118151. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  118152. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  118153. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  118154. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  118155. */
  118156. var VideoDome = /** @class */ (function (_super) {
  118157. __extends(VideoDome, _super);
  118158. /**
  118159. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  118160. * @param name Element's name, child elements will append suffixes for their own names.
  118161. * @param urlsOrVideo defines the url(s) or the video element to use
  118162. * @param options An object containing optional or exposed sub element properties
  118163. */
  118164. function VideoDome(name, urlsOrVideo, options, scene) {
  118165. var _this = _super.call(this, name, scene) || this;
  118166. _this._useDirectMapping = false;
  118167. // set defaults and manage values
  118168. name = name || "videoDome";
  118169. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  118170. options.clickToPlay = Boolean(options.clickToPlay);
  118171. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  118172. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  118173. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  118174. if (options.useDirectMapping === undefined) {
  118175. _this._useDirectMapping = true;
  118176. }
  118177. else {
  118178. _this._useDirectMapping = options.useDirectMapping;
  118179. }
  118180. _this._setReady(false);
  118181. // create
  118182. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  118183. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  118184. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  118185. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  118186. texture.onLoadObservable.addOnce(function () {
  118187. _this._setReady(true);
  118188. });
  118189. // configure material
  118190. material.useEquirectangularFOV = true;
  118191. material.fovMultiplier = 1.0;
  118192. material.opacityFresnel = false;
  118193. if (_this._useDirectMapping) {
  118194. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118195. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118196. material.diffuseTexture = texture;
  118197. }
  118198. else {
  118199. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  118200. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118201. material.reflectionTexture = texture;
  118202. }
  118203. // configure mesh
  118204. _this._mesh.material = material;
  118205. _this._mesh.parent = _this;
  118206. // optional configuration
  118207. if (options.clickToPlay) {
  118208. scene.onPointerUp = function () {
  118209. _this._videoTexture.video.play();
  118210. };
  118211. }
  118212. return _this;
  118213. }
  118214. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  118215. /**
  118216. * Gets the video texture being displayed on the sphere
  118217. */
  118218. get: function () {
  118219. return this._videoTexture;
  118220. },
  118221. enumerable: true,
  118222. configurable: true
  118223. });
  118224. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  118225. /**
  118226. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  118227. * Also see the options.resolution property.
  118228. */
  118229. get: function () {
  118230. return this._material.fovMultiplier;
  118231. },
  118232. set: function (value) {
  118233. this._material.fovMultiplier = value;
  118234. },
  118235. enumerable: true,
  118236. configurable: true
  118237. });
  118238. /**
  118239. * Releases resources associated with this node.
  118240. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  118241. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  118242. */
  118243. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  118244. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  118245. this._videoTexture.dispose();
  118246. this._mesh.dispose();
  118247. this._material.dispose();
  118248. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  118249. };
  118250. return VideoDome;
  118251. }(BABYLON.TransformNode));
  118252. BABYLON.VideoDome = VideoDome;
  118253. })(BABYLON || (BABYLON = {}));
  118254. //# sourceMappingURL=babylon.videoDome.js.map
  118255. var BABYLON;
  118256. (function (BABYLON) {
  118257. /**
  118258. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  118259. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  118260. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  118261. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  118262. */
  118263. var PhotoDome = /** @class */ (function (_super) {
  118264. __extends(PhotoDome, _super);
  118265. /**
  118266. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  118267. * @param name Element's name, child elements will append suffixes for their own names.
  118268. * @param urlsOfPhoto defines the url of the photo to display
  118269. * @param options defines an object containing optional or exposed sub element properties
  118270. * @param onError defines a callback called when an error occured while loading the texture
  118271. */
  118272. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  118273. if (onError === void 0) { onError = null; }
  118274. var _this = _super.call(this, name, scene) || this;
  118275. _this._useDirectMapping = false;
  118276. /**
  118277. * Observable raised when an error occured while loading the 360 image
  118278. */
  118279. _this.onLoadErrorObservable = new BABYLON.Observable();
  118280. // set defaults and manage values
  118281. name = name || "photoDome";
  118282. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  118283. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  118284. if (options.useDirectMapping === undefined) {
  118285. _this._useDirectMapping = true;
  118286. }
  118287. else {
  118288. _this._useDirectMapping = options.useDirectMapping;
  118289. }
  118290. _this._setReady(false);
  118291. // create
  118292. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  118293. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  118294. // configure material
  118295. material.opacityFresnel = false;
  118296. material.useEquirectangularFOV = true;
  118297. material.fovMultiplier = 1.0;
  118298. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  118299. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  118300. if (onError) {
  118301. onError(message, exception);
  118302. }
  118303. });
  118304. _this.photoTexture.onLoadObservable.addOnce(function () {
  118305. _this._setReady(true);
  118306. });
  118307. // configure mesh
  118308. _this._mesh.material = material;
  118309. _this._mesh.parent = _this;
  118310. return _this;
  118311. }
  118312. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  118313. /**
  118314. * Gets or sets the texture being displayed on the sphere
  118315. */
  118316. get: function () {
  118317. return this._photoTexture;
  118318. },
  118319. set: function (value) {
  118320. if (this._photoTexture === value) {
  118321. return;
  118322. }
  118323. this._photoTexture = value;
  118324. if (this._useDirectMapping) {
  118325. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118326. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118327. this._material.diffuseTexture = this._photoTexture;
  118328. }
  118329. else {
  118330. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  118331. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118332. this._material.reflectionTexture = this._photoTexture;
  118333. }
  118334. },
  118335. enumerable: true,
  118336. configurable: true
  118337. });
  118338. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  118339. /**
  118340. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  118341. * Also see the options.resolution property.
  118342. */
  118343. get: function () {
  118344. return this._material.fovMultiplier;
  118345. },
  118346. set: function (value) {
  118347. this._material.fovMultiplier = value;
  118348. },
  118349. enumerable: true,
  118350. configurable: true
  118351. });
  118352. /**
  118353. * Releases resources associated with this node.
  118354. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  118355. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  118356. */
  118357. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  118358. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  118359. this._photoTexture.dispose();
  118360. this._mesh.dispose();
  118361. this._material.dispose();
  118362. this.onLoadErrorObservable.clear();
  118363. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  118364. };
  118365. return PhotoDome;
  118366. }(BABYLON.TransformNode));
  118367. BABYLON.PhotoDome = PhotoDome;
  118368. })(BABYLON || (BABYLON = {}));
  118369. //# sourceMappingURL=babylon.photoDome.js.map
  118370. var BABYLON;
  118371. (function (BABYLON) {
  118372. /** @hidden */
  118373. var _OcclusionDataStorage = /** @class */ (function () {
  118374. function _OcclusionDataStorage() {
  118375. /** @hidden */
  118376. this.occlusionInternalRetryCounter = 0;
  118377. /** @hidden */
  118378. this.isOcclusionQueryInProgress = false;
  118379. /** @hidden */
  118380. this.isOccluded = false;
  118381. /** @hidden */
  118382. this.occlusionRetryCount = -1;
  118383. /** @hidden */
  118384. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  118385. /** @hidden */
  118386. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  118387. }
  118388. return _OcclusionDataStorage;
  118389. }());
  118390. BABYLON.Engine.prototype.createQuery = function () {
  118391. return this._gl.createQuery();
  118392. };
  118393. BABYLON.Engine.prototype.deleteQuery = function (query) {
  118394. this._gl.deleteQuery(query);
  118395. return this;
  118396. };
  118397. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  118398. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  118399. };
  118400. BABYLON.Engine.prototype.getQueryResult = function (query) {
  118401. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  118402. };
  118403. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  118404. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  118405. this._gl.beginQuery(glAlgorithm, query);
  118406. return this;
  118407. };
  118408. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  118409. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  118410. this._gl.endQuery(glAlgorithm);
  118411. return this;
  118412. };
  118413. BABYLON.Engine.prototype._createTimeQuery = function () {
  118414. var timerQuery = this.getCaps().timerQuery;
  118415. if (timerQuery.createQueryEXT) {
  118416. return timerQuery.createQueryEXT();
  118417. }
  118418. return this.createQuery();
  118419. };
  118420. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  118421. var timerQuery = this.getCaps().timerQuery;
  118422. if (timerQuery.deleteQueryEXT) {
  118423. timerQuery.deleteQueryEXT(query);
  118424. return;
  118425. }
  118426. this.deleteQuery(query);
  118427. };
  118428. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  118429. var timerQuery = this.getCaps().timerQuery;
  118430. if (timerQuery.getQueryObjectEXT) {
  118431. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  118432. }
  118433. return this.getQueryResult(query);
  118434. };
  118435. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  118436. var timerQuery = this.getCaps().timerQuery;
  118437. if (timerQuery.getQueryObjectEXT) {
  118438. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  118439. }
  118440. return this.isQueryResultAvailable(query);
  118441. };
  118442. BABYLON.Engine.prototype.startTimeQuery = function () {
  118443. var caps = this.getCaps();
  118444. var timerQuery = caps.timerQuery;
  118445. if (!timerQuery) {
  118446. return null;
  118447. }
  118448. var token = new BABYLON._TimeToken();
  118449. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  118450. if (caps.canUseTimestampForTimerQuery) {
  118451. token._startTimeQuery = this._createTimeQuery();
  118452. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  118453. }
  118454. else {
  118455. if (this._currentNonTimestampToken) {
  118456. return this._currentNonTimestampToken;
  118457. }
  118458. token._timeElapsedQuery = this._createTimeQuery();
  118459. if (timerQuery.beginQueryEXT) {
  118460. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  118461. }
  118462. else {
  118463. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  118464. }
  118465. this._currentNonTimestampToken = token;
  118466. }
  118467. return token;
  118468. };
  118469. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  118470. var caps = this.getCaps();
  118471. var timerQuery = caps.timerQuery;
  118472. if (!timerQuery || !token) {
  118473. return -1;
  118474. }
  118475. if (caps.canUseTimestampForTimerQuery) {
  118476. if (!token._startTimeQuery) {
  118477. return -1;
  118478. }
  118479. if (!token._endTimeQuery) {
  118480. token._endTimeQuery = this._createTimeQuery();
  118481. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  118482. }
  118483. }
  118484. else if (!token._timeElapsedQueryEnded) {
  118485. if (!token._timeElapsedQuery) {
  118486. return -1;
  118487. }
  118488. if (timerQuery.endQueryEXT) {
  118489. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  118490. }
  118491. else {
  118492. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  118493. }
  118494. token._timeElapsedQueryEnded = true;
  118495. }
  118496. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  118497. var available = false;
  118498. if (token._endTimeQuery) {
  118499. available = this._getTimeQueryAvailability(token._endTimeQuery);
  118500. }
  118501. else if (token._timeElapsedQuery) {
  118502. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  118503. }
  118504. if (available && !disjoint) {
  118505. var result = 0;
  118506. if (caps.canUseTimestampForTimerQuery) {
  118507. if (!token._startTimeQuery || !token._endTimeQuery) {
  118508. return -1;
  118509. }
  118510. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  118511. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  118512. result = timeEnd - timeStart;
  118513. this._deleteTimeQuery(token._startTimeQuery);
  118514. this._deleteTimeQuery(token._endTimeQuery);
  118515. token._startTimeQuery = null;
  118516. token._endTimeQuery = null;
  118517. }
  118518. else {
  118519. if (!token._timeElapsedQuery) {
  118520. return -1;
  118521. }
  118522. result = this._getTimeQueryResult(token._timeElapsedQuery);
  118523. this._deleteTimeQuery(token._timeElapsedQuery);
  118524. token._timeElapsedQuery = null;
  118525. token._timeElapsedQueryEnded = false;
  118526. this._currentNonTimestampToken = null;
  118527. }
  118528. return result;
  118529. }
  118530. return -1;
  118531. };
  118532. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  118533. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  118534. };
  118535. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  118536. get: function () {
  118537. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  118538. },
  118539. enumerable: false,
  118540. configurable: true
  118541. });
  118542. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  118543. get: function () {
  118544. if (!this.__occlusionDataStorage) {
  118545. this.__occlusionDataStorage = new _OcclusionDataStorage();
  118546. }
  118547. return this.__occlusionDataStorage;
  118548. },
  118549. enumerable: false,
  118550. configurable: true
  118551. });
  118552. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  118553. get: function () {
  118554. return this._occlusionDataStorage.isOccluded;
  118555. },
  118556. set: function (value) {
  118557. this._occlusionDataStorage.isOccluded = value;
  118558. },
  118559. enumerable: true,
  118560. configurable: true
  118561. });
  118562. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  118563. get: function () {
  118564. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  118565. },
  118566. set: function (value) {
  118567. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  118568. },
  118569. enumerable: true,
  118570. configurable: true
  118571. });
  118572. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  118573. get: function () {
  118574. return this._occlusionDataStorage.occlusionType;
  118575. },
  118576. set: function (value) {
  118577. this._occlusionDataStorage.occlusionType = value;
  118578. },
  118579. enumerable: true,
  118580. configurable: true
  118581. });
  118582. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  118583. get: function () {
  118584. return this._occlusionDataStorage.occlusionRetryCount;
  118585. },
  118586. set: function (value) {
  118587. this._occlusionDataStorage.occlusionRetryCount = value;
  118588. },
  118589. enumerable: true,
  118590. configurable: true
  118591. });
  118592. // We also need to update AbstractMesh as there is a portion of the code there
  118593. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  118594. var dataStorage = this._occlusionDataStorage;
  118595. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  118596. dataStorage.isOccluded = false;
  118597. return false;
  118598. }
  118599. var engine = this.getEngine();
  118600. if (engine.webGLVersion < 2) {
  118601. dataStorage.isOccluded = false;
  118602. return false;
  118603. }
  118604. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  118605. dataStorage.isOccluded = false;
  118606. return false;
  118607. }
  118608. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  118609. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  118610. if (isOcclusionQueryAvailable) {
  118611. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  118612. dataStorage.isOcclusionQueryInProgress = false;
  118613. dataStorage.occlusionInternalRetryCounter = 0;
  118614. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  118615. }
  118616. else {
  118617. dataStorage.occlusionInternalRetryCounter++;
  118618. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  118619. dataStorage.isOcclusionQueryInProgress = false;
  118620. dataStorage.occlusionInternalRetryCounter = 0;
  118621. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  118622. // if strict continue the last state of the object.
  118623. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  118624. }
  118625. else {
  118626. return false;
  118627. }
  118628. }
  118629. }
  118630. var scene = this.getScene();
  118631. if (scene.getBoundingBoxRenderer) {
  118632. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  118633. if (!this._occlusionQuery) {
  118634. this._occlusionQuery = engine.createQuery();
  118635. }
  118636. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  118637. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  118638. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  118639. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  118640. }
  118641. return dataStorage.isOccluded;
  118642. };
  118643. })(BABYLON || (BABYLON = {}));
  118644. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  118645. var BABYLON;
  118646. (function (BABYLON) {
  118647. /**
  118648. * Class used to generate noise procedural textures
  118649. */
  118650. var NoiseProceduralTexture = /** @class */ (function (_super) {
  118651. __extends(NoiseProceduralTexture, _super);
  118652. /**
  118653. * Creates a new NoiseProceduralTexture
  118654. * @param name defines the name fo the texture
  118655. * @param size defines the size of the texture (default is 256)
  118656. * @param scene defines the hosting scene
  118657. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  118658. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  118659. */
  118660. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  118661. if (size === void 0) { size = 256; }
  118662. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  118663. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  118664. _this._time = 0;
  118665. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  118666. _this.brightness = 0.2;
  118667. /** Defines the number of octaves to process */
  118668. _this.octaves = 3;
  118669. /** Defines the level of persistence (0.8 by default) */
  118670. _this.persistence = 0.8;
  118671. /** Gets or sets animation speed factor (default is 1) */
  118672. _this.animationSpeedFactor = 1;
  118673. _this.autoClear = false;
  118674. _this._updateShaderUniforms();
  118675. return _this;
  118676. }
  118677. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  118678. var scene = this.getScene();
  118679. if (!scene) {
  118680. return;
  118681. }
  118682. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  118683. this.setFloat("brightness", this.brightness);
  118684. this.setFloat("persistence", this.persistence);
  118685. this.setFloat("timeScale", this._time);
  118686. };
  118687. NoiseProceduralTexture.prototype._getDefines = function () {
  118688. return "#define OCTAVES " + (this.octaves | 0);
  118689. };
  118690. /** Generate the current state of the procedural texture */
  118691. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  118692. this._updateShaderUniforms();
  118693. _super.prototype.render.call(this, useCameraPostProcess);
  118694. };
  118695. /**
  118696. * Serializes this noise procedural texture
  118697. * @returns a serialized noise procedural texture object
  118698. */
  118699. NoiseProceduralTexture.prototype.serialize = function () {
  118700. var serializationObject = {};
  118701. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  118702. serializationObject.brightness = this.brightness;
  118703. serializationObject.octaves = this.octaves;
  118704. serializationObject.persistence = this.persistence;
  118705. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  118706. serializationObject.size = this.getSize().width;
  118707. serializationObject.generateMipMaps = this._generateMipMaps;
  118708. return serializationObject;
  118709. };
  118710. /**
  118711. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  118712. * @param parsedTexture defines parsed texture data
  118713. * @param scene defines the current scene
  118714. * @param rootUrl defines the root URL containing noise procedural texture information
  118715. * @returns a parsed NoiseProceduralTexture
  118716. */
  118717. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  118718. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  118719. texture.brightness = parsedTexture.brightness;
  118720. texture.octaves = parsedTexture.octaves;
  118721. texture.persistence = parsedTexture.persistence;
  118722. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  118723. return texture;
  118724. };
  118725. return NoiseProceduralTexture;
  118726. }(BABYLON.ProceduralTexture));
  118727. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  118728. })(BABYLON || (BABYLON = {}));
  118729. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  118730. var __assign = (this && this.__assign) || function () {
  118731. __assign = Object.assign || function(t) {
  118732. for (var s, i = 1, n = arguments.length; i < n; i++) {
  118733. s = arguments[i];
  118734. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  118735. t[p] = s[p];
  118736. }
  118737. return t;
  118738. };
  118739. return __assign.apply(this, arguments);
  118740. };
  118741. var BABYLON;
  118742. (function (BABYLON) {
  118743. /**
  118744. * This can helps recording videos from BabylonJS.
  118745. * This is based on the available WebRTC functionalities of the browser.
  118746. *
  118747. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  118748. */
  118749. var VideoRecorder = /** @class */ (function () {
  118750. /**
  118751. * Create a new VideoCapture object which can help converting what you see in Babylon to
  118752. * a video file.
  118753. * @param engine Defines the BabylonJS Engine you wish to record
  118754. * @param options Defines options that can be used to customized the capture
  118755. */
  118756. function VideoRecorder(engine, options) {
  118757. if (options === void 0) { options = null; }
  118758. if (!VideoRecorder.IsSupported(engine)) {
  118759. throw "Your browser does not support recording so far.";
  118760. }
  118761. var canvas = engine.getRenderingCanvas();
  118762. if (!canvas) {
  118763. throw "The babylon engine must have a canvas to be recorded";
  118764. }
  118765. this._canvas = canvas;
  118766. this._canvas.isRecording = false;
  118767. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  118768. var stream = this._canvas.captureStream(this._options.fps);
  118769. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  118770. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  118771. this._mediaRecorder.onerror = this._handleError.bind(this);
  118772. this._mediaRecorder.onstop = this._handleStop.bind(this);
  118773. }
  118774. /**
  118775. * Returns wehther or not the VideoRecorder is available in your browser.
  118776. * @param engine Defines the Babylon Engine to check the support for
  118777. * @returns true if supported otherwise false
  118778. */
  118779. VideoRecorder.IsSupported = function (engine) {
  118780. var canvas = engine.getRenderingCanvas();
  118781. return (!!canvas && typeof canvas.captureStream === "function");
  118782. };
  118783. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  118784. /**
  118785. * True wether a recording is already in progress.
  118786. */
  118787. get: function () {
  118788. return !!this._canvas && this._canvas.isRecording;
  118789. },
  118790. enumerable: true,
  118791. configurable: true
  118792. });
  118793. /**
  118794. * Stops the current recording before the default capture timeout passed in the startRecording
  118795. * functions.
  118796. */
  118797. VideoRecorder.prototype.stopRecording = function () {
  118798. if (!this._canvas || !this._mediaRecorder) {
  118799. return;
  118800. }
  118801. if (!this.isRecording) {
  118802. return;
  118803. }
  118804. this._canvas.isRecording = false;
  118805. this._mediaRecorder.stop();
  118806. };
  118807. /**
  118808. * Starts recording the canvas for a max duration specified in parameters.
  118809. * @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.
  118810. * @param maxDuration Defines the maximum recording time in seconds.
  118811. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  118812. * @return a promise callback at the end of the recording with the video data in Blob.
  118813. */
  118814. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  118815. var _this = this;
  118816. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  118817. if (maxDuration === void 0) { maxDuration = 7; }
  118818. if (!this._canvas || !this._mediaRecorder) {
  118819. throw "Recorder has already been disposed";
  118820. }
  118821. if (this.isRecording) {
  118822. throw "Recording already in progress";
  118823. }
  118824. if (maxDuration > 0) {
  118825. setTimeout(function () {
  118826. _this.stopRecording();
  118827. }, maxDuration * 1000);
  118828. }
  118829. this._fileName = fileName;
  118830. this._recordedChunks = [];
  118831. this._resolve = null;
  118832. this._reject = null;
  118833. this._canvas.isRecording = true;
  118834. this._mediaRecorder.start(this._options.recordChunckSize);
  118835. return new Promise(function (resolve, reject) {
  118836. _this._resolve = resolve;
  118837. _this._reject = reject;
  118838. });
  118839. };
  118840. /**
  118841. * Releases internal resources used during the recording.
  118842. */
  118843. VideoRecorder.prototype.dispose = function () {
  118844. this._canvas = null;
  118845. this._mediaRecorder = null;
  118846. this._recordedChunks = [];
  118847. this._fileName = null;
  118848. this._resolve = null;
  118849. this._reject = null;
  118850. };
  118851. VideoRecorder.prototype._handleDataAvailable = function (event) {
  118852. if (event.data.size > 0) {
  118853. this._recordedChunks.push(event.data);
  118854. }
  118855. };
  118856. VideoRecorder.prototype._handleError = function (event) {
  118857. this.stopRecording();
  118858. if (this._reject) {
  118859. this._reject(event.error);
  118860. }
  118861. else {
  118862. throw new event.error();
  118863. }
  118864. };
  118865. VideoRecorder.prototype._handleStop = function () {
  118866. this.stopRecording();
  118867. var superBuffer = new Blob(this._recordedChunks);
  118868. if (this._resolve) {
  118869. this._resolve(superBuffer);
  118870. }
  118871. window.URL.createObjectURL(superBuffer);
  118872. if (this._fileName) {
  118873. BABYLON.Tools.Download(superBuffer, this._fileName);
  118874. }
  118875. };
  118876. VideoRecorder._defaultOptions = {
  118877. mimeType: "video/webm",
  118878. fps: 25,
  118879. recordChunckSize: 3000
  118880. };
  118881. return VideoRecorder;
  118882. }());
  118883. BABYLON.VideoRecorder = VideoRecorder;
  118884. })(BABYLON || (BABYLON = {}));
  118885. //# sourceMappingURL=babylon.videoRecorder.js.map
  118886. var BABYLON;
  118887. (function (BABYLON) {
  118888. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  118889. if (replace === void 0) { replace = false; }
  118890. // Dispose existing light in replace mode.
  118891. if (replace) {
  118892. if (this.lights) {
  118893. for (var i = 0; i < this.lights.length; i++) {
  118894. this.lights[i].dispose();
  118895. }
  118896. }
  118897. }
  118898. // Light
  118899. if (this.lights.length === 0) {
  118900. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  118901. }
  118902. };
  118903. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  118904. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  118905. if (replace === void 0) { replace = false; }
  118906. if (attachCameraControls === void 0) { attachCameraControls = false; }
  118907. // Dispose existing camera in replace mode.
  118908. if (replace) {
  118909. if (this.activeCamera) {
  118910. this.activeCamera.dispose();
  118911. this.activeCamera = null;
  118912. }
  118913. }
  118914. // Camera
  118915. if (!this.activeCamera) {
  118916. var worldExtends = this.getWorldExtends();
  118917. var worldSize = worldExtends.max.subtract(worldExtends.min);
  118918. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  118919. var camera;
  118920. var radius = worldSize.length() * 1.5;
  118921. // empty scene scenario!
  118922. if (!isFinite(radius)) {
  118923. radius = 1;
  118924. worldCenter.copyFromFloats(0, 0, 0);
  118925. }
  118926. if (createArcRotateCamera) {
  118927. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  118928. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  118929. arcRotateCamera.wheelPrecision = 100 / radius;
  118930. camera = arcRotateCamera;
  118931. }
  118932. else {
  118933. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  118934. freeCamera.setTarget(worldCenter);
  118935. camera = freeCamera;
  118936. }
  118937. camera.minZ = radius * 0.01;
  118938. camera.maxZ = radius * 1000;
  118939. camera.speed = radius * 0.2;
  118940. this.activeCamera = camera;
  118941. var canvas = this.getEngine().getRenderingCanvas();
  118942. if (attachCameraControls && canvas) {
  118943. camera.attachControl(canvas);
  118944. }
  118945. }
  118946. };
  118947. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  118948. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  118949. if (replace === void 0) { replace = false; }
  118950. if (attachCameraControls === void 0) { attachCameraControls = false; }
  118951. this.createDefaultLight(replace);
  118952. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  118953. };
  118954. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  118955. if (pbr === void 0) { pbr = false; }
  118956. if (scale === void 0) { scale = 1000; }
  118957. if (blur === void 0) { blur = 0; }
  118958. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  118959. if (!environmentTexture) {
  118960. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  118961. return null;
  118962. }
  118963. if (setGlobalEnvTexture) {
  118964. if (environmentTexture) {
  118965. this.environmentTexture = environmentTexture;
  118966. }
  118967. }
  118968. // Skybox
  118969. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  118970. if (pbr) {
  118971. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  118972. hdrSkyboxMaterial.backFaceCulling = false;
  118973. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  118974. if (hdrSkyboxMaterial.reflectionTexture) {
  118975. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  118976. }
  118977. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  118978. hdrSkyboxMaterial.disableLighting = true;
  118979. hdrSkyboxMaterial.twoSidedLighting = true;
  118980. hdrSkybox.infiniteDistance = true;
  118981. hdrSkybox.material = hdrSkyboxMaterial;
  118982. }
  118983. else {
  118984. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  118985. skyboxMaterial.backFaceCulling = false;
  118986. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  118987. if (skyboxMaterial.reflectionTexture) {
  118988. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  118989. }
  118990. skyboxMaterial.disableLighting = true;
  118991. hdrSkybox.infiniteDistance = true;
  118992. hdrSkybox.material = skyboxMaterial;
  118993. }
  118994. return hdrSkybox;
  118995. };
  118996. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  118997. if (BABYLON.EnvironmentHelper) {
  118998. return new BABYLON.EnvironmentHelper(options, this);
  118999. }
  119000. return null;
  119001. };
  119002. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  119003. if (webVROptions === void 0) { webVROptions = {}; }
  119004. return new BABYLON.VRExperienceHelper(this, webVROptions);
  119005. };
  119006. BABYLON.Scene.prototype.createDefaultXRExperienceAsync = function () {
  119007. var _this = this;
  119008. return BABYLON.WebXRExperienceHelper.CreateAsync(this).then(function (helper) {
  119009. var outputCanvas = new BABYLON.WebXRManagedOutputCanvas(helper);
  119010. return BABYLON.WebXREnterExitUI.CreateAsync(_this, helper, { outputCanvasContext: outputCanvas.canvasContext })
  119011. .then(function (ui) {
  119012. new BABYLON.WebXRInput(helper);
  119013. return helper;
  119014. });
  119015. });
  119016. };
  119017. })(BABYLON || (BABYLON = {}));
  119018. //# sourceMappingURL=babylon.sceneHelpers.js.map
  119019. 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"};
  119020. 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};"};